id
stringlengths 40
40
| text
stringlengths 29
2.03k
| original_text
stringlengths 3
154k
| subdomain
stringclasses 20
values | metadata
dict |
---|---|---|---|---|
3517e4f50b1c37e089cff721af8b4f73eae35633
|
Stackoverflow Stackexchange
Q: Disable a text edit field in flutter I need to disable TextFormField occasionally. I couldn't find a flag in the widget, or the controller to simply make it read-only or disable.
What is the best way to do it?
A: It has enabled key, this is doing fine for me.
TextFormField(
enabled: false,
)
|
Q: Disable a text edit field in flutter I need to disable TextFormField occasionally. I couldn't find a flag in the widget, or the controller to simply make it read-only or disable.
What is the best way to do it?
A: It has enabled key, this is doing fine for me.
TextFormField(
enabled: false,
)
A: TextField and TextFormField both have an argument called enabled. You can control it using a boolean variable. enabled=true means it will act as an editing text field whereas enabled=false will disable the TextField.
A: For that... TextField has two properties:
TextField(
readOnly: true,
enabled: false,
)
1- If you desire to disable the TextField typing and taping set [enabled: false]
2- If you desire to disable only TextField typing set [readOnly: true]
A: Similar to readonly like in html
TextField(
enableInteractiveSelection: false,
focusNode: FocusNode(),
)
This can response to onTap.
Similar to disabled like in html
TextField(
enable: false
)
This can not response to onTap.
A: This isn't a feature that is currently provided by the framework, but you can use a FocusScope to prevent a TextFormField from requesting focus.
Here's what it looks like when it's disabled.
(with hint text)
(with a readonly value)
Here's what it looks like when it's enabled.
(with focus)
(without focus)
Code for this is below:
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
home: new HomePage(),
));
}
class HomePage extends StatefulWidget {
HomePageState createState() => new HomePageState();
}
class HomePageState extends State<HomePage> {
TextEditingController _controller = new TextEditingController();
bool _enabled = false;
@override
Widget build(BuildContext context) {
ThemeData theme = Theme.of(context);
return new Scaffold(
appBar: new AppBar(
title: new Text('Disabled Text'),
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.free_breakfast),
onPressed: () {
setState(() {
_enabled = !_enabled;
});
}
),
body: new Center(
child: new Container(
margin: const EdgeInsets.all(10.0),
child: _enabled ?
new TextFormField(controller: _controller) :
new FocusScope(
node: new FocusScopeNode(),
child: new TextFormField(
controller: _controller,
style: theme.textTheme.subhead.copyWith(
color: theme.disabledColor,
),
decoration: new InputDecoration(
hintText: _enabled ? 'Type something' : 'You cannot focus me',
),
),
),
),
),
);
}
}
A: This is another way of somehow disabling a TextField but keeping it's functionality. I mean for onTap usage
TextField(
enableInteractiveSelection: false,
onTap: () { FocusScope.of(context).requestFocus(new FocusNode()); },
)
*
*enableInteractiveSelection
will disable content selection of TextField
*FocusScope.of(context).requestFocus(new FocusNode());
change the focus to an unused focus node
Using this way, you can still touch TextField but can't type in it or select it's content. Believe me it's going to be useful sometimes ( datepicker, timepicker, ... ) :)
A: Use readOnly:true is correct. But if you still want focus to this text field you can follow below code:
TextFormField(
showCursor: true,//add this line
readOnly: true
)
And if you want hide text pointer (cursor), you need set enableInteractiveSelection to false.
A: TextField
(
enable: false
)
Or
TextFormField(
enable: false
)
if you use InputDecoration don't forget to set disabledBorder like this
TextFormField(
enabled: false,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
borderSide: BorderSide(color: Colors.blue),
),
disabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
borderSide: BorderSide(color: Colors.gray),
),
filled: true,
),
);
A: I have used a combination of readOnly and enableInteractiveSelection properties to achieve the desired behavior on TextField.
TextField(
readOnly: true,
enableInteractiveSelection: true,
onTap: () {
do_something(),
},
)
With enableInteractiveSelection set to true, it will allow onTap() to function as normal.
A: There is another way this can be achieved which also does not cause this issue. Hope this might help someone.
Create AlwaysDisabledFocusNode and pass it to the focusNode property of a TextField.
class AlwaysDisabledFocusNode extends FocusNode {
@override
bool get hasFocus => false;
}
then
new TextField(
enableInteractiveSelection: false, // will disable paste operation
focusNode: new AlwaysDisabledFocusNode(),
...
...
)
Update:
TextField now has enabled property. Where you can just disable the TextField like
new TextField(
enabled: false,
...
...
)
Note: This will also disable icon associated with text input.
A: TextFormField(
readOnly: true,
)
A: There is now a way to disable TextField and TextFormField. See github here.
Use it like this:
TextField(enabled: false)
A: I tried using FocuseNode(), enabled = false yet not working,
Instead of that I use a widget called AbsorbPointer. It's use for preventing a widget from touch or tap, I wrap my TextFormField or other widget inside AbsordPointer Widgets and give a parameter to disable from touch
Example
AbsorbPointer(
absorbing: true, //To disable from touch use false while **true** for otherwise
child: Your WidgetsName
);
A: Use readOnly: true
TextField(
readOnly: true,
controller: controller,
obscureText: obscureText,
onChanged: (value) {
onValueChange();
},
style: TextStyle(
color: ColorResource.COLOR_292828,
fontFamily: Font.AvenirLTProMedium.value,
fontSize: ScreenUtil().setHeight(Size.FOURTEEN)),
decoration: InputDecoration(
border: InputBorder.none,
hintText: hint,
hintStyle: TextStyle(
fontSize: ScreenUtil().setHeight(Size.FOURTEEN),
color: ColorResource.COLOR_HINT,
fontFamily: Font.AvenirLTProBook.value)),
),
A: Remove native keyboard then focus TextField programmaticaly (for example, after click emoji button):
FocusScope.of(context).requestFocus(titleFocusNode);
titleFocusNode.consumeKeyboardToken();
A: It's working for me
TextField(
readOnly: true,
onChanged: (value) { },
)
|
stackoverflow
|
{
"language": "en",
"length": 805,
"provenance": "stackexchange_0000F.jsonl.gz:848282",
"question_score": "108",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44490622"
}
|
41b4df41799ceb74a9227b7a20ee108955aec03d
|
Stackoverflow Stackexchange
Q: Source maps in webpack + closure compiler I would like to use SourceMaps generated by Closure Compiler using Webpack but I cant figure out how to do it.
Here is my webpack config:
const ClosureCompiler = require('google-closure-compiler-js').webpack;
module.exports = {
devtool: 'source-map',
entry: './src/app.js',
output: {
path: __dirname + "/build/",
filename: "bundle.js",
//sourceMapFilename: "./app.js.map",
},
plugins: [
new ClosureCompiler({
compiler: {
language_in: 'ECMASCRIPT5',
language_out: 'ECMASCRIPT5',
compilation_level: 'ADVANCED',
create_source_map: __dirname + './output.js.map'
},
concurrency: 3,
})
]
};
When I run webpack, nothing happen. Why? What am I doing wrong?
Thank you for your help.
A: Using the latest version of google-closure-compiler-js (20170910.0.1), I was able to get it to work using the following options:
plugins: [
new ClosureCompiler({
options: {
languageIn: 'ECMASCRIPT6',
languageOut: 'ECMASCRIPT5',
compilationLevel: 'ADVANCED',
createSourceMap: true
}
})
]
|
Q: Source maps in webpack + closure compiler I would like to use SourceMaps generated by Closure Compiler using Webpack but I cant figure out how to do it.
Here is my webpack config:
const ClosureCompiler = require('google-closure-compiler-js').webpack;
module.exports = {
devtool: 'source-map',
entry: './src/app.js',
output: {
path: __dirname + "/build/",
filename: "bundle.js",
//sourceMapFilename: "./app.js.map",
},
plugins: [
new ClosureCompiler({
compiler: {
language_in: 'ECMASCRIPT5',
language_out: 'ECMASCRIPT5',
compilation_level: 'ADVANCED',
create_source_map: __dirname + './output.js.map'
},
concurrency: 3,
})
]
};
When I run webpack, nothing happen. Why? What am I doing wrong?
Thank you for your help.
A: Using the latest version of google-closure-compiler-js (20170910.0.1), I was able to get it to work using the following options:
plugins: [
new ClosureCompiler({
options: {
languageIn: 'ECMASCRIPT6',
languageOut: 'ECMASCRIPT5',
compilationLevel: 'ADVANCED',
createSourceMap: true
}
})
]
|
stackoverflow
|
{
"language": "en",
"length": 132,
"provenance": "stackexchange_0000F.jsonl.gz:848296",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44490647"
}
|
9d6e6e45e61ffe0264e58fadee6174ab82836c46
|
Stackoverflow Stackexchange
Q: Keras auto generate batch sizes Is there a way to auto-generate the batch size based on the GPU's memory in keras? As far as I know, the batch size is mainly used to tweak how large the model uses up the vram. Currently, I just use trial and error to set a good batch size but I don't know if there is an easier way. This works okay, but it is a little tedious. If I am trying to run multiple different models where I can leave my computer running for multiple days, I'd like it to be most efficient with every model.
Edit:
Some pseudo code
# What I currently do
batch = 32
model.fit(x_train, y_train, batch_size=batch)
# here I have to manually change batch to maximize my gpu
# What I would prefer to do
model.fit(x_train, y_train, batch_size='auto')
# where the auto takes into account the size of my gpu
# and adjusts the batch_size automatically
|
Q: Keras auto generate batch sizes Is there a way to auto-generate the batch size based on the GPU's memory in keras? As far as I know, the batch size is mainly used to tweak how large the model uses up the vram. Currently, I just use trial and error to set a good batch size but I don't know if there is an easier way. This works okay, but it is a little tedious. If I am trying to run multiple different models where I can leave my computer running for multiple days, I'd like it to be most efficient with every model.
Edit:
Some pseudo code
# What I currently do
batch = 32
model.fit(x_train, y_train, batch_size=batch)
# here I have to manually change batch to maximize my gpu
# What I would prefer to do
model.fit(x_train, y_train, batch_size='auto')
# where the auto takes into account the size of my gpu
# and adjusts the batch_size automatically
|
stackoverflow
|
{
"language": "en",
"length": 159,
"provenance": "stackexchange_0000F.jsonl.gz:848298",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44490651"
}
|
df9ec8d8cc0c5d4b9f71c873c241587ceed97743
|
Stackoverflow Stackexchange
Q: How to run a Jenkins job on multiple virtual servers? I have installed Jenkins on a server ,by default the job will run on that server only .My requirement is from my Jenkins how I can run the the same job on to multiple server ?How it will ssh to other servers ? I am new to Jenkins,Please help .Basically my aim is to deploy a application on to multiple servers .
A: Ansible is the best way for this.
Ansible :
Install Ansible in the same server where Jenkins get installed.
Configure the multiple servers details in the host file under a single name.
Mention the jobs in Ansible-playbook which will get executed in all the mentioned servers.
internal process: it will run the job in the multiple servers by ssh
in to it
or
use shell script in the Jenkins installed server and use shell command along with ssh username@ip "#cmd" //mulitple server ip
|
Q: How to run a Jenkins job on multiple virtual servers? I have installed Jenkins on a server ,by default the job will run on that server only .My requirement is from my Jenkins how I can run the the same job on to multiple server ?How it will ssh to other servers ? I am new to Jenkins,Please help .Basically my aim is to deploy a application on to multiple servers .
A: Ansible is the best way for this.
Ansible :
Install Ansible in the same server where Jenkins get installed.
Configure the multiple servers details in the host file under a single name.
Mention the jobs in Ansible-playbook which will get executed in all the mentioned servers.
internal process: it will run the job in the multiple servers by ssh
in to it
or
use shell script in the Jenkins installed server and use shell command along with ssh username@ip "#cmd" //mulitple server ip
A: You may use any of the configuration management tool like ansible, chef or capistrano as jenkins jobs so that they can do your work with jenkins. You can mention the number of servers under the capistrano cookbook and whenever you will build the job it will run your task on all servers.
There is also a tool like pssh(parallel ssh), In case you want to use ssh.
A: You can use the master-slave Concept. Install jenkins slave in all other machines, i.e in your case the other application servers. You can find more about Jenkins master slave concept from here.
You can then use the same job to run on other application servers.
A: I think by using single job with post build steps you can deploy on multiple servers.
Let me know in case if any corrections
A: Using Master-Slave Concept, You can add Jenkins slave agent on multiple slave nodes, so you can deploy on them.
You can deploy in two ways, Either using Jenkins node pipeline syntax, or using Ansible-Playbook through the Building Script:
First Way would be as follows in the Jenkinsfile:
node('node1') {
// Building Stages on node 1
}
node('node2') {
// Building Stages node 2
}
Second Way would be as follow in Jenkinsfile:
node('master_node'){
// master node has the ansible-playbook
ansiblePlaybook credentialsId: 'ansible_ssh_user', inventory: 'path_to_inventory_file', playbook: 'path_to_playbook', sudo: true, sudoUser: 'sudo_user_name'
}
This way requires to install Ansible-plugin on the Jenkins Master Node.
and you can put all the nodes you want in the Inventory file.
The main difference between the two ways besides to Idempotence, The First way will provide a sequential execution, while the Second way will provide a parallel execution using Ansible.
|
stackoverflow
|
{
"language": "en",
"length": 441,
"provenance": "stackexchange_0000F.jsonl.gz:848299",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44490654"
}
|
711b1da4d787ac44efef42e946d23485ed7e5419
|
Stackoverflow Stackexchange
Q: Using Gensim shows "Slow version of gensim.models.doc2vec being used" I am trying to run a program using the Gensim library of the Python with the version 3.6.
Whenever I ran the program, I came across these statements:
C:\Python36\lib\site-packages\gensim-2.0.0-py3.6-win32.egg\gensim\utils.py:860: UserWarning: detected Windows; aliasing chunkize to chunkize_serial
warnings.warn("detected Windows; aliasing chunkize to chunkize_serial")
Slow version of gensim.models.doc2vec is being used
I do not understand what is the meaning behind Slow version of gensim.models.doc2vec is being used. How the gensim is selecting the slow version and if I want the fastest version then what I need to do?
A: Highlighting @juanpa.arrivillaga's comment, as it helped me resolve this issue.
If you installed anaconda :
*
*uninstall gensim : pip uninstall gensim
*install it with the anaconda package manager : conda install gensim
|
Q: Using Gensim shows "Slow version of gensim.models.doc2vec being used" I am trying to run a program using the Gensim library of the Python with the version 3.6.
Whenever I ran the program, I came across these statements:
C:\Python36\lib\site-packages\gensim-2.0.0-py3.6-win32.egg\gensim\utils.py:860: UserWarning: detected Windows; aliasing chunkize to chunkize_serial
warnings.warn("detected Windows; aliasing chunkize to chunkize_serial")
Slow version of gensim.models.doc2vec is being used
I do not understand what is the meaning behind Slow version of gensim.models.doc2vec is being used. How the gensim is selecting the slow version and if I want the fastest version then what I need to do?
A: Highlighting @juanpa.arrivillaga's comment, as it helped me resolve this issue.
If you installed anaconda :
*
*uninstall gensim : pip uninstall gensim
*install it with the anaconda package manager : conda install gensim
A: The problem is to do with the some underlying packages not being up to date. Gordon's post here helped me.
But in short:
*
*Uninstall Gensim
sudo pip3 uninstall gensim
*Install python3-dev build-essential
sudo apt-get install python3-dev build-essential
*Re-Install Gensim
sudo pip3 install --upgrade gensim
Notes:
*
*Instructions above are for systems where pip and apt-get are used to
manage packages
*pip3 is the python3 version of pip
A: I also had this problem (I'm running ubuntu). I found out that if i'm using directly the version from github, the problem is fixed.
So there are 2 solutions: (first uninstall gensim using pip uninstall gensim)
*
*download and unzip the gensim zip file from gensim's github page, then CD to the folder of the zip content and run the command python setup.py install
*run this command pip install git+https://github.com/RaRe-Technologies/gensim@master#egg=gensim
I used the second and now I don't get the warnings
|
stackoverflow
|
{
"language": "en",
"length": 281,
"provenance": "stackexchange_0000F.jsonl.gz:848328",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44490739"
}
|
b637a0af519eaa1f6153c29a7a5ec5ff72017eda
|
Stackoverflow Stackexchange
Q: matplotlib: match legend text color with symbol in scatter plot I made a scatter plot with 3 different colors and I want to match the color of the symbol and the text in the legend.
A nice solution exist for the case of line plots:
leg = ax.legend()
# change the font colors to match the line colors:
for line,text in zip(leg.get_lines(), leg.get_texts()):
text.set_color(line.get_color())
However, scatter plot colors cannot be accessed by get_lines().For the case of 3 colors I think I can manually set the text colors one-by-one using eg. text.set_color('r'). But I was curious if it can be done automatically as lines. Thanks!
A: Scatter plots have a facecolor and an edgecolor. The legend handler for a scatter is a PathCollection.
So you can loop over the legend handles and set the text color to the facecolor of the legend handle
for h, t in zip(leg.legendHandles, leg.get_texts()):
t.set_color(h.get_facecolor()[0])
Complete code:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
for i in range(3):
x,y = np.random.rand(2, 20)
ax.scatter(x, y, label="Label {}".format(i))
leg = ax.legend()
for h, t in zip(leg.legendHandles, leg.get_texts()):
t.set_color(h.get_facecolor()[0])
plt.show()
|
Q: matplotlib: match legend text color with symbol in scatter plot I made a scatter plot with 3 different colors and I want to match the color of the symbol and the text in the legend.
A nice solution exist for the case of line plots:
leg = ax.legend()
# change the font colors to match the line colors:
for line,text in zip(leg.get_lines(), leg.get_texts()):
text.set_color(line.get_color())
However, scatter plot colors cannot be accessed by get_lines().For the case of 3 colors I think I can manually set the text colors one-by-one using eg. text.set_color('r'). But I was curious if it can be done automatically as lines. Thanks!
A: Scatter plots have a facecolor and an edgecolor. The legend handler for a scatter is a PathCollection.
So you can loop over the legend handles and set the text color to the facecolor of the legend handle
for h, t in zip(leg.legendHandles, leg.get_texts()):
t.set_color(h.get_facecolor()[0])
Complete code:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
for i in range(3):
x,y = np.random.rand(2, 20)
ax.scatter(x, y, label="Label {}".format(i))
leg = ax.legend()
for h, t in zip(leg.legendHandles, leg.get_texts()):
t.set_color(h.get_facecolor()[0])
plt.show()
A: This seems complicated but does give you what you want. Suggestions are welcomed. I use ax.get_legend_handles_labels() to get the markers and use tuple(handle.get_facecolor()[0]) to get the matplotlib color tuple. Made an example with a really simple scatter plot like this:
Edit:
As ImportanceOfBeingErnest pointed in his answer:
*
*leg.legendHandles will return the legend handles;
*List, instead of tuple, can be used to assign matplotlib color.
Codes are simplified as:
import matplotlib.pyplot as plt
from numpy.random import rand
fig, ax = plt.subplots()
for color in ['red', 'green', 'blue']:
x, y = rand(2, 10)
ax.scatter(x, y, c=color, label=color)
leg = ax.legend()
for handle, text in zip(leg.legendHandles, leg.get_texts()):
text.set_color(handle.get_facecolor()[0])
plt.show()
What I got is:
|
stackoverflow
|
{
"language": "en",
"length": 299,
"provenance": "stackexchange_0000F.jsonl.gz:848353",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44490815"
}
|
a23bfffa11a2316e862bef9f0df6465ed9c84db7
|
Stackoverflow Stackexchange
Q: How exclude Folder inside folder app when build with angular-cli? This is my project structure :
- src
- app
- tenantA
- tenantB
- assets
- index.html
How I can exclude folder tenantA when run "ng build"
Thanks
A: you can try put that folder in either tsconfig.app.json under /src or tsconfig.json under root, like
"exclude": [
"test.ts",
"**/*.spec.ts",
"_backup/**/*"
]
|
Q: How exclude Folder inside folder app when build with angular-cli? This is my project structure :
- src
- app
- tenantA
- tenantB
- assets
- index.html
How I can exclude folder tenantA when run "ng build"
Thanks
A: you can try put that folder in either tsconfig.app.json under /src or tsconfig.json under root, like
"exclude": [
"test.ts",
"**/*.spec.ts",
"_backup/**/*"
]
|
stackoverflow
|
{
"language": "en",
"length": 63,
"provenance": "stackexchange_0000F.jsonl.gz:848370",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44490853"
}
|
31ea5a62eaad53433b92176e9ca3fe9195e0c65d
|
Stackoverflow Stackexchange
Q: How to loop over all but last column in pandas dataframe + indexing? Let's day I have a pandas dataframe df where the column names are the corresponding indices, so 1, 2, 3,....len(df.columns). How do I loop through all but the last column, so one before len(df.columns). My goal is to ultimately compare the corresponding element in each row for each of the columns with that of the last column. Any code with be helpful! Thank you!
A: To iterate over each column, use
for column_name, column_series in df.iteritems():
pass
To iterate over all but last column
for column_name, column_series in df.iloc[:, :-1].iteritems():
pass
I'd highly recommend asking another question with more detail about what you are trying do to as it is likely we can avoid using the iterators completely via vectorization.
|
Q: How to loop over all but last column in pandas dataframe + indexing? Let's day I have a pandas dataframe df where the column names are the corresponding indices, so 1, 2, 3,....len(df.columns). How do I loop through all but the last column, so one before len(df.columns). My goal is to ultimately compare the corresponding element in each row for each of the columns with that of the last column. Any code with be helpful! Thank you!
A: To iterate over each column, use
for column_name, column_series in df.iteritems():
pass
To iterate over all but last column
for column_name, column_series in df.iloc[:, :-1].iteritems():
pass
I'd highly recommend asking another question with more detail about what you are trying do to as it is likely we can avoid using the iterators completely via vectorization.
A: A simple way would be to use slicing with iloc
all but last column would be:
df.iloc[:,:-1]
all but first column would be:
df.iloc[:,1:]
|
stackoverflow
|
{
"language": "en",
"length": 159,
"provenance": "stackexchange_0000F.jsonl.gz:848435",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491067"
}
|
5e652588551831386c7b12feee40f212537f8cdd
|
Stackoverflow Stackexchange
Q: Python for .NET: "TypeError: Cannot get managed object" due to getting wrong type info from .NET structs I can't make Python for .NET get the right type from my .NET struct.
Here is my C# code:
namespace PyNetFails
{
public struct A
{
public int X;
public int Y;
public uint V;
}
}
So the code is really simple.
Then I try to use this struct in Python:
import clr
clr.AddReference('PyNetFails.dll')
from PyNetFails import A
a = A()
print(type(a.V))
and I get <class 'int'> although it has to be System.UInt32.
So when I try afterwards to run
from System import UInt32
v = UInt32(42)
print(v >= a.V)
I get
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
print(v >= a.V)
TypeError: Cannot get managed object
Is this a bug or am I doing something wrong?
Thanks in advance.
|
Q: Python for .NET: "TypeError: Cannot get managed object" due to getting wrong type info from .NET structs I can't make Python for .NET get the right type from my .NET struct.
Here is my C# code:
namespace PyNetFails
{
public struct A
{
public int X;
public int Y;
public uint V;
}
}
So the code is really simple.
Then I try to use this struct in Python:
import clr
clr.AddReference('PyNetFails.dll')
from PyNetFails import A
a = A()
print(type(a.V))
and I get <class 'int'> although it has to be System.UInt32.
So when I try afterwards to run
from System import UInt32
v = UInt32(42)
print(v >= a.V)
I get
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
print(v >= a.V)
TypeError: Cannot get managed object
Is this a bug or am I doing something wrong?
Thanks in advance.
|
stackoverflow
|
{
"language": "en",
"length": 143,
"provenance": "stackexchange_0000F.jsonl.gz:848470",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491159"
}
|
0fb4fad31baa8c89e53cd0d3dee1b18bc302f745
|
Stackoverflow Stackexchange
Q: Default value of argument in ES6 Is this default value of argument in es6?
function list({ skip = 0, limit = 50 } = {}) {
}
What does the above code do?
if it's list(skip=0, limit=50) I can understand but now I'm confused.
A: The function is expecting an object, with skip and limit properties, and setting defaults if not present. See an example usage below to understand it more clearly
function list({ skip = 0, limit = 50 } = {}) {
console.log(skip);
console.log(limit);
}
// No args
list();
// skip changed. Note the object
list({skip: 2});
// limit changed. Note the object
list({limit: 2});
|
Q: Default value of argument in ES6 Is this default value of argument in es6?
function list({ skip = 0, limit = 50 } = {}) {
}
What does the above code do?
if it's list(skip=0, limit=50) I can understand but now I'm confused.
A: The function is expecting an object, with skip and limit properties, and setting defaults if not present. See an example usage below to understand it more clearly
function list({ skip = 0, limit = 50 } = {}) {
console.log(skip);
console.log(limit);
}
// No args
list();
// skip changed. Note the object
list({skip: 2});
// limit changed. Note the object
list({limit: 2});
A: It's called de-structuring and it can be tricky to understand if you get caught up with = {}.
This is the equivalent in es5:
function list() {
var opts = arguments[0] === undefined ? {} : arguments[0];
var skip = opts.skip === undefined ? 0 : opts.skip;
var limit = opts.limit === undefined ? 50 : opts.limit;
}
This is very useful for passing configuration objects around and saves us from having to make use of a long list of x == undefined ? foo : bar.
The reason for doing { skip = 0, limit = 50 } = {} is simply a part of de-structuring. skip and limit are properties of an unnamed object thus allowing one to simply get the values of the properties without the object reference. You can say they have been injected into the current scope. When we do the = {}, then if the right side object (the currently empty one) had a key called skip, then the skip on the left side gets the new value of the skip on the right side. Likewise for limit. But since the object on the right does not have properties corresponding to either property names on the left, the left hand properties are left unchanged. Furthermore the use for = {} is so that we can have this method called without any arguments, thus the function gets it's default arguments as parameter.
If one is still confused about this, just remember that the only reason for = {} is to act as a default parameter for the function which allows us to call the function without arguments. And also, it does not affect the values on the left side of that expression because of the reasons stated.
References:
https://simonsmith.io/destructuring-objects-as-function-parameters-in-es6/
https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/
A: That function has destructuring and default parameters mixed together.
Based on the function signature, we can say that we're expecting a single argument, which should be an object.
function list(myObject) {
}
If no arguments are passed (or undefined is passed), we setup a default value to be an empty object, {}.
function list(myObject = {}) {
}
Now, no matter if we pass an object, no arguments, or undefined, myObject will be an object.
// myObject will be {} for all 3 calls
list({})
list()
list(undefined);
Next, we destructure this myObject by extracting skip and limit from it:
function list(myObject = {}) {
let { skip, limit } = myObject;
}
Furthermore, we can perform this destructuring directly instead of the myObject parameter:
function list({ skip, limit } = {}) {
}
Finally, in case skip or limit do not exist on the value we end up with, we give them default values:
function list({ skip = 0, limit = 50 } = {}) {
}
|
stackoverflow
|
{
"language": "en",
"length": 572,
"provenance": "stackexchange_0000F.jsonl.gz:848492",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491229"
}
|
cfceb6835315a98120bd26010138e5c2fd0bdbde
|
Stackoverflow Stackexchange
Q: How to replace the first occurence in Swift? How can I use the replacingOccurrences with regex and only replace the first occurrence?
Example
var str = "= 1 = 2 = 3"
str = str.replacingOccurrences(of: "(\\d+)", with: "\\\\$1", options: .regularExpression)
// prints: = \\1 = \\2 = \\3
// should print: = \\1 = 2 = 3
A: String.range() will stop at the first match:
var str = "= 1 = 2 = 3"
if let range = str.range(of: "\\d+", options: .regularExpression) {
let substr = str[range]
str = str.replacingCharacters(in: range, with: "\\\\" + substr)
}
print(str)
|
Q: How to replace the first occurence in Swift? How can I use the replacingOccurrences with regex and only replace the first occurrence?
Example
var str = "= 1 = 2 = 3"
str = str.replacingOccurrences(of: "(\\d+)", with: "\\\\$1", options: .regularExpression)
// prints: = \\1 = \\2 = \\3
// should print: = \\1 = 2 = 3
A: String.range() will stop at the first match:
var str = "= 1 = 2 = 3"
if let range = str.range(of: "\\d+", options: .regularExpression) {
let substr = str[range]
str = str.replacingCharacters(in: range, with: "\\\\" + substr)
}
print(str)
A: You may actually use a common work-around with a bit modified regex (the idea already suggested by @I'L'I, but I suggest a little modification to it):
var str = "= 1 = 2 = 3"
str = str.replacingOccurrences(of: "(?s)([0-9]+)(.*)", with: "\\\\\\\\$1$2", options: .regularExpression)
print(str) // => = \\1 = 2 = 3
Two remarks:
*
*(?s)([0-9]+)(.*) - matches the first 1 or more digits (Group 1) and then captures all the rest of the string (note that . will match line breaks thanks to the (?s) inline "dotall" modifier)
*The replacement part needs 4 backslashes to replace with 1 backslash, so, you need to put 8 backslashes there to get 2 literal backslashes in the output.
A similar to @CodeDifferent solution using the string mutating .replaceSubrange method mentioned by @MartinR:
var str = "= 123 = 256 = 378"
if let range = str.range(of: "[0-9]+", options: .regularExpression) {
str.replaceSubrange(range, with: "\\\\" + str[range])
}
print(str) // => = \\123 = 256 = 378
Hints on the regex:
*
*To match standalone numbers (not those like in ABC1234) use either word boundaries ("\\b[0-9]+\\b") or negative lookarounds (i.e. "(?
*Since ICU regexps are Unicode aware by default, you should consider using [0-9] instead of \d to avoid matching non-ASCII digits.
|
stackoverflow
|
{
"language": "en",
"length": 307,
"provenance": "stackexchange_0000F.jsonl.gz:848503",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491278"
}
|
9156ef411bfd0cb85547f2a62d8fa5939d3e03c4
|
Stackoverflow Stackexchange
Q: MethodError: objects of type Module are not callable I am trying to duplicate a code in Julia using Jupyter Notebook.
and getting the error
MethodError: objects of type Module are not callable
What am i missing here?
using JuMP, Clp
m=Model(solver=Clp())
@variable(m, 0 >= x >= 9)
@variable(m, 0 >= y >= 10)
@objective(m,Min,3x-y)
@constraint(m,const1, 6x+5y <=30)
@constraint(m,const2, 7x+12y <= 84)
@constraint(m,const3, 19x+14y <=266)
solve(m)
println("Optimal Solutions:")
println("x = ", getvalue(x))
println("y = ", getvalue(y))
A: Clp is a module, you cannot call a module, ie. Cpl(), you want to call ClpSolver instead, see:
*
*http://jump.readthedocs.io/en/latest/installation.html#getting-solvers
Use: m = Model(solver = ClpSolver())
|
Q: MethodError: objects of type Module are not callable I am trying to duplicate a code in Julia using Jupyter Notebook.
and getting the error
MethodError: objects of type Module are not callable
What am i missing here?
using JuMP, Clp
m=Model(solver=Clp())
@variable(m, 0 >= x >= 9)
@variable(m, 0 >= y >= 10)
@objective(m,Min,3x-y)
@constraint(m,const1, 6x+5y <=30)
@constraint(m,const2, 7x+12y <= 84)
@constraint(m,const3, 19x+14y <=266)
solve(m)
println("Optimal Solutions:")
println("x = ", getvalue(x))
println("y = ", getvalue(y))
A: Clp is a module, you cannot call a module, ie. Cpl(), you want to call ClpSolver instead, see:
*
*http://jump.readthedocs.io/en/latest/installation.html#getting-solvers
Use: m = Model(solver = ClpSolver())
|
stackoverflow
|
{
"language": "en",
"length": 103,
"provenance": "stackexchange_0000F.jsonl.gz:848506",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491282"
}
|
dde87443f8e9c397dc5d7830b2eea7d7a344766d
|
Stackoverflow Stackexchange
Q: iOS TWTRComposer Request failed: unauthorized (401) With the following code and a bunch of other variations I've tried, I always get an unauthorized error. I'm using TwitterKit 3.0 using CocoaPods. I've got my plist setup, my twitter app configured, and code like this:
// In didFinishLaunchingWithOptions
Twitter.sharedInstance().start(withConsumerKey:"XX", consumerSecret:"YYY")
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool
{
return Twitter.sharedInstance().application(app, open: url, options: options)
}
// In response to a click
Twitter.sharedInstance().logIn { session, error in
if session != nil { // Log in succeeded
let composer = TWTRComposer()
composer.setText(tweetText)
composer.show(from: self.navigationController!) { result in
if (result == .done) {
print("Successfully composed Tweet")
} else {
print("Cancelled composing")
}
}
}
}
"Did encounter error sending Tweet: Error
Domain=TWTRNetworkingErrorDomain Code=-1011 "Request failed:
unauthorized (401)" UserInfo={NSLocalizedFailureReason=,
TWTRNetworkingStatusCode=401,
NSErrorFailingURLKey=https://api.twitter.com/1.1/statuses/update.json,
NSLocalizedDescription=Request failed: unauthorized (401)"
A: If it doesn't work even after following Twitter's setup instructions, try regenerating the consumer keys. This fixed the problem for me.
|
Q: iOS TWTRComposer Request failed: unauthorized (401) With the following code and a bunch of other variations I've tried, I always get an unauthorized error. I'm using TwitterKit 3.0 using CocoaPods. I've got my plist setup, my twitter app configured, and code like this:
// In didFinishLaunchingWithOptions
Twitter.sharedInstance().start(withConsumerKey:"XX", consumerSecret:"YYY")
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool
{
return Twitter.sharedInstance().application(app, open: url, options: options)
}
// In response to a click
Twitter.sharedInstance().logIn { session, error in
if session != nil { // Log in succeeded
let composer = TWTRComposer()
composer.setText(tweetText)
composer.show(from: self.navigationController!) { result in
if (result == .done) {
print("Successfully composed Tweet")
} else {
print("Cancelled composing")
}
}
}
}
"Did encounter error sending Tweet: Error
Domain=TWTRNetworkingErrorDomain Code=-1011 "Request failed:
unauthorized (401)" UserInfo={NSLocalizedFailureReason=,
TWTRNetworkingStatusCode=401,
NSErrorFailingURLKey=https://api.twitter.com/1.1/statuses/update.json,
NSLocalizedDescription=Request failed: unauthorized (401)"
A: If it doesn't work even after following Twitter's setup instructions, try regenerating the consumer keys. This fixed the problem for me.
A: There is no reason to log in when using TWTRComposer. The SDK will use the current session in the Twitter App if there is one, or it will fall back in a smart way. I can't say why your login is failing, but I would suggest simply removing it to get around the problem.
let composer = TWTRComposer()
composer.setText(tweetText)
composer.show(from: self.navigationController!) { (result in
if (result == .done) {
print("Successfully composed Tweet")
} else {
print("Cancelled composing")
}
}
You said that you already set everything up, but I will give you an installation checklist, should you have missed a step:
*
*Initialize Twitter Kit
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Twitter.sharedInstance().start(withConsumerKey:"xxx", consumerSecret:"xxx")
return true
}
*Configure Info.Plist
// Info.plist
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>twitterkit-<consumerKey></string>
</array>
</dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>twitter</string>
<string>twitterauth</string>
</array>
If you are still having problems, make sure to check your app's status at https://apps.twitter.com/. There are multiple ways of getting your app key restricted or even deactivated. If this is the case, there will be a red label underneath the app name.
A: I also face the same problem. I was using Twitter, FB and Google logins.
the problem in the plist sequence of he URLSchemes
I added twitter Schemes first it worked
my ex -
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>twitterkit-xxxx</string>
</array>
</dict>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fbxxxxx</string>
</array>
</dict>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>com.googleusercontent.apps.xxxx-xxxx</string>
</array>
</dict>
</array>
A: In TwitterKit 3.3.0, basically:
Although the callback URL will not be requested by Twitter Kit in your
app, it must be set to a valid URL for the app to work with the SDK.
even though when you try to create a Twitter app it doesn't say it is mandatory - which it is if you want below flow will work
Failing to do that will break below entire flow and nothing will happen automatically:
If Twitter is not installed on the device it automatically falls back to use OAuth via a web view (using SFSafariViewController for the first user, and a UIWebView for subsequent additional users.)
What will work if you won't have callback_url:
Only if the user has Twitter app installed we can compose a twit or log-in - the rest just doesn't work.
When Twitter app isn't installed:
*
*When using composer.show(from: self) { (result) in you'll be getting .cancelled.
*When using TWTRTwitter.sharedInstance().logIn(completion: { (session, error) in you'll be getting Request failed: unauthorized (401)
General notes:
*
*If API key/secret are invalid, any action performed by TwitterKit lead to app crash
*Ensure that the singleton start("key", "secret") method, and project plist with the value: twitterkit-{API KEY} has the same key or else your app will crash.
|
stackoverflow
|
{
"language": "en",
"length": 610,
"provenance": "stackexchange_0000F.jsonl.gz:848524",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491349"
}
|
b8442c18c5cd2846b654287f1bf4e1c7458ba842
|
Stackoverflow Stackexchange
Q: Find all references does not work in Visual Studio 2015 for an ASP.NET web site I am working with Visual Studio 2015, target framework 4.5.
Find All References(Shift + F12) works perfectly on desktop and ASP.NET web application, but does not work with ASP.NET web site.
I created the web site as follows:
*
*File -> New -> Web Site -> Visual C# -> ASP.NET Empty Web Site -> Create As-> NewWebSite
*Right click on Solution -> Add -> New Project -> Class Library -> ClassLibrary1.cs
*NewWebSite -> Right Click -> Add -> Add New Item -> Web Form -> Default.aspx
*NewWebSite (Right Click) -> Add -> Reference -> Solution -> ClassLibrary1 -> Ok
ClassLibrary1.cs and Default.aspx files code is this:
ClassLibrary1 -> Class1 Code
using System;
namespace ClassLibrary1
{
public class Class1
{
public static string demo = "demo";
}
}
Default.aspx.cs Code
using System;
using ClassLibrary1;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string a = Class1.demo;
}
}
Please close Default.aspx.cs file. And Shift + F12 on ClassLibrary1 -> Class1 -> Demo
I can't get reference of Demo which does exist in Default.aspx.cs file
|
Q: Find all references does not work in Visual Studio 2015 for an ASP.NET web site I am working with Visual Studio 2015, target framework 4.5.
Find All References(Shift + F12) works perfectly on desktop and ASP.NET web application, but does not work with ASP.NET web site.
I created the web site as follows:
*
*File -> New -> Web Site -> Visual C# -> ASP.NET Empty Web Site -> Create As-> NewWebSite
*Right click on Solution -> Add -> New Project -> Class Library -> ClassLibrary1.cs
*NewWebSite -> Right Click -> Add -> Add New Item -> Web Form -> Default.aspx
*NewWebSite (Right Click) -> Add -> Reference -> Solution -> ClassLibrary1 -> Ok
ClassLibrary1.cs and Default.aspx files code is this:
ClassLibrary1 -> Class1 Code
using System;
namespace ClassLibrary1
{
public class Class1
{
public static string demo = "demo";
}
}
Default.aspx.cs Code
using System;
using ClassLibrary1;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string a = Class1.demo;
}
}
Please close Default.aspx.cs file. And Shift + F12 on ClassLibrary1 -> Class1 -> Demo
I can't get reference of Demo which does exist in Default.aspx.cs file
|
stackoverflow
|
{
"language": "en",
"length": 195,
"provenance": "stackexchange_0000F.jsonl.gz:848556",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491433"
}
|
2bac1837159b9ae16dc761ab9d2be4cedd4fa20a
|
Stackoverflow Stackexchange
Q: Recyclerview automatically scroll up when data inserted I'm suffering with one problem that when I add data to array list and then add it into adapter after that when I set it to recycler view adapter it jumps to top automatically how can I prevent it like I want to add data in virtual space I also tried with use of -
runOnUiThread(new Runnable() {
public void run() {
innerAdapter.notifyDataSetChanged();
}
});
but it not working. how can I solve it?
add some code for scrolling up
if (isScrollUp) {
isEnable = true;
userChats.addAll(0, model.data);
innerChatAdapter.notifyDataSetChanged();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
nnerChatAdapter.notifyItemInserted(0);
recyclerView.smoothScrollToPosition(0);
}
}, 1);
}
A: Hello if you want to scroll down after add data to adapter.Add below method after notifyDataSetChanged() called.
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mRecyclerView.smoothScrollToPosition(new_data_size);
}
}, 1);
|
Q: Recyclerview automatically scroll up when data inserted I'm suffering with one problem that when I add data to array list and then add it into adapter after that when I set it to recycler view adapter it jumps to top automatically how can I prevent it like I want to add data in virtual space I also tried with use of -
runOnUiThread(new Runnable() {
public void run() {
innerAdapter.notifyDataSetChanged();
}
});
but it not working. how can I solve it?
add some code for scrolling up
if (isScrollUp) {
isEnable = true;
userChats.addAll(0, model.data);
innerChatAdapter.notifyDataSetChanged();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
nnerChatAdapter.notifyItemInserted(0);
recyclerView.smoothScrollToPosition(0);
}
}, 1);
}
A: Hello if you want to scroll down after add data to adapter.Add below method after notifyDataSetChanged() called.
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mRecyclerView.smoothScrollToPosition(new_data_size);
}
}, 1);
A: Try this one
Don't update the entire RecyclerView. Ref Here
runOnUiThread(new Runnable() {
public void run() {
innerAdapter.notifyItemInserted(position /* position of newly added item */);
}
});
A: To solve this problem you can use requestFocus() method on any other top element of your view.
top_element.requestFocus();
|
stackoverflow
|
{
"language": "en",
"length": 190,
"provenance": "stackexchange_0000F.jsonl.gz:848582",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491526"
}
|
cecd09b956be60a42d6560f487e1112ddbdeaf99
|
Stackoverflow Stackexchange
Q: pod 'MaterialComponents' not adding all material components I followed the Github link for installing MaterialComponents via pods. Though installation was successful, but could not find MaterialTextFields. Later noticed that for installing separate components, we have to use different pods. I also noticed that pod MaterialComponents itself installs many components.
My query is, on what basis, are there different pods for different components considering that many components are installed using single pod (MaterialComponents) as well. Why not have a same pod for all components OR why not have separate pod for each component.
A: We only landed MaterialTextFields in the 24.0.0 release 8 days go. Perhaps you saw that it landed in develop earlier and expected it to be in our podspec?
All of our components should come if you add the root podspec target as instructed on the main readme. We setup subspecs so that clients can pick and choose which components they want to use if they are size averse.
|
Q: pod 'MaterialComponents' not adding all material components I followed the Github link for installing MaterialComponents via pods. Though installation was successful, but could not find MaterialTextFields. Later noticed that for installing separate components, we have to use different pods. I also noticed that pod MaterialComponents itself installs many components.
My query is, on what basis, are there different pods for different components considering that many components are installed using single pod (MaterialComponents) as well. Why not have a same pod for all components OR why not have separate pod for each component.
A: We only landed MaterialTextFields in the 24.0.0 release 8 days go. Perhaps you saw that it landed in develop earlier and expected it to be in our podspec?
All of our components should come if you add the root podspec target as instructed on the main readme. We setup subspecs so that clients can pick and choose which components they want to use if they are size averse.
A: I had a similar problem with the material buttons.
In my case I had to add use_frameworks! to the Podfile. It would be nice it this was added to the documentation.
Without the use_frameworks! the import was giving the error No such module 'MaterialComponents.MaterialButtons'.
|
stackoverflow
|
{
"language": "en",
"length": 207,
"provenance": "stackexchange_0000F.jsonl.gz:848595",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491568"
}
|
685a2ffe598eae4e5ca4b3b782b0f147578d779e
|
Stackoverflow Stackexchange
Q: Jupyter: Get multi-line input from user I tried for several hours to get solution to my basic question with out success.
How can I get in Jupyter, multi-line input from user (Python3)?
Pay attention that the question is regard to user input in Jupyter.
I have been try:
*
*widgets.Text:
from IPython.display import display
text = widgets.Text()
display(text)
button = widgets.Button(description="Send")
display(button)
def on_button_clicked(b):
print(text.value)
button.on_click(on_button_clicked)`
*Special keys:
print ("Enter/Paste your content. Ctrl-D to save it.")
contents = []
line = "vv"
while line != "":
try:
line = input("")
except EOFError:
break
contents.append(line)
and more..
Thanks for you time and help,
Oran
|
Q: Jupyter: Get multi-line input from user I tried for several hours to get solution to my basic question with out success.
How can I get in Jupyter, multi-line input from user (Python3)?
Pay attention that the question is regard to user input in Jupyter.
I have been try:
*
*widgets.Text:
from IPython.display import display
text = widgets.Text()
display(text)
button = widgets.Button(description="Send")
display(button)
def on_button_clicked(b):
print(text.value)
button.on_click(on_button_clicked)`
*Special keys:
print ("Enter/Paste your content. Ctrl-D to save it.")
contents = []
line = "vv"
while line != "":
try:
line = input("")
except EOFError:
break
contents.append(line)
and more..
Thanks for you time and help,
Oran
|
stackoverflow
|
{
"language": "en",
"length": 104,
"provenance": "stackexchange_0000F.jsonl.gz:848602",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491590"
}
|
447ed270304800fbe75bda1d1fff4b5f684f7506
|
Stackoverflow Stackexchange
Q: .HTACCESS Unicode Recignisition/Encoding I am having a problem with my URL Shorthands in my .htaccess.
Namely, everything works fine with this (now old) code...
# URL ShortCut Maker.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} .(.+)$
RewriteRule ^(.) ?open=encyclopedia&letter=$1&term=%1 [B,L,NC]
It shows URL correctly as example.com/Modesty (it shows the page as if the URL would be /?open=encyclopedia&letter=m&term=modesty), but the problem occurs when I enter:
example.com/Šanti, or
example.com/Đin, or
example.com/Žal,
example.com/Čakra, or
example.com/Ćof...
...if I enter any of these URLs - it shows the page as if I would enter:
?open=encyclopedia and not as
?open=encyclopedia&letter=Š&term=Šanti
EDIT: Non-English letters in question/problem.
Any solution to this?
A: You can change your existing rule with rule:
RewriteEngine On
RewriteBase /
# executes repeatedly as long as there are more than 1 spaces in URI
RewriteRule "^(\S*)\s+(\S* .*)$" $1+$2 [N,NE]
# executes when there is exactly 1 space in URI
RewriteRule "^(\S*)\s(\S*)$" $1+$2 [L,R=302,NE]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([A-Z](?:[^\x00-\x7F]+|[A-Z])?).*$ ?open=encyclopedia&letter=$1&term=$0 [B,L,QSA]
RewriteRule ^([^\x00-\x7F]+).*$ ?open=encyclopedia&letter=$1&term=$0 [B,L,QSA]
Negated character class [^\x00-\x7F] matches any character outside ASCII range.
|
Q: .HTACCESS Unicode Recignisition/Encoding I am having a problem with my URL Shorthands in my .htaccess.
Namely, everything works fine with this (now old) code...
# URL ShortCut Maker.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} .(.+)$
RewriteRule ^(.) ?open=encyclopedia&letter=$1&term=%1 [B,L,NC]
It shows URL correctly as example.com/Modesty (it shows the page as if the URL would be /?open=encyclopedia&letter=m&term=modesty), but the problem occurs when I enter:
example.com/Šanti, or
example.com/Đin, or
example.com/Žal,
example.com/Čakra, or
example.com/Ćof...
...if I enter any of these URLs - it shows the page as if I would enter:
?open=encyclopedia and not as
?open=encyclopedia&letter=Š&term=Šanti
EDIT: Non-English letters in question/problem.
Any solution to this?
A: You can change your existing rule with rule:
RewriteEngine On
RewriteBase /
# executes repeatedly as long as there are more than 1 spaces in URI
RewriteRule "^(\S*)\s+(\S* .*)$" $1+$2 [N,NE]
# executes when there is exactly 1 space in URI
RewriteRule "^(\S*)\s(\S*)$" $1+$2 [L,R=302,NE]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([A-Z](?:[^\x00-\x7F]+|[A-Z])?).*$ ?open=encyclopedia&letter=$1&term=$0 [B,L,QSA]
RewriteRule ^([^\x00-\x7F]+).*$ ?open=encyclopedia&letter=$1&term=$0 [B,L,QSA]
Negated character class [^\x00-\x7F] matches any character outside ASCII range.
|
stackoverflow
|
{
"language": "en",
"length": 180,
"provenance": "stackexchange_0000F.jsonl.gz:848618",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491639"
}
|
b7a3a09a039d3ed49e8add47b912680385c13eee
|
Stackoverflow Stackexchange
Q: How to get channel name in Bot Framework I am working on MS Bot Framework App.I want to know how many peoples are coming from specific channels like via webchat, DirectLine, etc. I want to maintain a log of this. How to can I get channel name from context?
A: You can use the following code to get the channel type:
context.Activity.ChannelId
For example, if it is "telegram", you've gotten the message from the "telegram".
|
Q: How to get channel name in Bot Framework I am working on MS Bot Framework App.I want to know how many peoples are coming from specific channels like via webchat, DirectLine, etc. I want to maintain a log of this. How to can I get channel name from context?
A: You can use the following code to get the channel type:
context.Activity.ChannelId
For example, if it is "telegram", you've gotten the message from the "telegram".
A: If someone from Node.js needs this information too, channel name is stored in, as far as I know:
session.message.address.channelId
and in:
session.message.source
|
stackoverflow
|
{
"language": "en",
"length": 99,
"provenance": "stackexchange_0000F.jsonl.gz:848648",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491769"
}
|
07f753c919c26bb2bd70074773bd72278923e91e
|
Stackoverflow Stackexchange
Q: unable to run python programs from windows 10 cmd This is the path where python is installed on my computer A:\software installation\python and the same path has been added to the system path in Environment variables.
My scripts are stored in A:\python programs but when I try to execute from the Windows command prompt (cmd) there is no output as shown below.
A: Just set your environment variable path, like C:\Python27.
*
*Check your system for the installation path
*Copy the path
*Go to my computer properties => advance system setting
*In the Advanced tab => Environment variable => click on the path, then click on new and paste the path
*Click ok and restart the cmd
All done :)
|
Q: unable to run python programs from windows 10 cmd This is the path where python is installed on my computer A:\software installation\python and the same path has been added to the system path in Environment variables.
My scripts are stored in A:\python programs but when I try to execute from the Windows command prompt (cmd) there is no output as shown below.
A: Just set your environment variable path, like C:\Python27.
*
*Check your system for the installation path
*Copy the path
*Go to my computer properties => advance system setting
*In the Advanced tab => Environment variable => click on the path, then click on new and paste the path
*Click ok and restart the cmd
All done :)
A: If you have installed Python 3.7 or above try using keyword "py" instead of "python" on cmd. It worked for me.(I have python 3.7 32bit installed in windows 10 operating system)
A: I had a similar problem and solved it using the following steps:
*
*Right-click the file you want to run.
*Select "always run using this program" to make this default, to avoid doing this again for other running other python files.
*Browse and select the python 3.6 (or 2.7) interpreter file.
|
stackoverflow
|
{
"language": "en",
"length": 205,
"provenance": "stackexchange_0000F.jsonl.gz:848659",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491802"
}
|
ea59cfb1d0e05cddc3692407f2fb39afada16f54
|
Stackoverflow Stackexchange
Q: Find difference of list of dictionary Python I have 2 Lists in Python;
listA = [{'b': '3'}, {'b': '4'}]
listB = [{'a': '3'}, {'b': '3'}]
I tried to convert it to set it showed unhashable type: 'dict'
The operation i was trying to do is
list[(set(listA)).difference(set(listB))]
So what can be done with my list to achieve same functionality? Thanks
A: Do it with simple list comprehension.
>>> [i for i in listA if i not in listB]
[{'b': '4'}]
|
Q: Find difference of list of dictionary Python I have 2 Lists in Python;
listA = [{'b': '3'}, {'b': '4'}]
listB = [{'a': '3'}, {'b': '3'}]
I tried to convert it to set it showed unhashable type: 'dict'
The operation i was trying to do is
list[(set(listA)).difference(set(listB))]
So what can be done with my list to achieve same functionality? Thanks
A: Do it with simple list comprehension.
>>> [i for i in listA if i not in listB]
[{'b': '4'}]
A: We could use dict.items() to get tuples, which could be converted to set type
setA = set(chain(*[e.items() for e in listA]))
setB = set(chain(*[e.items() for e in listB]))
print setA.symmetric_difference(setB)
The output is
set([('a', '3'), ('b', '4')])
A: You can make use of ifilterfalse from itertools.
list(itertools.ifilterfalse(lambda x: x in listA, listB)) + list(itertools.ifilterfalse(lambda x: x in listB, listA))
The output will be
[{'b': '4'}, {'a': '3'}]
|
stackoverflow
|
{
"language": "en",
"length": 148,
"provenance": "stackexchange_0000F.jsonl.gz:848660",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491804"
}
|
017a45ad236e77326ae50265010513c706e9e13c
|
Stackoverflow Stackexchange
Q: Get available display resolution list Is it possible to get resolution list like in Display preferences? See attached image. I'm using Delphi XE3
I can enum DeviceModeList (source: http://www.delphifeeds.com/go/s/96231)
var
cnt : Integer;
DevMode : TDevMode;
begin
cnt := 0;
while EnumDisplaySettings(nil,cnt,DevMode) do
begin
with Devmode do
ListBox1.Items.Add(Format('%dx%d %d Colors', [dmPelsWidth,dmPelsHeight,Int64(1) shl dmBitsperPel])) ;
Inc(cnt) ;
end;
end;
First problem:
There are resulution I can not set using windows display preferences. Of course I can cut this < 800x600 - But this is a poor idea :)
Next problem:
There is no information on whether the resolution is greyed out (like in display preferences)
I will be grateful for any help in resolving these two problems.
Best regards!
|
Q: Get available display resolution list Is it possible to get resolution list like in Display preferences? See attached image. I'm using Delphi XE3
I can enum DeviceModeList (source: http://www.delphifeeds.com/go/s/96231)
var
cnt : Integer;
DevMode : TDevMode;
begin
cnt := 0;
while EnumDisplaySettings(nil,cnt,DevMode) do
begin
with Devmode do
ListBox1.Items.Add(Format('%dx%d %d Colors', [dmPelsWidth,dmPelsHeight,Int64(1) shl dmBitsperPel])) ;
Inc(cnt) ;
end;
end;
First problem:
There are resulution I can not set using windows display preferences. Of course I can cut this < 800x600 - But this is a poor idea :)
Next problem:
There is no information on whether the resolution is greyed out (like in display preferences)
I will be grateful for any help in resolving these two problems.
Best regards!
|
stackoverflow
|
{
"language": "en",
"length": 119,
"provenance": "stackexchange_0000F.jsonl.gz:848674",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491848"
}
|
1973308179098b0c038148f18b97b643effc641f
|
Stackoverflow Stackexchange
Q: Showing Projected field does not exist in schema: line:bytearray 1)I have loaded a folder in Apache.Pig without defining delimiter given as LINE.
2)I have used PYTHON udf's to filter the given string.But I m getting the above error.
REGISTER '/home/hadoop/alanGates/filter.py' using jython as filterfunction;
d = load '/home/hadoop/Desktop/' using PigStorage as line;
M = foreach d generate filterfunction.tuple_contains(line,Mariko);
Anyone could sought out this error and give me solution.
|
Q: Showing Projected field does not exist in schema: line:bytearray 1)I have loaded a folder in Apache.Pig without defining delimiter given as LINE.
2)I have used PYTHON udf's to filter the given string.But I m getting the above error.
REGISTER '/home/hadoop/alanGates/filter.py' using jython as filterfunction;
d = load '/home/hadoop/Desktop/' using PigStorage as line;
M = foreach d generate filterfunction.tuple_contains(line,Mariko);
Anyone could sought out this error and give me solution.
|
stackoverflow
|
{
"language": "en",
"length": 69,
"provenance": "stackexchange_0000F.jsonl.gz:848679",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491865"
}
|
cb7bfd5bcce6272b19eb899bcdd9f90345290e1b
|
Stackoverflow Stackexchange
Q: iOS: Scrolling text view to bottom programmatically creates a large white space after the text I am trying to load the contents of a file to a TextView on viewDidLoad() of a ViewController. I want the user to see the last content loaded from the file, so I tried the solutions mentioned here.
let bottom = textView.contentSize.height - textView.bounds.size.height
textView.setContentOffset(CGPoint(x: 0, y: bottom), animated:true)
The textview will scroll down but creates a large white space if we scroll down again.
A: By updating the content offset you are actually adding that much offset to the content of scrollview. Here with
let bottom = textView.contentSize.height - textView.bounds.size.height textView.setContentOffset(CGPoint(x: 0, y: bottom), animated: true)
these you are adding extra space at the bottom. So for automatically scrolling the content to the last line try using scrollRangeToVisible function. Like in the top rated answer you have mentioned in your question that you have used to scroll the textview to the last line.
|
Q: iOS: Scrolling text view to bottom programmatically creates a large white space after the text I am trying to load the contents of a file to a TextView on viewDidLoad() of a ViewController. I want the user to see the last content loaded from the file, so I tried the solutions mentioned here.
let bottom = textView.contentSize.height - textView.bounds.size.height
textView.setContentOffset(CGPoint(x: 0, y: bottom), animated:true)
The textview will scroll down but creates a large white space if we scroll down again.
A: By updating the content offset you are actually adding that much offset to the content of scrollview. Here with
let bottom = textView.contentSize.height - textView.bounds.size.height textView.setContentOffset(CGPoint(x: 0, y: bottom), animated: true)
these you are adding extra space at the bottom. So for automatically scrolling the content to the last line try using scrollRangeToVisible function. Like in the top rated answer you have mentioned in your question that you have used to scroll the textview to the last line.
A: This minor change, resolved my issue:
let bottom = CGPoint(x: 0, y: textView.contentSize.height - textView.frame.size.height)
textView.setContentOffset(bottom, animated: false)
Posting my answer, so that someone else find this helpful.
Thanku all for the support.
|
stackoverflow
|
{
"language": "en",
"length": 194,
"provenance": "stackexchange_0000F.jsonl.gz:848681",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491875"
}
|
d1f9ae7b719a0c62afe3e80f3acae83fbfdf90e5
|
Stackoverflow Stackexchange
Q: Conv2 in opencv I'm working on image processing and need to know an equivalent of conv2 of Matlab in c++ OpenCV.
I found this link, but it doesn't suit my requirements.
The problem I'm facing is that I need to convolute a Mat image with a 2-D double array, which is not the case given in the link above.
The matlab code is:
img = conv2(img1,Mx,'same')
where
Mx = {
{0, 0, 0, 0, 0, 0} ,
{0, -0.0003, -0.0035, 0, 0.0035, 0.0003} ,
{0, -0.0090, -0.0903, 0, 0.0903, 0.0090} ,
{0, -0.0229, -0.2292, 0, 0.2292, 0.0229} ,
{0, -0.0090, -0.0903, 0, 0.0903, 0.0090} ,
{0, -0.0003, -0.0035, 0, 0.0035, 0.0003}
};
Thank you.
A: Solution
Use OpenCV's filter2D function.
Code example
//initializes matrix
cv::Mat mat = cv::Mat::ones(50, 50, CV_32F);
//initializes kernel
float Mx[36] = { 0, 0, 0, 0, 0, 0 ,
0, -0.0003, -0.0035, 0, 0.0035, 0.0003 ,
0, -0.0090, -0.0903, 0, 0.0903, 0.0090 ,
0, -0.0229, -0.2292, 0, 0.2292, 0.0229 ,
0, -0.0090, -0.0903, 0, 0.0903, 0.0090 ,
0, -0.0003, -0.0035, 0, 0.0035, 0.0003
};
cv::Mat kernel(6, 6, CV_32F, Mx);
//convolove
cv::Mat dst;
cv::filter2D(mat, dst, mat.depth(), kernel);
|
Q: Conv2 in opencv I'm working on image processing and need to know an equivalent of conv2 of Matlab in c++ OpenCV.
I found this link, but it doesn't suit my requirements.
The problem I'm facing is that I need to convolute a Mat image with a 2-D double array, which is not the case given in the link above.
The matlab code is:
img = conv2(img1,Mx,'same')
where
Mx = {
{0, 0, 0, 0, 0, 0} ,
{0, -0.0003, -0.0035, 0, 0.0035, 0.0003} ,
{0, -0.0090, -0.0903, 0, 0.0903, 0.0090} ,
{0, -0.0229, -0.2292, 0, 0.2292, 0.0229} ,
{0, -0.0090, -0.0903, 0, 0.0903, 0.0090} ,
{0, -0.0003, -0.0035, 0, 0.0035, 0.0003}
};
Thank you.
A: Solution
Use OpenCV's filter2D function.
Code example
//initializes matrix
cv::Mat mat = cv::Mat::ones(50, 50, CV_32F);
//initializes kernel
float Mx[36] = { 0, 0, 0, 0, 0, 0 ,
0, -0.0003, -0.0035, 0, 0.0035, 0.0003 ,
0, -0.0090, -0.0903, 0, 0.0903, 0.0090 ,
0, -0.0229, -0.2292, 0, 0.2292, 0.0229 ,
0, -0.0090, -0.0903, 0, 0.0903, 0.0090 ,
0, -0.0003, -0.0035, 0, 0.0035, 0.0003
};
cv::Mat kernel(6, 6, CV_32F, Mx);
//convolove
cv::Mat dst;
cv::filter2D(mat, dst, mat.depth(), kernel);
A: Here's my attempt, I'm not sure whether it's accurate, but for very small amount of test data, it worked for me:
enum Conv2DShape {
FULL,
SAME,
VALID,
};
Mat conv2D( const Mat& input, const Mat& kernel, const Conv2DShape shape ){
Mat flipped_kernel;
flip( kernel, flipped_kernel, -1 );
Point2i pad;
Mat result, padded;
switch( shape ) {
case SAME:
padded = input;
pad = Point2i( 0, 0 );
break;
case VALID:
padded = input;
pad = Point2i( kernel.cols - 1, kernel.rows - 1);
break;
case FULL:
pad = Point2i( kernel.cols - 1, kernel.rows - 1);
copyMakeBorder( input, padded, pad.y, pad.y, pad.x, pad.x, BORDER_CONSTANT );
break;
default:
throw runtime_error("Unsupported convolutional shape");
}
Rect region = Rect( pad.x / 2, pad.y / 2, padded.cols - pad.x, padded.rows - pad.y);
filter2D( padded, result , -1, flipped_kernel, Point(-1, -1), 0, BORDER_CONSTANT );
return result( region );
}
|
stackoverflow
|
{
"language": "en",
"length": 334,
"provenance": "stackexchange_0000F.jsonl.gz:848682",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491883"
}
|
a18838af0b7ea894380c406ffb4eef4c1e71d2b6
|
Stackoverflow Stackexchange
Q: VirtualAlloc() failed: [0x00000008] Not enough storage is available to process this command I have been facing this error quite a long time, My production environment is running Apache 2.4 and php7 on a windows 2008 R2 enterprise platform.
My error log is full of these lines
VirtualAlloc() failed: [0x00000008] Not enough storage is available to process this command.
VirtualFree() failed: [0x000001e7] Attempt to access invalid address
After some time it leads to a 500 error, and later I have to restart the server it works fine only for some time.
Please help me in resolving these issues I have tried to update the memory from php and wordpress end but still no help
A: Your project may not be setup on the appropriate architecture.
Is your PHP 32 bit? Check the PHP_INT_SIZE constant to find out.
print_r(PHP_INT_SIZE); # 4 == 32bit // 8 == 64bit
Windows Server 2008 R2 is an x64 operating system, so an x86 version of Apache +/- x86 PHP could be capping the memory you may have installed on your machine and are trying to allocate. You won't be able to allocate more than 2G on on x86 version.
|
Q: VirtualAlloc() failed: [0x00000008] Not enough storage is available to process this command I have been facing this error quite a long time, My production environment is running Apache 2.4 and php7 on a windows 2008 R2 enterprise platform.
My error log is full of these lines
VirtualAlloc() failed: [0x00000008] Not enough storage is available to process this command.
VirtualFree() failed: [0x000001e7] Attempt to access invalid address
After some time it leads to a 500 error, and later I have to restart the server it works fine only for some time.
Please help me in resolving these issues I have tried to update the memory from php and wordpress end but still no help
A: Your project may not be setup on the appropriate architecture.
Is your PHP 32 bit? Check the PHP_INT_SIZE constant to find out.
print_r(PHP_INT_SIZE); # 4 == 32bit // 8 == 64bit
Windows Server 2008 R2 is an x64 operating system, so an x86 version of Apache +/- x86 PHP could be capping the memory you may have installed on your machine and are trying to allocate. You won't be able to allocate more than 2G on on x86 version.
A: I was getting this error if I do
composer update
It worked for me when I tried
composer install
A: I was facing the same error and this command fixed issue for me on localhost
php -d memory_limit=-1 "C:/ProgramData/ComposerSetup/bin/composer.phar"
then do composer update
A: Just Update latest version of composer
https://getcomposer.org/download/
otherwise do below steps
This setting only in Local machine(commands)
To Check PHP Memory
php -r "echo ini_get('memory_limit');"
output:
128M
To Know PHP path
php --ini
output:
Configuration File (php.ini) Path: C:\Windows
Loaded Configuration File: C:\xampp72\php\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed: (none)
Just Update your memory limit
; Maximum amount of memory a script may consume (128MB)
; http://php.net/memory-limit
memory_limit=512M
For Unlimit memory Access
memory_limit=-1
or
simply run for windows
php -d memory_limit=-1 "C:\ProgramData\ComposerSetup\bin\composer.phar" update
Note:
I recommend must download latest composer version
composer -v
A: Updating php.ini file working for me.
If you are using a Windows machine, you can try to increase the Memory Limit to 2 Gigabytes, as Laravel suggests, in your php.ini.
On XAMPP it is located at C:\xampp\php\php.ini
; Maximum amount of memory a script may consume (128MB)
; http://php.net/memory-limit
memory_limit = 2G
Restart the XAMPP server and run the composer update again.
Before:
After:
A: Try this
composer install --ignore-platform-reqs
|
stackoverflow
|
{
"language": "en",
"length": 408,
"provenance": "stackexchange_0000F.jsonl.gz:848684",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491893"
}
|
8d6e2a6269c7fbf461069b7257919d99d0c43c77
|
Stackoverflow Stackexchange
Q: iOS:Objective -C How to change push notification sound payload when app in background mode? In my application i am allowing user to change a sound for push notification.
When user selects Sound-A or Sound-B it plays properly when app is in active mode.
But when app is in background mode it always plays Sound-A because push notification payload sound is set to Sound-A.
{
"aps": {
"alert": "My News!",
"sound": "sound_a.mp3",
}
}
How can i overwrite it with users selected sound.
I have stored users selected sound in app preferences and i tried with replacing it, but it is not working.
NSString *soundName = [self getSoundTrack];
[pushArray setObject:soundName forKey:@"sound"];
A: you can play notification sound in background using AVplayer..working fine in my app
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
_audioPlayer=nil;
if(application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground ){
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@“soundName”
ofType:@"mp3"]];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(@"Error in audioPlayer: %@",
[error localizedDescription]);
} else {
[_audioPlayer prepareToPlay];
}
[_audioPlayer play];
}
|
Q: iOS:Objective -C How to change push notification sound payload when app in background mode? In my application i am allowing user to change a sound for push notification.
When user selects Sound-A or Sound-B it plays properly when app is in active mode.
But when app is in background mode it always plays Sound-A because push notification payload sound is set to Sound-A.
{
"aps": {
"alert": "My News!",
"sound": "sound_a.mp3",
}
}
How can i overwrite it with users selected sound.
I have stored users selected sound in app preferences and i tried with replacing it, but it is not working.
NSString *soundName = [self getSoundTrack];
[pushArray setObject:soundName forKey:@"sound"];
A: you can play notification sound in background using AVplayer..working fine in my app
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
_audioPlayer=nil;
if(application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground ){
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@“soundName”
ofType:@"mp3"]];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(@"Error in audioPlayer: %@",
[error localizedDescription]);
} else {
[_audioPlayer prepareToPlay];
}
[_audioPlayer play];
}
A: You can not change sound from your ios app, when receiving in background mode. The sound to be played is sent in payload. If you want play sound which user selected, you should be able to store that data in backend as well
A: If you want to programmatically change the sound using iOS client code, you can instead have the server send a silent push notification, then send a local notification with the configured sound when your app is woken up into the background.
However, the simpler solution is what others are saying. Update the server when a user changes their sound settings.
|
stackoverflow
|
{
"language": "en",
"length": 284,
"provenance": "stackexchange_0000F.jsonl.gz:848698",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491927"
}
|
876b843c6bb65713b97f403df54ec498ecca0adb
|
Stackoverflow Stackexchange
Q: Separating between Hebrew and English strings So I have this huge list of strings in Hebrew and English, and I want to extract from them only those in Hebrew, but couldn't find a regex example that works with Hebrew.
I have tried the stupid method of comparing every character:
import string
data = []
for s in slist:
found = False
for c in string.ascii_letters:
if c in s:
found = True
if not found:
data.append(s)
And it works, but it is of course very slow and my list is HUGE.
Instead of this, I tried comparing only the first letter of the string to string.ascii_letters which was much faster, but it only filters out those that start with an English letter, and leaves the "mixed" strings in there. I only want those that are "pure" Hebrew.
I'm sure this can be done much better... Help, anyone?
P.S: I prefer to do it within a python program, but a grep command that does the same would also help
A: To check if a string contains any ASCII letters (ie. non-Hebrew) use:
re.search('[' + string.ascii_letters + ']', s)
If this returns true, your string is not pure Hebrew.
|
Q: Separating between Hebrew and English strings So I have this huge list of strings in Hebrew and English, and I want to extract from them only those in Hebrew, but couldn't find a regex example that works with Hebrew.
I have tried the stupid method of comparing every character:
import string
data = []
for s in slist:
found = False
for c in string.ascii_letters:
if c in s:
found = True
if not found:
data.append(s)
And it works, but it is of course very slow and my list is HUGE.
Instead of this, I tried comparing only the first letter of the string to string.ascii_letters which was much faster, but it only filters out those that start with an English letter, and leaves the "mixed" strings in there. I only want those that are "pure" Hebrew.
I'm sure this can be done much better... Help, anyone?
P.S: I prefer to do it within a python program, but a grep command that does the same would also help
A: To check if a string contains any ASCII letters (ie. non-Hebrew) use:
re.search('[' + string.ascii_letters + ']', s)
If this returns true, your string is not pure Hebrew.
A: This one should work:
import re
data = [s for s in slist if re.match('^[a-zA-Z ]+$', s)]
This will pick all the strings that consist of lowercase and uppercase English letters and spaces. If the strings are allowed to contain digits or punctuation marks, the allowed characters should be included into the regex.
Edit: Just noticed, it filters out the English-only strings, but you need it do do the other way round. You can try this instead:
data = [s for s in slist if not re.match('^.*[a-zA-Z].*$', s)]
This will discard any string that contains at least one English letter.
A: Python has extensive unicode support. It depends on what you're asking for. Is a hebrew word one that contains only hebrew characters and whitespace, or is it simply a word that contains no latin characters? Either way, you can do so directly. Just create the criteria set and test for membership.
Note that testing for membership in a set is much faster than iteration through string.ascii_letters.
Please note that I do not speak hebrew so I may have missed a letter or two of the alphabet.
def is_hebrew(word):
hebrew = set("אבגדהוזחטיכךלמנס עפצקרשתםןףץ"+string.whitespace)
for char in word:
if char not in hebrew:
return False
return True
def contains_latin(word):
return any(char in set("abcdefghijklmnopqrstuvwxyz") for char in word.lower())
# a generator expression like this is a terser way of expressing the
# above concept.
hebrew_words = [word for word in words if is_hebrew(word)]
non_latin words = [word for word in words if not contains_latin(word)]
A: Another option would be to create a dictionary of hebrew words:
hebrew_words = {...}
And then you iterate through the list of words and compare them against this dictionary ignoring case. This will work much faster than other approaches (O(n) where n is the length of your list of words).
The downside is that you need to get all or most of hebrew words somewhere. I think it's possible to find it on the web in csv or some other form. Parse it and put it into python dictionary.
However, it makes sense if you need to parse such lists of words very often and quite quickly. Another problem is that the dictionary may contain not all hebrew words which will not give a completely right answer.
A: Try this:
>>> import re
>>> filter(lambda x: re.match(r'^[^\w]+$',x),s)
|
stackoverflow
|
{
"language": "en",
"length": 589,
"provenance": "stackexchange_0000F.jsonl.gz:848714",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491971"
}
|
359f9f1f3cafd3bc5a0ac5ccdf5f22a26636b79f
|
Stackoverflow Stackexchange
Q: How can I fetch all possible flights between two cities? I have a MySQL table called flight details as shown below:
Expected results:
*
*Bangalore to Chennai
*Bangalore to Delhi
*Bangalore to Kolkata
*Bangalore to Mumbai
*Chennai to Bangalore
*Chennai to Delhi
*Chennai to Kolkata
*Chennai to Mumbai
*Delhi to Chennai
*Delhi to Bangalore
*Delhi to Kolkata
*Delhi to Mumbai
*Kolkata to Chennai
*Kolkata to Delhi
*Kolkata to Bangalore
*Kolkata to Mumbai
*Mumbai to Chennai
*Mumbai to Delhi
*Mumbai to Kolkata
*Mumbai to Bangalore
not with same city.
A: try this,
SELECT fl1.flight_city,fl2.flight_city FROM `flight_details` as fl1 JOIN `flight_details` as fl2 on fl2.fid != fl1.fid
|
Q: How can I fetch all possible flights between two cities? I have a MySQL table called flight details as shown below:
Expected results:
*
*Bangalore to Chennai
*Bangalore to Delhi
*Bangalore to Kolkata
*Bangalore to Mumbai
*Chennai to Bangalore
*Chennai to Delhi
*Chennai to Kolkata
*Chennai to Mumbai
*Delhi to Chennai
*Delhi to Bangalore
*Delhi to Kolkata
*Delhi to Mumbai
*Kolkata to Chennai
*Kolkata to Delhi
*Kolkata to Bangalore
*Kolkata to Mumbai
*Mumbai to Chennai
*Mumbai to Delhi
*Mumbai to Kolkata
*Mumbai to Bangalore
not with same city.
A: try this,
SELECT fl1.flight_city,fl2.flight_city FROM `flight_details` as fl1 JOIN `flight_details` as fl2 on fl2.fid != fl1.fid
|
stackoverflow
|
{
"language": "en",
"length": 106,
"provenance": "stackexchange_0000F.jsonl.gz:848720",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491991"
}
|
a0ee1b258d6876a5b242d0a0dbd68feaef950b79
|
Stackoverflow Stackexchange
Q: Not able to add multiple target_id inside targer group using terraform I'm trying to create target groups and attach multiple machines to the target groups using terraform script.
I'm not able to attach multiple target_id please help me to achieve this.
A: Below code actually works for me.
resource "aws_alb_target_group_attachment" "test" {
count = 3 #This can be passed as variable.
target_group_arn = "${aws_alb_target_group.test.arn}"
target_id = "${element(split(",", join(",", aws_instance.web.*.id)), count.index)}"
}
Ref:
https://github.com/terraform-providers/terraform-provider-aws/issues/357
https://groups.google.com/forum/#!msg/terraform-tool/Mr7F3W8WZdk/ouVR3YsrAQAJ
|
Q: Not able to add multiple target_id inside targer group using terraform I'm trying to create target groups and attach multiple machines to the target groups using terraform script.
I'm not able to attach multiple target_id please help me to achieve this.
A: Below code actually works for me.
resource "aws_alb_target_group_attachment" "test" {
count = 3 #This can be passed as variable.
target_group_arn = "${aws_alb_target_group.test.arn}"
target_id = "${element(split(",", join(",", aws_instance.web.*.id)), count.index)}"
}
Ref:
https://github.com/terraform-providers/terraform-provider-aws/issues/357
https://groups.google.com/forum/#!msg/terraform-tool/Mr7F3W8WZdk/ouVR3YsrAQAJ
A: Thanks for your quick reply.
Actually giving seperate tag like test1 and test2 for aws_alb_target_group_attachment helped me to add multiple target instances inside one taget group.
resource "aws_alb_target_group_attachment" "test1" {
target_group_arn = "${aws_alb_target_group.test.arn}"
port = 8080
target_id = "${aws_instance.inst1.id}"
}
resource "aws_alb_target_group_attachment" "test2" {
target_group_arn = "${aws_alb_target_group.test.arn}"
port = 8080
target_id = "${aws_instance.inst2.id}"
}
A: As of Terraform 0.12, this could simply be
resource "aws_alb_target_group_attachment" "test" {
count = length(aws_instance.test)
target_group_arn = aws_alb_target_group.test.arn
target_id = aws_instance.test[count.index].id
}
assuming aws_instance.test returns a list.
https://blog.gruntwork.io/terraform-tips-tricks-loops-if-statements-and-gotchas-f739bbae55f9 is an excellent reference.
A: Try creating a list of instance ID's and then iterate over using the count index.
For example:
variable "instance_list" {
description = "Push these instances to ALB"
type = "list"
default = ["i00001", "i00002", "i00003"]
}
resource "aws_alb_target_group_attachment" "test" {
count = "${var.instance_list}"
target_group_arn = "${aws_alb_target_group.test.arn}"
target_id = "${element(var.instance_list, count.index)}"
port = 80
}
A: I created an EMR from terraform and attached multiple "CORE" type EC2 instances to a target group.
The first step would be to retrieve existing instances (which are in "running" state)
data "aws_instances" "core_instances" {
instance_state_names = ["running"]
instance_tags = {
"aws:elasticmapreduce:instance-group-role" = "CORE"
"terraform" = "true"
}
}
Next, retrieve an existing VPC
data "aws_vpc" "test_vpc" {
filter {
name = "tag:Name"
values = ["your-vpc-name"]
}
}
Use the above data to create a target group and then attach instances to it:
resource "aws_lb_target_group" "core_lb" {
name = "core-emr-target-group"
port = 8765
protocol = "TCP"
target_type = "instance"
vpc_id = data.aws_vpc.test_vpc.id
}
resource "aws_lb_target_group_attachment" "core_lb_instances" {
for_each = toset(data.aws_instances.core_instances.ids)
target_group_arn = aws_lb_target_group.core_lb.arn
target_id = each.value
}
Note that you would have to convert the value returned by aws_instances, which is a list, to a set.
A: From my side I found this solution:
*
*Define a data to collect EC2 IDs from an autoscaling security group:
data "aws_instances" "team_deployment" {
instance_tags = {
Name = local.ec2_name
}
instance_state_names = ["running"]
}
And be sure that instances IDs are the right ones with and evidence (like output)
output "autoscaling_group_ec2_ids" {
value = data.aws_instances.team_deployment.ids
}
*Create as many attachments as IDs has found. Use count parameter:
resource "aws_lb_target_group_attachment" "team_deployment" {
count = length(data.aws_instances.team_deployment.ids)
target_group_arn = data.terraform_remote_state.common_resources.outputs.target_group_api.arn
target_id = data.aws_instances.team_deployment.ids[count.index]
port = var.ecr_image_port
depends_on = [data.aws_instances.team_deployment]
}
And problem solved!
|
stackoverflow
|
{
"language": "en",
"length": 447,
"provenance": "stackexchange_0000F.jsonl.gz:848721",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44491994"
}
|
eceab7b2e15b64be2431339c02ef9c7e8d555d5c
|
Stackoverflow Stackexchange
Q: Post-build script with electron-builder Is it possible to run some sort of script post-build before packing the installer with electron-builder? I need to generate an extra file that should be distributed but I need the binary, the .exe, to generate it.
|
Q: Post-build script with electron-builder Is it possible to run some sort of script post-build before packing the installer with electron-builder? I need to generate an extra file that should be distributed but I need the binary, the .exe, to generate it.
|
stackoverflow
|
{
"language": "en",
"length": 42,
"provenance": "stackexchange_0000F.jsonl.gz:848724",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492003"
}
|
fa339240903a24a3551d39f0e536d8954ffa92ec
|
Stackoverflow Stackexchange
Q: using variable name in lodash collection Question is bit crazy. Is there any possibility to using variable name instead of another, clearly, consider the following code where I have to switch over to any variable name "people" or "student" accordingly
var people=[
{name:"akash",age:25},
{name:"abi",age:22}
];
var student =[
{name:"Sanjai",age:25},
{name:"Ravi",age:35},
{name:"Bopara",age:36}
];
var variables=["people","student"];
var result= _.find(variables[0], function(o) { return o.age < 35; });
console.log(result);
A: Sure, just put variables into array instead of strings:
var variables=[people, student];
Full example:
var people=[
{name:"akash",age:25},
{name:"abi",age:22}
];
var student =[
{name:"Sanjai",age:25},
{name:"Ravi",age:35},
{name:"Bopara",age:36}
];
var variables=[people, student];
var result= _.find(variables[0], function(o) { return o.age < 35; });
console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
|
Q: using variable name in lodash collection Question is bit crazy. Is there any possibility to using variable name instead of another, clearly, consider the following code where I have to switch over to any variable name "people" or "student" accordingly
var people=[
{name:"akash",age:25},
{name:"abi",age:22}
];
var student =[
{name:"Sanjai",age:25},
{name:"Ravi",age:35},
{name:"Bopara",age:36}
];
var variables=["people","student"];
var result= _.find(variables[0], function(o) { return o.age < 35; });
console.log(result);
A: Sure, just put variables into array instead of strings:
var variables=[people, student];
Full example:
var people=[
{name:"akash",age:25},
{name:"abi",age:22}
];
var student =[
{name:"Sanjai",age:25},
{name:"Ravi",age:35},
{name:"Bopara",age:36}
];
var variables=[people, student];
var result= _.find(variables[0], function(o) { return o.age < 35; });
console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
|
stackoverflow
|
{
"language": "en",
"length": 109,
"provenance": "stackexchange_0000F.jsonl.gz:848728",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492015"
}
|
ae4f4e0bde1e0b9adff5338c54ac498f694fe44f
|
Stackoverflow Stackexchange
Q: Scala grammar for Antlr4 is not working I'm using the grammar on the Antlr github page: https://github.com/antlr/grammars-v4/tree/master/scala
But the grammar has a problem based on reading the reported issue on GitHub.
Here is my code:
InputStream targetStream = new FileInputStream(file);
System.out.println(targetStream.toString());
ANTLRInputStream input = new ANTLRInputStream(targetStream);
ScalaLexer lexer = new ScalaLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
...
The error message is:
line 1:0 no viable alternative at input 'object HelloWorld {'
I searched the issue, several other people also found the problem. It is hard to understand why such a state-of-the-art tool has such an obvious issue, but the issue is there. I'm not an export of parsing and just need a working scala parser in Java. Are there any other grammar I can use for scala? Or are there any other scala parser written in Java?
|
Q: Scala grammar for Antlr4 is not working I'm using the grammar on the Antlr github page: https://github.com/antlr/grammars-v4/tree/master/scala
But the grammar has a problem based on reading the reported issue on GitHub.
Here is my code:
InputStream targetStream = new FileInputStream(file);
System.out.println(targetStream.toString());
ANTLRInputStream input = new ANTLRInputStream(targetStream);
ScalaLexer lexer = new ScalaLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
...
The error message is:
line 1:0 no viable alternative at input 'object HelloWorld {'
I searched the issue, several other people also found the problem. It is hard to understand why such a state-of-the-art tool has such an obvious issue, but the issue is there. I'm not an export of parsing and just need a working scala parser in Java. Are there any other grammar I can use for scala? Or are there any other scala parser written in Java?
|
stackoverflow
|
{
"language": "en",
"length": 138,
"provenance": "stackexchange_0000F.jsonl.gz:848751",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492097"
}
|
6a63d124f637d1340bdd3115748aeea66fcb3fe4
|
Stackoverflow Stackexchange
Q: React is rendering [object object] rather than the JSX I'm trying to render out journal entries on my site with an object (not array) and I am running into an issue, here is my current code
populateJournal(){
const j = Object.values(this.state.journal);
var journalEntries = '';
for (var i = 0; i < j.length; i++){
journalEntries+=
<div>
<h3>{j[i].title} - {j[i].date}</h3>
<p>{j[i].entry}</p>
</div>;
}
return(<div>{journalEntries}</div>);
}
When i call this function it renders "<div>[object object]</div>" and the text between the divs is plain text.
When i change the loop to say "journalEntries = <div...." it renders out the last journal entry as expected, but the issue is that it's not actually appending the journal entries with the loop.
ideas?
A: Why you don't use from .map(), try this:
render(){
const j = Object.values(this.state.journal);
return(
<div>
{j.map((item,index) =>
<div key={index}>
<h3>{item.title} - {item.date}</h3>
<p>{item.entry}</p>
</div>
)}
</div>
);
}
|
Q: React is rendering [object object] rather than the JSX I'm trying to render out journal entries on my site with an object (not array) and I am running into an issue, here is my current code
populateJournal(){
const j = Object.values(this.state.journal);
var journalEntries = '';
for (var i = 0; i < j.length; i++){
journalEntries+=
<div>
<h3>{j[i].title} - {j[i].date}</h3>
<p>{j[i].entry}</p>
</div>;
}
return(<div>{journalEntries}</div>);
}
When i call this function it renders "<div>[object object]</div>" and the text between the divs is plain text.
When i change the loop to say "journalEntries = <div...." it renders out the last journal entry as expected, but the issue is that it's not actually appending the journal entries with the loop.
ideas?
A: Why you don't use from .map(), try this:
render(){
const j = Object.values(this.state.journal);
return(
<div>
{j.map((item,index) =>
<div key={index}>
<h3>{item.title} - {item.date}</h3>
<p>{item.entry}</p>
</div>
)}
</div>
);
}
A: Instead of a defining journalEntries as a string define it as an array and push the JSX elements to the array in order to render, for example:
populateJournal() {
const j = Object.values(this.state.journal);
var journalEntries = [];
for (var i = 0; i < j.length; i++) {
journalEntries.push(
<div>
<h3>{j[i].title} - {j[i].date}</h3>
<p>{j[i].entry}</p>
</div>
);
}
return (<div>{journalEntries}</div>);
}
When you append to the string, you are not actually appending a string but an object which is incorrect and hence you get [object Object]
You can also use map to render your context. See this answer on how to use map:
REACT JS: Map over an array of objects to render in JSX
A: You don't need popluateJournal, just use this in render():
render() {
//const j = Object.values(this.state.journal);
const j = [{'title':'one','date':'12/03/17','entry':'This is an entry'},
{'title':'two','date':'14/03/17','entry':'This is another entry'}
];
//inject j as property into Test
const Test = ({journals}) => (
<div>
{journals.map(journal => (
<div>
<h3>{journal.title} - {journal.date}</h3>
<p>{journal.entry}</p>
</div>
))}
</div>
);
return (
<div><Test journals={j}></Test></div>
);
}
A: you already have the journal data on state,
why would you construct the element outside render?
the correct way to do it is to map it directly on render.
populateJournal(){
const j = Object.values(this.state.journal);
return(<div>{
j && j.map((journal,i)=>{
return ( <div key={"journal"+i}>
<h3>{journal.title} - {journal.date}</h3>
<p>{journal.entry}</p>
</div>
})
}</div>);
}
remember to put the "key" on each mapped element.
|
stackoverflow
|
{
"language": "en",
"length": 380,
"provenance": "stackexchange_0000F.jsonl.gz:848770",
"question_score": "33",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492166"
}
|
381b34ea80c4a5458fe5cf9a8ebf1cb81eb149c5
|
Stackoverflow Stackexchange
Q: React Native ios build : Can't find node I have a prototype ready to go and the project is jammed with build:
error: Can't find 'node' binary to build React Native bundle If you
have non-standard nodejs installation, select your project in Xcode,
find 'Build Phases' - 'Bundle React Native code and images' and change
NODE_BINARY to absolute path to your node executable (you can find it
by invoking 'which node' in the terminal)
this feedback is helpless for me, i do have node with nvm. is this something related to bash?
A: nvm alias default 14
OR
sudo ln -s "$(which node)" /usr/local/bin/node
This made my Xcode 12.4 see node
|
Q: React Native ios build : Can't find node I have a prototype ready to go and the project is jammed with build:
error: Can't find 'node' binary to build React Native bundle If you
have non-standard nodejs installation, select your project in Xcode,
find 'Build Phases' - 'Bundle React Native code and images' and change
NODE_BINARY to absolute path to your node executable (you can find it
by invoking 'which node' in the terminal)
this feedback is helpless for me, i do have node with nvm. is this something related to bash?
A: nvm alias default 14
OR
sudo ln -s "$(which node)" /usr/local/bin/node
This made my Xcode 12.4 see node
A: I found one
solution
First find your current node, in shell
which node
then copy your node url to
export NODE_BINARY=[your node path]
../node_modules/react-native/packager/react-native-xcode.sh to node_modules/react-native/scripts/react-native-xcode.sh
A: If you are developing a React Native based solution and you are using NVM for local Node versioning, the error may be due to this.
XCode cannot find the Node version, of course XCode fetches the Node in the / usr / local / bin / node directory and NVM stores the Node in another directory like Users / $ {my-user} /. Nvm / versions /node/v14.16.0/bin/node
To work it is enough to create an alias for XCode to find the Node in its default search:
ln -s $ (which node) / usr / local / bin / node
A: The best solution is to actually do ln -s $(which node) /usr/local/bin, this will create a "symlink" from /usr/local/bin/node to wherever your node is, this is important because most apps looks at node at this path. You probably don't want to do export NODE_BINARY=[your node path] because when another teammate has a different OS or different installation of node (i.e., one is using nvm the other is using homebrew), then the same error will occur, it will also happen when building for production. So just go with ln -s $(which node) /usr/local/bin to be safe.
A: In 2022 the default build looks in ios/.xcode.env.local and ios/.xcode.env for environment customizations. The provided .xcode.env has an example enabling nvm and setting NODE_BINARY.
This is configured in Build Phases -> Bundle React Native code and images. The shell script looks as follows circa 10/2022:
set -e
WITH_ENVIRONMENT="../node_modules/react-native/scripts/xcode/with-environment.sh"
REACT_NATIVE_XCODE="../node_modules/react-native/scripts/react-native-xcode.sh"
/bin/sh -c "$WITH_ENVIRONMENT $REACT_NATIVE_XCODE"
The Input Files section for this script has
$(SRCROOT)/.xcode.env.local
$(SRCROOT)/.xcode.env
The default .xcode.env looks like this now:
# This `.xcode.env` file is versioned and is used to source the environment
# used when running script phases inside Xcode.
# To customize your local environment, you can create an `.xcode.env.local`
# file that is not versioned.
# NODE_BINARY variable contains the PATH to the node executable.
#
# Customize the NODE_BINARY variable here.
# For example, to use nvm with brew, add the following line
#. "$(brew --prefix nvm)/nvm.sh" --no-use
export NODE_BINARY=$(command -v node)
To reliably get node set, configure your project properties to the current default values and update one of the two reference env files.
A: Solution for nvm users :
In your build phases scripts, just add
# Fix for machines using nvm
if [[ -s "$HOME/.nvm/nvm.sh" ]]; then
. "$HOME/.nvm/nvm.sh"
elif [[ -x "$(command -v brew)" && -s "$(brew --prefix nvm)/nvm.sh" ]]; then
. "$(brew --prefix nvm)/nvm.sh"
fi
Above export NODE_BINARY=node. This will make Xcode work regardless of your machine using nvm.
A: The solution for me is to set a default version of node with nvm in your profile. This works for bash or zsh:
Add this to your .zshrc or .bashrc
# default node version for nvm
nvm use 8.9.3
Be sure to change it to the version you want when starting a new terminal.
A: If this command says /usr/local/bin/node: File exists you need to know that the link already exists to maybe a different version of node. In my case, to install yarn, brew installed a separate nodejs v15 and linked the file to its binary. Although I use nvm to have nodejs v14 and nodejs v16. This extra nodejs was the reason for the error mentioned in question.
Simply run sudo rm -f /usr/local/bin/node to remove the link followed by the command sudo ln -s $(which node) /usr/local/bin/node to create correct link.
A: @brunocascio solution on the comment is simpler and less invasive, create a symlink to node, on command line:
ln -s $(which node) /usr/local/bin/node
Update:
On new M1 Mac I had to cd /usr/local then mkdir bin (or just sudo mkdir /usr/local/bin) first.
thanks leo for the comment
A: From the React Native environment setup documentation:
Starting from React Native version 0.69, it is possible to configure the Xcode environment using the .xcode.env file provided by the template.
The .xcode.env file contains an environment variable to export the path to the node executable in the NODE_BINARY variable. This is the suggested approach to decouple the build infrastructure from the system version of node. You should customize this variable with your own path or your own node version manager, if it differs from the default.
so in your project's root directory, look in the ios/ subdirectory, create or update the file .xcode.env to export your node binary:
file: /ios/.xcode.env
# To use nvm with brew, uncomment the line below
# . "$(brew --prefix nvm)/nvm.sh" --no-use
export NODE_BINARY=$(command -v node)
This file will be loaded by Xcode and properly provide the node binary for your build process. Note that if you're using NVM for your node environment, you'll need to uncomment the line to initialize your NVM environment before exporting the node binary.
Hope this helps! :)
A: For anyone that stumbles upon this in 2022 here is my situation and how I fixed it.
*
*react-native --version -> 4.14
*npx --version -> 6.14.9
*node --version -> 12.14.1
*We use TypeScript also.
XCode "Bundle React Native code and images"
export ENTRY_FILE=src/App.tsx
../node_modules/react-native/scripts/react-native-xcode.sh
../node_modules/expo-constants/scripts/get-app-config-ios.sh
../node_modules/expo-updates/scripts/create-manifest-ios.sh
Remove the export NODE_BINARY=node line of code. It's not needed anymore. The way I figured this out was reading through the source code found in ../node_modules/react-native/scripts/react-native-xcode.sh If you look there, you'll find nvm/node sourcing being done for you.
A: This error occurs if the path of the "node" changes somehow. I have solved this issue by using this command:
sudo ln -s $(which node) /usr/local/bin/node"
A: In my case, I had to choose a lower version of node
from node/18.7.0 to node/16.9.0
react-native: 0.66.3
Xcode: 14.1
MacOs: 12.6.1
A: Open Xcode, then choose "Preferences..." from the Xcode menu.
Go to the Locations panel and install the tools by selecting the most recent version in the Command Line Tools dropdown.
select command line tools like as this image
A: If you are using Mac, check if you have installed node with brew. In this case it cannot find the path. Install node by downloading from the official website
|
stackoverflow
|
{
"language": "en",
"length": 1137,
"provenance": "stackexchange_0000F.jsonl.gz:848779",
"question_score": "74",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492197"
}
|
82cd7ee467b41ab7008ef9b1a2c78652905e0c3b
|
Stackoverflow Stackexchange
Q: How to change the order of object( not array ) in angular js I have one set of object(key value pair )
var data = {
"AnomalyEnableLatch": "false",
"DistLogPeriod": "0",
"AedCooldown": "0",
"AedEnableLatch": "false",
"AedGuardBand": "0",
"AedSensitivity": "0",
"AedWindowSize": "0",
"AnomalyCurrentNoiseFloor": "10",
"AnomalyGuardBandSize": "32",
"AnomalyKsigToStart": "40",
"AnomalyMinSnrToStop": "100",
"AnomalyWindowSize": "651"
};
This list will be dynamic one.
I need to order by two params
one is starts with aed and another set starts with anomaly.
Actually, i am getting correct order from api response. While working on js, order changing automatically by asc.
It should not do like this. I need to do work on actual order.
Otherwise i need to change the order. I need a order as given in above set
http://jsfiddle.net/MohaideenIsmail/ADukg/11659/
A: Actually, the order is not changing. But the console will show like that.
Just observe console.log(Object.keys(data)) before using filter. It's just un ordered array of object properties. Now, if you want to sort alphabetically, then
you could do is use Object.keys(), and sort the Array, then iterate it through object.
Object.keys(data)
.sort() // sort keys alphabetically
.forEach(function(v, i) {
console.log(v, data[v]); // access properties(keys) alphabetically
});
|
Q: How to change the order of object( not array ) in angular js I have one set of object(key value pair )
var data = {
"AnomalyEnableLatch": "false",
"DistLogPeriod": "0",
"AedCooldown": "0",
"AedEnableLatch": "false",
"AedGuardBand": "0",
"AedSensitivity": "0",
"AedWindowSize": "0",
"AnomalyCurrentNoiseFloor": "10",
"AnomalyGuardBandSize": "32",
"AnomalyKsigToStart": "40",
"AnomalyMinSnrToStop": "100",
"AnomalyWindowSize": "651"
};
This list will be dynamic one.
I need to order by two params
one is starts with aed and another set starts with anomaly.
Actually, i am getting correct order from api response. While working on js, order changing automatically by asc.
It should not do like this. I need to do work on actual order.
Otherwise i need to change the order. I need a order as given in above set
http://jsfiddle.net/MohaideenIsmail/ADukg/11659/
A: Actually, the order is not changing. But the console will show like that.
Just observe console.log(Object.keys(data)) before using filter. It's just un ordered array of object properties. Now, if you want to sort alphabetically, then
you could do is use Object.keys(), and sort the Array, then iterate it through object.
Object.keys(data)
.sort() // sort keys alphabetically
.forEach(function(v, i) {
console.log(v, data[v]); // access properties(keys) alphabetically
});
A: As commented, you cannot sort/order keys in object. But you can order the way you access the keys.
You can use following JSFiddle to debug or following SO snippet.
var myApp = angular.module('myApp', []);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
$scope.data = {
"AnomalyEnableLatch": "false",
"DistLogPeriod": "0",
"AedCooldown": "0",
"AedEnableLatch": "false",
"AedGuardBand": "0",
"AedSensitivity": "0",
"AedWindowSize": "0",
"AnomalyCurrentNoiseFloor": "10",
"AnomalyGuardBandSize": "32",
"AnomalyKsigToStart": "40",
"AnomalyMinSnrToStop": "100",
"AnomalyWindowSize": "651"
};
$scope.keys = Object.keys($scope.data);
$scope.keys.sort(function(a, b) {
return getDifference(a, b, "Aed") || getDifference(a, b, "Anomal") || a.localeCompare(b)
});
function getDifference(a, b, s) {
return b.startsWith(s) - a.startsWith(s)
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
<div ng-app>
<div ng-controller="MyCtrl">
Hello, {{name}}!
<div>
<ul>
<li ng-repeat="k in keys">
{{k}} : {{ data[k] }}</li>
</ul>
</div>
</div>
</div>
A: The order of keys in a JavaScript object is not guaranteed. There are two possible ways to approach this:
*
*The keys and their order are known before: In this case, predefine your array of keys and use Array.prototype.map to build an ordered array from your data map.
*If the keys are dynamic too, use Object.keys to extract the keys, sort them as needed using Array.prototype.sort(compareFn). Then, you can use this sorted key array as described in method 1
Sample Code for getting an ordered array out of a map given an ordered set of keys:
var data = {...}; //Original data map
var orderedKeys = ["firstKey", "secondKey"]; //Array of preordered keys
var sortedArrayOfMaps = orderedKeys.map(function(key){var o={}; o[key]=data[key]; return o;}) //Use map to get ordered array of objects
I have also updated the JS Fiddle using this method for your reference
|
stackoverflow
|
{
"language": "en",
"length": 460,
"provenance": "stackexchange_0000F.jsonl.gz:848792",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492241"
}
|
393f56a624ae0eee87600b0daa88e6d25cfb1986
|
Stackoverflow Stackexchange
Q: Is there an Unminified Version of google analytics? I'm trying to find the unminified version of: https://www.google-analytics.com/analytics.js.
I'm able to run it through a beautifier, but still is not helping much.
Google provides this unminified version of the tracking snippet: https://developers.google.com/analytics/devguides/collection/analyticsjs/tracking-snippet-reference
I'm wondering if there's something similar about their analytics code.
|
Q: Is there an Unminified Version of google analytics? I'm trying to find the unminified version of: https://www.google-analytics.com/analytics.js.
I'm able to run it through a beautifier, but still is not helping much.
Google provides this unminified version of the tracking snippet: https://developers.google.com/analytics/devguides/collection/analyticsjs/tracking-snippet-reference
I'm wondering if there's something similar about their analytics code.
|
stackoverflow
|
{
"language": "en",
"length": 52,
"provenance": "stackexchange_0000F.jsonl.gz:848807",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492290"
}
|
474f6c7d4e038734e8c81858b476f3fb0b8cd71b
|
Stackoverflow Stackexchange
Q: type hinting array with 2 entries / phpdoc for array say i have this
function foo(){
return [1, 'bippo'];
}
how can I write phpdoc that it creates automatically on autocomplete something like this
list($x, $y) = foo();
A: As stated in the phpDocumentor: Defining a 'Type' section Array you can specify an array containing multiple types as @return (int|string)[], which means that the return type of this function is an array that can contain elements which are either of type int or string
|
Q: type hinting array with 2 entries / phpdoc for array say i have this
function foo(){
return [1, 'bippo'];
}
how can I write phpdoc that it creates automatically on autocomplete something like this
list($x, $y) = foo();
A: As stated in the phpDocumentor: Defining a 'Type' section Array you can specify an array containing multiple types as @return (int|string)[], which means that the return type of this function is an array that can contain elements which are either of type int or string
|
stackoverflow
|
{
"language": "en",
"length": 85,
"provenance": "stackexchange_0000F.jsonl.gz:848817",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492338"
}
|
a9ff54df8b8aaf4a3325e656544c263fe1127137
|
Stackoverflow Stackexchange
Q: Safe Area of Xcode 9 While exploring Xcode9 Beta Found Safe Area on Interface builders View hierarchy viewer. Got curious and tried to know about Safe Area on Apples documentation, in gist the doc says "The the view area which directly interacts with Auto layout" But it did not satisfy me, I want to know Practical use of this new thing.
Do any one have some clue?
Conclusion paragraph from Apple doc for Safe area.
The UILayoutGuide class is designed to perform all the tasks previously performed by dummy views, but to do it in a safer, more efficient manner. Layout guides do not define a new view. They do not participate in the view hierarchy. Instead, they simply define a rectangular region in their owning view’s coordinate system that can interact with Auto Layout.
A: Apple introduced the topLayoutGuide and bottomLayoutGuide as properties of UIViewController way back in iOS 7. They allowed you to create constraints to keep your content from being hidden by UIKit bars like the status, navigation or tab bar. These layout guides are deprecated in iOS 11 and replaced by a single safe area layout guide.
Refer link for more information.
|
Q: Safe Area of Xcode 9 While exploring Xcode9 Beta Found Safe Area on Interface builders View hierarchy viewer. Got curious and tried to know about Safe Area on Apples documentation, in gist the doc says "The the view area which directly interacts with Auto layout" But it did not satisfy me, I want to know Practical use of this new thing.
Do any one have some clue?
Conclusion paragraph from Apple doc for Safe area.
The UILayoutGuide class is designed to perform all the tasks previously performed by dummy views, but to do it in a safer, more efficient manner. Layout guides do not define a new view. They do not participate in the view hierarchy. Instead, they simply define a rectangular region in their owning view’s coordinate system that can interact with Auto Layout.
A: Apple introduced the topLayoutGuide and bottomLayoutGuide as properties of UIViewController way back in iOS 7. They allowed you to create constraints to keep your content from being hidden by UIKit bars like the status, navigation or tab bar. These layout guides are deprecated in iOS 11 and replaced by a single safe area layout guide.
Refer link for more information.
A:
The Safe Area Layout Guide helps avoid underlapping System UI elements
when positioning content and controls.
The Safe Area is the area in between System UI elements which are Status Bar, Navigation Bar and Tool Bar or Tab Bar. So when you add a Status bar to your app, the Safe Area shrink. When you add a Navigation Bar to your app, the Safe Area shrinks again.
On the iPhone X, the Safe Area provides additional inset from the top and bottom screen edges in portrait even when no bar is shown. In landscape, the Safe Area is inset from the sides of the screens and the home indicator.
This is taken from Apple's video Designing for iPhone X where they also visualize how different elements affect the Safe Area.
A:
Safe Area is a layout guide (Safe Area Layout Guide).
The layout guide representing the portion of your view that is unobscured by bars and other content. In iOS 11+, Apple is deprecating the top and bottom layout guides and replacing them with a single safe area layout guide.
When the view is visible onscreen, this guide reflects the portion of the view that is not covered by other content. The safe area of a view reflects the area covered by navigation bars, tab bars, toolbars, and other ancestors that obscure a view controller's view. (In tvOS, the safe area incorporates the screen's bezel, as defined by the overscanCompensationInsets property of UIScreen.) It also covers any additional space defined by the view controller's additionalSafeAreaInsets property. If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the layout guide always matches the edges of the view.
For the view controller's root view, the safe area in this property represents the entire portion of the view controller's content that is obscured, and any additional insets that you specified. For other views in the view hierarchy, the safe area reflects only the portion of that view that is obscured. For example, if a view is entirely within the safe area of its view controller's root view, the edge insets in this property are 0.
According to Apple, Xcode 9 - Release note
Interface Builder uses UIView.safeAreaLayoutGuide as a replacement for the deprecated Top and Bottom layout guides in UIViewController. To use the new safe area, select Safe Area Layout Guides in the File inspector for the view controller, and then add constraints between your content and the new safe area anchors. This prevents your content from being obscured by top and bottom bars, and by the overscan region on tvOS. Constraints to the safe area are converted to Top and Bottom when deploying to earlier versions of iOS.
Here is simple reference as a comparison (to make similar visual effect) between existing (Top & Bottom) Layout Guide and Safe Area Layout Guide.
Safe Area Layout:
AutoLayout
How to work with Safe Area Layout?
Follow these steps to find solution:
*
*Enable 'Safe Area Layout', if not enabled.
*Remove 'all constraint' if they shows connection with with Super view and re-attach all with safe layout anchor. OR Double click on a constraint and edit connection from super view to SafeArea anchor
Here is sample snapshot, how to enable safe area layout and edit constraint.
Here is result of above changes
Layout Design with SafeArea
When designing for iPhone X, you must ensure that layouts fill the screen and aren't obscured by the device's rounded corners, sensor housing, or the indicator for accessing the Home screen.
Most apps that use standard, system-provided UI elements like navigation bars, tables, and collections automatically adapt to the device's new form factor. Background materials extend to the edges of the display and UI elements are appropriately inset and positioned.
For apps with custom layouts, supporting iPhone X should also be relatively easy, especially if your app uses Auto Layout and adheres to safe area and margin layout guides.
Here is sample code (Ref from: Safe Area Layout Guide):
If you create your constraints in code use the safeAreaLayoutGuide property of UIView to get the relevant layout anchors. Let’s recreate the above Interface Builder example in code to see how it looks:
Assuming we have the green view as a property in our view controller:
private let greenView = UIView()
We might have a function to set up the views and constraints called from viewDidLoad:
private func setupView() {
greenView.translatesAutoresizingMaskIntoConstraints = false
greenView.backgroundColor = .green
view.addSubview(greenView)
}
Create the leading and trailing margin constraints as always using the layoutMarginsGuide of the root view:
let margins = view.layoutMarginsGuide
NSLayoutConstraint.activate([
greenView.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
greenView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
])
Now unless you are targeting iOS 11 only you will need to wrap the safe area layout guide constraints with #available and fall back to top and bottom layout guides for earlier iOS versions:
if #available(iOS 11, *) {
let guide = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
greenView.topAnchor.constraintEqualToSystemSpacingBelow(guide.topAnchor, multiplier: 1.0),
guide.bottomAnchor.constraintEqualToSystemSpacingBelow(greenView.bottomAnchor, multiplier: 1.0)
])
} else {
let standardSpacing: CGFloat = 8.0
NSLayoutConstraint.activate([
greenView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: standardSpacing),
bottomLayoutGuide.topAnchor.constraint(equalTo: greenView.bottomAnchor, constant: standardSpacing)
])
}
Result:
Following UIView extension, make it easy for you to work with SafeAreaLayout programatically.
extension UIView {
// Top Anchor
var safeAreaTopAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.topAnchor
} else {
return self.topAnchor
}
}
// Bottom Anchor
var safeAreaBottomAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.bottomAnchor
} else {
return self.bottomAnchor
}
}
// Left Anchor
var safeAreaLeftAnchor: NSLayoutXAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.leftAnchor
} else {
return self.leftAnchor
}
}
// Right Anchor
var safeAreaRightAnchor: NSLayoutXAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.rightAnchor
} else {
return self.rightAnchor
}
}
}
Here is sample code in Objective-C:
*
*How to add a safe area programmatically
Here is Apple Developer Official Documentation for Safe Area Layout Guide
Safe Area is required to handle user interface design for iPhone-X. Here is basic guideline for How to design user interface for iPhone-X using Safe Area Layout
A: I want to mention something that caught me first when I was trying to adapt a SpriteKit-based app to avoid the round edges and "notch" of the new iPhone X, as suggested by the latest Human Interface Guidelines: The new property safeAreaLayoutGuide of UIView needs to be queried after the view has been added to the hierarchy (for example, on -viewDidAppear:) in order to report a meaningful layout frame (otherwise, it just returns the full screen size).
From the property's documentation:
The layout guide representing the portion of your view that is
unobscured by bars and other content.
When the view is visible onscreen, this guide reflects the portion of the view that is not covered by navigation bars, tab bars,
toolbars, and other ancestor views. (In tvOS, the safe area reflects
the area not covered the screen's bezel.) If the view is not
currently installed in a view hierarchy, or is not yet visible
onscreen, the layout guide edges are equal to the edges of the view.
(emphasis mine)
If you read it as early as -viewDidLoad:, the layoutFrame of the guide will be {{0, 0}, {375, 812}} instead of the expected {{0, 44}, {375, 734}}
A:
*
*Earlier in iOS 7.0–11.0 <Deprecated> UIKit uses the topLayoutGuide & bottomLayoutGuide which is UIView property
*iOS11+ uses safeAreaLayoutGuide which is also UIView property
*Enable Safe Area Layout Guide check box from file inspector.
*Safe areas help you place your views within the visible portion of the overall interface.
*In tvOS, the safe area also includes the screen’s overscan insets, which represent the area covered by the screen’s bezel.
*safeAreaLayoutGuide reflects the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor viewss.
*Use safe areas as an aid to laying out your content like UIButton
etc.
*When designing for iPhone X, you must ensure that layouts fill the screen and aren't obscured by the device's rounded corners, sensor housing, or the indicator for accessing the Home screen.
*Make sure backgrounds extend to the edges of the display, and that vertically scrollable layouts, like tables and collections, continue all the way to the bottom.
*The status bar is taller on iPhone X than on other iPhones. If your app assumes a fixed status bar height for positioning content below the status bar, you must update your app to dynamically position content based on the user's device. Note that the status bar on iPhone X doesn't change height when background tasks like voice recording and location tracking are active
print(UIApplication.shared.statusBarFrame.height)//44 for iPhone X, 20 for other iPhones
*Height of home indicator container is 34 points.
*Once you enable Safe Area Layout Guide you can see safe area constraints property listed in the interface builder.
You can set constraints with respective of self.view.safeAreaLayoutGuide as-
ObjC:
self.demoView.translatesAutoresizingMaskIntoConstraints = NO;
UILayoutGuide * guide = self.view.safeAreaLayoutGuide;
[self.demoView.leadingAnchor constraintEqualToAnchor:guide.leadingAnchor].active = YES;
[self.demoView.trailingAnchor constraintEqualToAnchor:guide.trailingAnchor].active = YES;
[self.demoView.topAnchor constraintEqualToAnchor:guide.topAnchor].active = YES;
[self.demoView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor].active = YES;
Swift:
demoView.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
let guide = self.view.safeAreaLayoutGuide
demoView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
demoView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
demoView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
demoView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
} else {
NSLayoutConstraint(item: demoView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: demoView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: demoView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: demoView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
}
|
stackoverflow
|
{
"language": "en",
"length": 1783,
"provenance": "stackexchange_0000F.jsonl.gz:848835",
"question_score": "153",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492404"
}
|
e82c33f331671c891384e1bb3b6681d77b70610d
|
Stackoverflow Stackexchange
Q: How do I get the whole error backtrace for rspec? Currently I am using
parallel tests
rspec
allure 0.8.0
After I run the tests I get the following error:
RSpec::Core::MultipleExceptionError
I need the whole backtrace of the error. Is it some parameter that I need to pass to the command that I use to run and is there a permanent way so that it always prints the whole error
A: You have two options, to define a helper with that attribute or in command line
## spec/spec_helper.rb
config.full_backtrace = true # false to dismiss
or in the command line
$ rspec spec/folder/your_spec.rb --backtrace
|
Q: How do I get the whole error backtrace for rspec? Currently I am using
parallel tests
rspec
allure 0.8.0
After I run the tests I get the following error:
RSpec::Core::MultipleExceptionError
I need the whole backtrace of the error. Is it some parameter that I need to pass to the command that I use to run and is there a permanent way so that it always prints the whole error
A: You have two options, to define a helper with that attribute or in command line
## spec/spec_helper.rb
config.full_backtrace = true # false to dismiss
or in the command line
$ rspec spec/folder/your_spec.rb --backtrace
A: If you get this error you need to find the specific test in the rspec log (scroll up). There you will see details about the issue.
In my case error was shown only on CI and I needed some time in order to figure out that everything I need is "hidden" somewhere in the super long output.
|
stackoverflow
|
{
"language": "en",
"length": 162,
"provenance": "stackexchange_0000F.jsonl.gz:848886",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492556"
}
|
b6807b234844a60ae06e99df7f03c7d361dfe25d
|
Stackoverflow Stackexchange
Q: How to write Spark Streaming output to HDFS without overwriting After some processing I have a DStream[String , ArrayList[String]] , so when I am writing it to hdfs using saveAsTextFile and after every batch it overwrites the data , so how to write new result by appending to previous results
output.foreachRDD(r => {
r.saveAsTextFile(path)
})
Edit :: If anyone could help me in converting the output to avro format and then writing to HDFS with appending
A: saveAsTextFile does not support append. If called with a fixed filename, it will overwrite it every time.
We could do saveAsTextFile(path+timestamp) to save to a new file every time. That's the basic functionality of DStream.saveAsTextFiles(path)
An easily accessible format that supports append is Parquet. We first transform our data RDD to a DataFrame or Dataset and then we can benefit from the write support offered on top of that abstraction.
case class DataStructure(field1,..., fieldn)
... streaming setup, dstream declaration, ...
val structuredOutput = outputDStream.map(record => mapFunctionRecordToDataStructure)
structuredOutput.foreachRDD(rdd =>
import sparkSession.implicits._
val df = rdd.toDF()
df.write.format("parquet").mode("append").save(s"$workDir/$targetFile")
})
Note that appending to Parquet files gets more expensive over time, so rotating the target file from time to time is still a requirement.
|
Q: How to write Spark Streaming output to HDFS without overwriting After some processing I have a DStream[String , ArrayList[String]] , so when I am writing it to hdfs using saveAsTextFile and after every batch it overwrites the data , so how to write new result by appending to previous results
output.foreachRDD(r => {
r.saveAsTextFile(path)
})
Edit :: If anyone could help me in converting the output to avro format and then writing to HDFS with appending
A: saveAsTextFile does not support append. If called with a fixed filename, it will overwrite it every time.
We could do saveAsTextFile(path+timestamp) to save to a new file every time. That's the basic functionality of DStream.saveAsTextFiles(path)
An easily accessible format that supports append is Parquet. We first transform our data RDD to a DataFrame or Dataset and then we can benefit from the write support offered on top of that abstraction.
case class DataStructure(field1,..., fieldn)
... streaming setup, dstream declaration, ...
val structuredOutput = outputDStream.map(record => mapFunctionRecordToDataStructure)
structuredOutput.foreachRDD(rdd =>
import sparkSession.implicits._
val df = rdd.toDF()
df.write.format("parquet").mode("append").save(s"$workDir/$targetFile")
})
Note that appending to Parquet files gets more expensive over time, so rotating the target file from time to time is still a requirement.
A: If you want to append the same file and store on file system, store it as a parquet file. You can do it by
kafkaData.foreachRDD( rdd => {
if(rdd.count()>0)
{
val df=rdd.toDF()
df.write(SaveMode.Append).save("/path")
}
A: Storing the streaming output to HDFS will always create a new files even in case when you use append with parquet which leads to a small files problems on Namenode. I may recommend to write your output to sequence files where you can keep appending to the same file.
A: Here I solve the issue without dataframe
import java.time.format.DateTimeFormatter
import java.time.LocalDateTime
messages.foreachRDD{ rdd =>
rdd.repartition(1)
val eachRdd = rdd.map(record => record.value)
if(!eachRdd.isEmpty) {
eachRdd.saveAsTextFile(hdfs_storage + DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now) + "/")
}
}
|
stackoverflow
|
{
"language": "en",
"length": 314,
"provenance": "stackexchange_0000F.jsonl.gz:848887",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492558"
}
|
580aa765b7aa41deb310f2639791d688ed6a5a0b
|
Stackoverflow Stackexchange
Q: Looking for large text files for testing compression in all sizes I am looking for large text files for testing the compression and decompression in all sizes from 1kb to 100mb. Can someone please refer me to download it from some link ?
A: And don't forget the collection of Corpus
The Canterbury Corpus
The Artificial Corpus
The Large Corpus
The Miscellaneous Corpus
The Calgary Corpus
The Canterbury Corpus
SEE: https://corpus.canterbury.ac.nz/descriptions/
there is a download links for the files available for each set
|
Q: Looking for large text files for testing compression in all sizes I am looking for large text files for testing the compression and decompression in all sizes from 1kb to 100mb. Can someone please refer me to download it from some link ?
A: And don't forget the collection of Corpus
The Canterbury Corpus
The Artificial Corpus
The Large Corpus
The Miscellaneous Corpus
The Calgary Corpus
The Canterbury Corpus
SEE: https://corpus.canterbury.ac.nz/descriptions/
there is a download links for the files available for each set
A: *** Linux users only ***
Arbitrarily large text files can be generated on Linux with the following command:
tr -dc "A-Za-z 0-9" < /dev/urandom | fold -w100|head -n 100000 > bigfile.txt
This command will generate a text file that will contain 100,000 lines of random text and look like this:
NsQlhbisDW5JVlLSaZVtCLSUUrkBijbkc5f9gFFscDkoGnN0J6GgIFqdCLyhbdWLHxRVY8IwDCrWF555JeY0yD0GtgH21NotZAEe
iWJR1A4 bxqq9VKKAzMJ0tW7TCOqNtMzVtPB6NrtCIg8NSmhrO7QjNcOzi4N b VGc0HB5HMNXdyEoWroU464ChM5R Lqdsm3iPo
1mz0cPKqobhjDYkvRs5LZO8n92GxEKGeCtt oX53Qu6T7O2E9nJLKoUeJI6Ul7keLsNGI2BC55qs7fhqW8eFDsGsLPaImF7kFJiz
...
...
On my Ubuntu 18 its size it about 10MB. Bumping up the number of lines, and thereby bumping up the size, is easy. Just increase the head -n 100000 part. So, say, this command:
tr -dc "A-Za-z 0-9" < /dev/urandom | fold -w100|head -n 1000000 > bigfile.txt
will generate a file with 1,000,000 of random lines of text and be around 100MB. On my commodity hardware the latter command takes about 3 seconds to finish.
A: You can download enwik8 and enwik9 from here. They are respectively 100,000,000 and 1,000,000,000 bytes of text for compression benchmarks. You can always pull subsets of those for smaller tests.
A: Project Gutenberg looks exceptionally promising for this purpose. This resource contains thousands of books in many formats. Here is a sample of what is available:
Clicking on any of the links will reveal the the various formats that always include Plain Text UTF-8 and .txt:
Another possible place to get large amounts of random text data for compression testing would be data dump sites such as Wiki or even Stack Exchange
I've alse found this blog post that lists 10 open source places to get complex text data for analytics testing.
There are a lot of online resources for creating large text files of arbitrary or specific sizes, such as this Lorem Ipsum Generator which I have used for script development, but I've learned that these sources are no good for compression testing because the words tend to be limited and repetitive. Consequently, these files will compress considerably more than natural text would.
|
stackoverflow
|
{
"language": "en",
"length": 405,
"provenance": "stackexchange_0000F.jsonl.gz:848891",
"question_score": "28",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492576"
}
|
d26d7acc234773a1df1220cce7badaa37c574a5d
|
Stackoverflow Stackexchange
Q: iOS App Crashes while loading image from Assets.xcassets There is an image file named "5.jpg", in the Assets.xcassets named "5".
I wrote code UIImage *image = [UIImage imageNamed:@"5"]; to create the image but app crashes and outputs *** Assertion failure in -[_CUIThemePixelRendition _initWithCSIHeader:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/CoreUI/CoreUI-432.4/CoreTheme/ThemeStorage/CUIThemeRendition.m:3797 in the console.
A: I had this problem in the XCode 9 beta, running iOS 10 or below. It seems that Apple has dropped support for JPEG files in XCAssets. You can either use do as @Esha suggested and switch to PNG's or you can not use an XCAsset, put the image in your local directory, and refer to it by its URL.
It's possible that Apple did this intentionally (though if they did, I couldn't find any documentation for it) or that this is an XCode 9 bug. I have reported to apple and you can track the progress of the bug here.
|
Q: iOS App Crashes while loading image from Assets.xcassets There is an image file named "5.jpg", in the Assets.xcassets named "5".
I wrote code UIImage *image = [UIImage imageNamed:@"5"]; to create the image but app crashes and outputs *** Assertion failure in -[_CUIThemePixelRendition _initWithCSIHeader:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/CoreUI/CoreUI-432.4/CoreTheme/ThemeStorage/CUIThemeRendition.m:3797 in the console.
A: I had this problem in the XCode 9 beta, running iOS 10 or below. It seems that Apple has dropped support for JPEG files in XCAssets. You can either use do as @Esha suggested and switch to PNG's or you can not use an XCAsset, put the image in your local directory, and refer to it by its URL.
It's possible that Apple did this intentionally (though if they did, I couldn't find any documentation for it) or that this is an XCode 9 bug. I have reported to apple and you can track the progress of the bug here.
A: Try puting .png images in the asset folder. jpg images will make this issue.
A: The line should be
UIImage *image = [UIImage imageNamed:@"5.jpg"];
If the file is in PNG format, it is not necessary to specify the .PNG filename extension. Prior to iOS 4, you must specify the filename extension.
From Apple Documentation
It is recommended that you use PNG or JPEG files for most images in your app. Image objects are optimized for reading and displaying both formats, and those formats offer better performance than most other image formats. Because the PNG format is lossless, it is especially recommended for the images you use in your app’s interface.
|
stackoverflow
|
{
"language": "en",
"length": 260,
"provenance": "stackexchange_0000F.jsonl.gz:848945",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492745"
}
|
59e5e25ed48acf47012139eaf1dea6fe417336a4
|
Stackoverflow Stackexchange
Q: Dynamic import: How to import * from module name from variable? As discussed here, we can dynamically import a module using string variable.
import importlib
importlib.import_module('os.path')
My question is how to import * from string variable?
Some thing like this not working for now
importlib.import_module('os.path.*')
A: You can do the following trick:
>>> import importlib
>>> globals().update(importlib.import_module('math').__dict__)
>>> sin
<built-in function sin>
Be warned that makes all names in the module available locally, so it is slightly different than * because it doesn't start with __all__ so for e.g. it will also override __name__, __package__, __loader__, __doc__.
Update:
Here is a more precise and safer version as @mata pointed out in comments:
module = importlib.import_module('math')
globals().update(
{n: getattr(module, n) for n in module.__all__} if hasattr(module, '__all__')
else
{k: v for (k, v) in module.__dict__.items() if not k.startswith('_')
})
Special thanks to Nam G VU for helping to make the answer more complete.
|
Q: Dynamic import: How to import * from module name from variable? As discussed here, we can dynamically import a module using string variable.
import importlib
importlib.import_module('os.path')
My question is how to import * from string variable?
Some thing like this not working for now
importlib.import_module('os.path.*')
A: You can do the following trick:
>>> import importlib
>>> globals().update(importlib.import_module('math').__dict__)
>>> sin
<built-in function sin>
Be warned that makes all names in the module available locally, so it is slightly different than * because it doesn't start with __all__ so for e.g. it will also override __name__, __package__, __loader__, __doc__.
Update:
Here is a more precise and safer version as @mata pointed out in comments:
module = importlib.import_module('math')
globals().update(
{n: getattr(module, n) for n in module.__all__} if hasattr(module, '__all__')
else
{k: v for (k, v) in module.__dict__.items() if not k.startswith('_')
})
Special thanks to Nam G VU for helping to make the answer more complete.
|
stackoverflow
|
{
"language": "en",
"length": 153,
"provenance": "stackexchange_0000F.jsonl.gz:848969",
"question_score": "15",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492803"
}
|
f6c7193800f2cb885793c812d3677bd9baae293c
|
Stackoverflow Stackexchange
Q: Declare all targets PHONY Consider a long makefile with numerous targets, all of which are PHONY (meaning that the target name does not represent an existing file).
I can do either:
.PHONY: a
a:
do someting a
.PHONY: b
b:
do someting b
.PHONY: c
c:
do someting c
Or:
.PHONY: a b c
a:
do someting a
b:
do someting b
c:
do someting c
The first option is cumbersome, and the second option is prone to error, when future me adds a target and forget to declare it as PHONY.
Is there a standard way to declare all targets in a makefile as PHONY?
A: Just use MAKEFLAGS and set option --always-make like so:
MAKEFLAGS += --always-make
|
Q: Declare all targets PHONY Consider a long makefile with numerous targets, all of which are PHONY (meaning that the target name does not represent an existing file).
I can do either:
.PHONY: a
a:
do someting a
.PHONY: b
b:
do someting b
.PHONY: c
c:
do someting c
Or:
.PHONY: a b c
a:
do someting a
b:
do someting b
c:
do someting c
The first option is cumbersome, and the second option is prone to error, when future me adds a target and forget to declare it as PHONY.
Is there a standard way to declare all targets in a makefile as PHONY?
A: Just use MAKEFLAGS and set option --always-make like so:
MAKEFLAGS += --always-make
A: For me .PHONY: * worked. (GNU make 4.2.1)
A: One way to do it:
.PHONY: $(shell sed -n -e '/^$$/ { n ; /^[^ .\#][^ ]*:/ { s/:.*$$// ; p ; } ; }' $(MAKEFILE_LIST))
Works perfectly even for targets mentioned as dependencies.
A: If really all targets are PHONY, this is a bit pointless. make is meant for "do what is necessary to update my output", and if the answer to what is necessary? is always the same, simple scripts would do the same job with less overhead.
That being said, I could imagine a situation where all targets intended to be given at the commandline should be PHONY -- Let's assume you want to build some documents like this:
all: doc1.pdf doc2.pdf doc3.pdf doc4.pdf doc5.pdf
manuals: doc3.pdf doc4.pdf
faqs: doc1.pdf
designdocs: doc2.pdf
apidocs: doc5.pdf
developerdocs: doc2.pdf doc5.pdf
userdocs: doc1.pdf doc3.pdf doc4.pdf
%.pdf: %.md
$(somedocgenerator) -o $@ $<
Then you could do the following:
.PHONY: all $(MAKECMDGOALS)
This would dynamically make any target given at the command line PHONY. Note you have to include your default target here as this could be invoked without giving it explicitly, by simply typing make.
I would not recommend this approach because it has two drawbacks:
*
*It's less portable to different flavors of make.
*It will misbehave if someone decides to make a specific output file like here make doc3.pdf.
*It will also misbehave if you decide to have one of your PHONY targets depend on another PHONY one.
So, better go with the approach to have one line declaring all the PHONY targets. If your Makefile is really huge, you could split it in several files and use include -- and have one .PHONY: line in each file.
|
stackoverflow
|
{
"language": "en",
"length": 408,
"provenance": "stackexchange_0000F.jsonl.gz:848970",
"question_score": "37",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492805"
}
|
d5e0a42ab90d8ace14046fb99957087822a9ddbe
|
Stackoverflow Stackexchange
Q: window.opener.location.href get blocking error I've a website and there is a search option from home page. I need to open two tabs from home page search and I did this job by the following way:
window.location.href = 'partnerUrl'; // Other Site URL
window.open('Listing Page URL', '_blank'); // Load may site's next page (listing page)
and it's working fine.
Ok, now from listing page I need to check which partner link was opened from the code line window.location.href = 'partnerUrl';. I'm trying to do this by window.opener.location.href but it returns the following error:
Exception: DOMException: Blocked a frame with origin my_site_link from accessing a cross-origin frame. at Function.getOwnPropertyDescriptor () at process.next () at _propertyDescriptors.next ()
How can I resolve the probelm? Any of your suggestion will be appriciated.
|
Q: window.opener.location.href get blocking error I've a website and there is a search option from home page. I need to open two tabs from home page search and I did this job by the following way:
window.location.href = 'partnerUrl'; // Other Site URL
window.open('Listing Page URL', '_blank'); // Load may site's next page (listing page)
and it's working fine.
Ok, now from listing page I need to check which partner link was opened from the code line window.location.href = 'partnerUrl';. I'm trying to do this by window.opener.location.href but it returns the following error:
Exception: DOMException: Blocked a frame with origin my_site_link from accessing a cross-origin frame. at Function.getOwnPropertyDescriptor () at process.next () at _propertyDescriptors.next ()
How can I resolve the probelm? Any of your suggestion will be appriciated.
|
stackoverflow
|
{
"language": "en",
"length": 128,
"provenance": "stackexchange_0000F.jsonl.gz:849029",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44492953"
}
|
1c1b53241301ad3dc56c90d01fc0b6a5d91b55f3
|
Stackoverflow Stackexchange
Q: PostgreSQL, get column name, column type and description I want to for selected table in selected schema get desired result like this
column_name | data_type | description
-----------------------------------------
id | integer | id of bill
name | character |
address | character | adress of buyer
notice that some columns don't have description (column comment).
For now i got only this query which gives me good result but only for columns which got comments (for columns that are in the selected table and don't have comment are not represented in output).
MY query which returns only data for columns that have comment is next
SELECT c.column_name, c.data_type, pgd.description
from pg_catalog.pg_statio_all_tables as st
inner join pg_catalog.pg_description pgd on (pgd.objoid=st.relid)
inner join information_schema.columns c on (pgd.objsubid=c.ordinal_position and c.table_schema=st.schemaname and c.table_name=st.relname)
where table_schema = 'public' and table_name = 'some_table';
How to get columns without comment in result?
A: There is the function col_description(table_oid, column_number)
select column_name, data_type, col_description('public.my_table'::regclass, ordinal_position)
from information_schema.columns
where table_schema = 'public' and table_name = 'my_table';
column_name | data_type | col_description
-------------+-----------+-------------------
gid | integer | a comment for gid
id | integer |
max_height | numeric |
(3 rows)
|
Q: PostgreSQL, get column name, column type and description I want to for selected table in selected schema get desired result like this
column_name | data_type | description
-----------------------------------------
id | integer | id of bill
name | character |
address | character | adress of buyer
notice that some columns don't have description (column comment).
For now i got only this query which gives me good result but only for columns which got comments (for columns that are in the selected table and don't have comment are not represented in output).
MY query which returns only data for columns that have comment is next
SELECT c.column_name, c.data_type, pgd.description
from pg_catalog.pg_statio_all_tables as st
inner join pg_catalog.pg_description pgd on (pgd.objoid=st.relid)
inner join information_schema.columns c on (pgd.objsubid=c.ordinal_position and c.table_schema=st.schemaname and c.table_name=st.relname)
where table_schema = 'public' and table_name = 'some_table';
How to get columns without comment in result?
A: There is the function col_description(table_oid, column_number)
select column_name, data_type, col_description('public.my_table'::regclass, ordinal_position)
from information_schema.columns
where table_schema = 'public' and table_name = 'my_table';
column_name | data_type | col_description
-------------+-----------+-------------------
gid | integer | a comment for gid
id | integer |
max_height | numeric |
(3 rows)
A: because information_schema.columns is the table with data for sure, and you reference it not the first, you need right outer join instead:
t=# SELECT c.column_name, c.data_type, pgd.description
from pg_catalog.pg_statio_all_tables as st
inner join pg_catalog.pg_description pgd on (pgd.objoid=st.relid)
right outer join information_schema.columns c on (pgd.objsubid=c.ordinal_position and c.table_schema=st.schemaname and c.table_name=st.relname)
where table_schema = 'public' and table_name = 's150';
column_name | data_type | description
---------------+-----------+-------------
customer_name | text |
order_id | text |
order_date | date |
(3 rows)
A: Use col_description() on pg_attribute:
select
attname as column_name,
atttypid::regtype as data_type,
col_description(attrelid, attnum) as description
from pg_attribute
where attrelid = '(myschema.)mytable'::regclass
and attnum > 0 -- hide system columns
and not attisdropped -- hide dead/dropped columns
order by attnum;
|
stackoverflow
|
{
"language": "en",
"length": 308,
"provenance": "stackexchange_0000F.jsonl.gz:849051",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493043"
}
|
c4f885ef64c819f9309fba681280e39a1d066716
|
Stackoverflow Stackexchange
Q: Format a date string in javascript Hello every i have date field of type string with iso format like this:
const date = "2017-06-10T16:08:00: i want somehow to edit the string in the following format like this: 10-06-2017 but i'm struggling in achieving this.
I cut the substring after the "T" character
A: If the date string is always in ISO format, you can also use regex to reformat without other library:
date.replace(/(\d{4})\-(\d{2})\-(\d{2}).*/, '$3-$2-$1')
|
Q: Format a date string in javascript Hello every i have date field of type string with iso format like this:
const date = "2017-06-10T16:08:00: i want somehow to edit the string in the following format like this: 10-06-2017 but i'm struggling in achieving this.
I cut the substring after the "T" character
A: If the date string is always in ISO format, you can also use regex to reformat without other library:
date.replace(/(\d{4})\-(\d{2})\-(\d{2}).*/, '$3-$2-$1')
A: It can be achieved without moment.js, but I suggest you use it
var date = new Date("2017-06-10T16:08:00");
var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();
if (day < 10) {
day = '0' + day;
}
if (month < 10) {
month = '0' + month;
}
var formattedDate = day + '-' + month + '-' + year
A: Use Moment.js and the .format function.
moment('2017-06-10T16:08:00').format('MM/DD/YYYY');
Will output
06/10/2017
Beside the format function Moment.js will enrich you will alot more useful functions.
A: You can use the JavaScript date() built in function to get parts of the date/time you want.
For example to display the time is 10:30:
<script>
var date = new Date();
var min = date.getMinutes();
var hour = date.getHour();
document.write(hour+":"+min);
</script>
To get the year, month, date, day of week use
*
*getFullYear();
*getMonth();
*getDate();
*getDay();
To get the date you posted:
A: Using Date.toJSON()
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
return (new Date(userDate).toJSON().slice(0,10).split('-').reverse().join('-'));
}
console.log(formatDate("2017-06-10T16:08:00"));
A: If you're looking to do this in vanilla javascript, @Ivan Mladenov's answer is great and can be consolidated slightly using padStart.
const date = new Date()
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
console.log(`${day}-${month}-${year}`)
A: I would like to suggest to use moment js find it - http://momentjs.com/docs/
and use it like
moment(date.toString()).format("MM/DD/YYYY")
|
stackoverflow
|
{
"language": "en",
"length": 306,
"provenance": "stackexchange_0000F.jsonl.gz:849063",
"question_score": "15",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493088"
}
|
d64cf3f7f35faaec77099c635d13e4870253f965
|
Stackoverflow Stackexchange
Q: Casting a superclass as one of its subclasses I have a function that takes an instance of type Being. There are two subclasses to Being: Person and Animal. I want the function to recognize which of the two was passed and do something with properties specific to each subclass.
I thought this would work:
func fight(attacker1: Being, attacker2: Being) -> String {
if attacker1 is Person {
let name1 = attacker1.name as! Person //Error: Value of type Being has no member name
} else {
print("Its not a person")
}
But it doesn't. What is the smoothest/shortest way to achieve what I am looking for?
A: You should create new variable of the needed type and put on your parameter into this variable.
func fight(attacker1: Being, attacker2: Being) -> String {
if let att1 = attacker1 as? Person {
let name1 = att1.name
} else {
print("Its not a person")
}
In this way, if attacker1 is Person, you just save this value into att1 constant and later you can use this constant as instance of the Person type.
|
Q: Casting a superclass as one of its subclasses I have a function that takes an instance of type Being. There are two subclasses to Being: Person and Animal. I want the function to recognize which of the two was passed and do something with properties specific to each subclass.
I thought this would work:
func fight(attacker1: Being, attacker2: Being) -> String {
if attacker1 is Person {
let name1 = attacker1.name as! Person //Error: Value of type Being has no member name
} else {
print("Its not a person")
}
But it doesn't. What is the smoothest/shortest way to achieve what I am looking for?
A: You should create new variable of the needed type and put on your parameter into this variable.
func fight(attacker1: Being, attacker2: Being) -> String {
if let att1 = attacker1 as? Person {
let name1 = att1.name
} else {
print("Its not a person")
}
In this way, if attacker1 is Person, you just save this value into att1 constant and later you can use this constant as instance of the Person type.
A: While @V.Khambir's code works and probably is the nicer solution, it did not point out the problem of you code. You are trying to cast .name to a Person. .name is not a property of attacker1, that is why you are getting the error. What you wanted to do is cast attacker1 to a Person and then access the name property.
func fight(attacker1: Being, attacker2: Being) -> String {
if attacker1 is Person {
let name1 = (attacker1 as! Person).name
} else {
print("Its not a person")
}
A: Since Being is a base class so it will not have access to any child class properties. So first of all, you have to check the type of attacker1 and attacker2. for ex: if attacker1 is of type Person then you can type cast it to an instance of type Person and then access the properties of the person object.
Note:- Make sure to check the type first and then type cast it else it will crash.
|
stackoverflow
|
{
"language": "en",
"length": 347,
"provenance": "stackexchange_0000F.jsonl.gz:849076",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493140"
}
|
7bd5eb3fb1a798a8adb9b0ea9c617063d68137de
|
Stackoverflow Stackexchange
Q: Retrieve a cookie using Spring RestTemplate I need to get a cookie from a server using Spring RestTemplate. Do you guys know how I can perform this?
Thank you for your help!
A: final String url = "http://codeflex.co:8080/rest/Management/login";
RestTemplate template = new RestTemplate();
Credentials cred = new Credentials();
cred.setUserName("[email protected]");
cred.setPassword("godmode");
HttpEntity<Credentials> request = new HttpEntity<>(cred);
HttpEntity<String> response = template.exchange(url, HttpMethod.POST, request, String.class);
HttpHeaders headers = response.getHeaders();
String set_cookie = headers.getFirst(HttpHeaders.SET_COOKIE);
code from the example
|
Q: Retrieve a cookie using Spring RestTemplate I need to get a cookie from a server using Spring RestTemplate. Do you guys know how I can perform this?
Thank you for your help!
A: final String url = "http://codeflex.co:8080/rest/Management/login";
RestTemplate template = new RestTemplate();
Credentials cred = new Credentials();
cred.setUserName("[email protected]");
cred.setPassword("godmode");
HttpEntity<Credentials> request = new HttpEntity<>(cred);
HttpEntity<String> response = template.exchange(url, HttpMethod.POST, request, String.class);
HttpHeaders headers = response.getHeaders();
String set_cookie = headers.getFirst(HttpHeaders.SET_COOKIE);
code from the example
A: HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Cookie", "JSESSIONID=" + session.getValue());
HttpEntity requestEntity = new HttpEntity(null, requestHeaders);
ResponseEntity rssResponse = restTemplate.exchange(
"https://jira.example.com/sr/jira.issueviews:searchrequest-xml/18107/SearchRequest-18107.xml?tempMax=1000",
HttpMethod.GET,
requestEntity,
Rss.class);
Rss rss = rssResponse.getBody();
from http://springinpractice.com/2012/04/08/sending-cookies-with-resttemplate
|
stackoverflow
|
{
"language": "en",
"length": 105,
"provenance": "stackexchange_0000F.jsonl.gz:849082",
"question_score": "12",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493162"
}
|
127da43fc629bfc26058746001c73d3f3927727b
|
Stackoverflow Stackexchange
Q: How many bytes is a gigabyte (GB)? When I convert between 1GB to byte using online tools, I get different answers. For instance, using Google Convertor: 1GB=1e+9 while in another converter I get 1GB= 1073741824. I suppose the unit is used in different fashion based on whether 1KB=1024B or 1KB=1000B (this is Google unit).
How can I know which unit my machine uses using a small C program or function? Does C have a macro for that? I want to do that as my program will possibly be run via various operating systems.
A: This is just a confusion of units. There are actually two prefixes G for 10⁹ and Gi for 2³⁰. Bytes should usually be measured with the second, so the correct writing would be GiB.
|
Q: How many bytes is a gigabyte (GB)? When I convert between 1GB to byte using online tools, I get different answers. For instance, using Google Convertor: 1GB=1e+9 while in another converter I get 1GB= 1073741824. I suppose the unit is used in different fashion based on whether 1KB=1024B or 1KB=1000B (this is Google unit).
How can I know which unit my machine uses using a small C program or function? Does C have a macro for that? I want to do that as my program will possibly be run via various operating systems.
A: This is just a confusion of units. There are actually two prefixes G for 10⁹ and Gi for 2³⁰. Bytes should usually be measured with the second, so the correct writing would be GiB.
A: The two tools are converting two different units.
1 GB = 10^9 bytes while 1 GiB = 2^30 bytes.
Try using google converter with GiB instead of GB and the mystery will be solved.
The following will help you understand the conversion a little better.
Factor Name Symbol Origin Derivation Decimal
2^10 kibi Ki kilobinary: (2^10)^1 kilo: (10^3)^1
2^20 mebi Mi megabinary: (2^10)^2 mega: (10^3)^2
2^30 gibi Gi gigabinary: (2^10)^3 giga: (10^3)^3
2^40 tebi Ti terabinary: (2^10)^4 tera: (10^3)^4
2^50 pebi Pi petabinary: (2^10)^5 peta: (10^3)^5
2^60 exbi Ei exabinary: (2^10)^6 exa: (10^3)^6
Note that the new prefixes for binary multiples are not part of the International System of Units (SI). However, for ease of understanding and recall, they were derived from the SI prefixes for positive powers of ten. As shown in the table, the name of each new prefix is derived from the name of the corresponding SI prefix by retaining the first two letters of the SI prefix and adding the letters bi.
There's still a lot of confusion on the usage of GB and GiB in fact very often GB is used when GiB should or was intended to be.
Think about the hard drives world:
Your operating system assumes that 1 MB equals 1 048 576 bytes i.e. 1MiB. Drive manufacturers consider (correctly) 1 MB as equal to 1 000 000 bytes. Thus if the drive is advertised as 6.4 GB (6 400 000 000 bytes) the operating system sees it as approximately 6.1 GB 6 400 000 000/1 048 576 000 = ~6.1 GiB
Take a look at this for more info on prefixes for binary units
and this on metric prefixes.
A: *
*The “gibibyte” is a multiple of the unit byte for Digital
Information.
*The binary prefix gibi means 2^30, therefore one gibibyte is equal to
1073741824 bytes = 1024 mebibytes.
*The unit symbol for the gibibyte is GiB. It is one of the units with
binary prefixes defined by the International Electrotechnical
Commission (IEC) in 1998.
*The “gibibyte” is closely related to the Gigabyte (GB), which is
defined by the IEC as 10^9 bytes = 1000000000 bytes, 1GiB ≈ 1.024GB.
1024 Gibibytes are equal to One Tebibyte.
*In the context of computer memory, Gigabyte and GB are customarily
used to mean 1024^3 (2^30) bytes, although not in the context of data
transmission and not necessarily for Hard Drive size.
|
stackoverflow
|
{
"language": "en",
"length": 528,
"provenance": "stackexchange_0000F.jsonl.gz:849086",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493178"
}
|
99994407b3cbbaccde5832bea77eca9ca5ec160b
|
Stackoverflow Stackexchange
Q: Is there an actual 4-bit integer data type in C++11 I require a 4 bit integer in a design for less memory use. In any version of c++ ,c++11 ,c++14 any can be used for the design.
A: There is no native 4bit datatype. But you could use an 8bit one to hold two 4bit values in the high/low nibble.
|
Q: Is there an actual 4-bit integer data type in C++11 I require a 4 bit integer in a design for less memory use. In any version of c++ ,c++11 ,c++14 any can be used for the design.
A: There is no native 4bit datatype. But you could use an 8bit one to hold two 4bit values in the high/low nibble.
A: no, but you can use:
struct A {
unsigned int value1 : 4;
unsigned int value2 : 4;
};
|
stackoverflow
|
{
"language": "en",
"length": 81,
"provenance": "stackexchange_0000F.jsonl.gz:849099",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493230"
}
|
0aea95d53b0c6ae996364a38a6cfc2456b032c71
|
Stackoverflow Stackexchange
Q: Java return null for primitive in ternary The following (logically) is a compile-time error:
public int myMethod(MyObject input) {
if (input == null) {
return null; // compiler says I cannot return null for primitive type
} else {
return 1;
}
}
So far so good. What I don't understand, that the following is allowed:
public int myMethod(MyObject input) {
return input == null ? null : 1;
}
Why? Recognising this should be straightforward for the compiler, or do I miss some crucial point here?
(And of course if in the ternary operator one ends up on the "null-branch", then it's a NPE, what else? :))
A: The type of the ternary conditional operator is determined by the types of its 2nd and 3rd operands.
In the case of
input == null ? null : 1
the type is Integer, which can be assigned both null and 1.
The compiler allows your method to return an Integer since it can be auto-unboxed into an int, so it fit the int return type of myMethod.
The fact that your specific code may throw a NullPointerException is not something the compiler can detect.
|
Q: Java return null for primitive in ternary The following (logically) is a compile-time error:
public int myMethod(MyObject input) {
if (input == null) {
return null; // compiler says I cannot return null for primitive type
} else {
return 1;
}
}
So far so good. What I don't understand, that the following is allowed:
public int myMethod(MyObject input) {
return input == null ? null : 1;
}
Why? Recognising this should be straightforward for the compiler, or do I miss some crucial point here?
(And of course if in the ternary operator one ends up on the "null-branch", then it's a NPE, what else? :))
A: The type of the ternary conditional operator is determined by the types of its 2nd and 3rd operands.
In the case of
input == null ? null : 1
the type is Integer, which can be assigned both null and 1.
The compiler allows your method to return an Integer since it can be auto-unboxed into an int, so it fit the int return type of myMethod.
The fact that your specific code may throw a NullPointerException is not something the compiler can detect.
|
stackoverflow
|
{
"language": "en",
"length": 194,
"provenance": "stackexchange_0000F.jsonl.gz:849103",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493258"
}
|
cca3c528238faaf7b340d59b5d5142db9bbc5ec2
|
Stackoverflow Stackexchange
Q: Send email from Jenkins job using Groovy Postbuild action Is there a way to send an email from Jenkins job using Groovy Postbuild action? Similar to how it can be done using Jenkins pipeline plugin
mail to: '[email protected]',
subject: "Job '${env.JOB_NAME}' (${env.BUILD_NUMBER}) is waiting for input",
body: "Please go to ${env.BUILD_URL}."
A: Thanks to https://stackoverflow.com/a/37194996/4624905 I figured out that I can use JavaMail API directly. It helped me.
import javax.mail.*
import javax.mail.internet.*
def sendMail(host, sender, receivers, subject, text) {
Properties props = System.getProperties()
props.put("mail.smtp.host", host)
Session session = Session.getDefaultInstance(props, null)
MimeMessage message = new MimeMessage(session)
message.setFrom(new InternetAddress(sender))
receivers.split(',').each {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(it))
}
message.setSubject(subject)
message.setText(text)
println 'Sending mail to ' + receivers + '.'
Transport.send(message)
println 'Mail sent.'
}
Usage Example:
sendMail('mailhost', messageSender, messageReceivers, messageSubject, messageAllText)
|
Q: Send email from Jenkins job using Groovy Postbuild action Is there a way to send an email from Jenkins job using Groovy Postbuild action? Similar to how it can be done using Jenkins pipeline plugin
mail to: '[email protected]',
subject: "Job '${env.JOB_NAME}' (${env.BUILD_NUMBER}) is waiting for input",
body: "Please go to ${env.BUILD_URL}."
A: Thanks to https://stackoverflow.com/a/37194996/4624905 I figured out that I can use JavaMail API directly. It helped me.
import javax.mail.*
import javax.mail.internet.*
def sendMail(host, sender, receivers, subject, text) {
Properties props = System.getProperties()
props.put("mail.smtp.host", host)
Session session = Session.getDefaultInstance(props, null)
MimeMessage message = new MimeMessage(session)
message.setFrom(new InternetAddress(sender))
receivers.split(',').each {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(it))
}
message.setSubject(subject)
message.setText(text)
println 'Sending mail to ' + receivers + '.'
Transport.send(message)
println 'Mail sent.'
}
Usage Example:
sendMail('mailhost', messageSender, messageReceivers, messageSubject, messageAllText)
A: Yes you can.
*
*Setup SMTP configuration for your jenkins by going to jenkins -> configuration. If you have your own(company) SMTP server that would be great otherwise you can use google's smtp server and your gmail account (you can create new gmail account for the jenkins).
*Add post build action (Email editable notification) and fill the form accordingly.
NB: Because we are putting the username and password of our gmail account on jenkins gmail will notify you that your account is being used by an app and it is less secure; In that case you have to tell gmail to allow for less secure access follow the instructions here.
If you did not enable less secure apps to access your apps your emails might not be delivered appropriately.
|
stackoverflow
|
{
"language": "en",
"length": 257,
"provenance": "stackexchange_0000F.jsonl.gz:849143",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493385"
}
|
3801e04a5bc52f552f90b4a39354b1630d9846e9
|
Stackoverflow Stackexchange
Q: Pandas DataFrame Bar Plot - Plot Bars Different Colors From Specific Colormap How do you plot the bars of a bar plot different colors only using the pandas dataframe plot method?
If I have this DataFrame:
df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()
index count
0 0 3372
1 1 68855
2 2 17948
3 3 708
4 4 9117
What df.plot() arguments do I need to set so each bar in the plot:
*
*Uses the 'Paired' colormap
*Plots each bar a different color
What I am attempting:
df.plot(x='index', y='count', kind='bar', label='index', colormap='Paired', use_index=False)
The result:
What I already know (yes, this works, but again, my purpose is to figure out how to do this with df.plot ONLY. Surely it must be possible?):
def f(df):
groups = df.groupby('index')
for name,group in groups:
plt.bar(name, group['count'], label=name, align='center')
plt.legend()
plt.show()
A: In addition/extension to @Jairo Alves work you can also indicate the specific hex code
df.plot(kind="bar",figsize=(20, 8),color=['#5cb85c','#5bc0de','#d9534f'])
|
Q: Pandas DataFrame Bar Plot - Plot Bars Different Colors From Specific Colormap How do you plot the bars of a bar plot different colors only using the pandas dataframe plot method?
If I have this DataFrame:
df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()
index count
0 0 3372
1 1 68855
2 2 17948
3 3 708
4 4 9117
What df.plot() arguments do I need to set so each bar in the plot:
*
*Uses the 'Paired' colormap
*Plots each bar a different color
What I am attempting:
df.plot(x='index', y='count', kind='bar', label='index', colormap='Paired', use_index=False)
The result:
What I already know (yes, this works, but again, my purpose is to figure out how to do this with df.plot ONLY. Surely it must be possible?):
def f(df):
groups = df.groupby('index')
for name,group in groups:
plt.bar(name, group['count'], label=name, align='center')
plt.legend()
plt.show()
A: In addition/extension to @Jairo Alves work you can also indicate the specific hex code
df.plot(kind="bar",figsize=(20, 8),color=['#5cb85c','#5bc0de','#d9534f'])
A: There is no argument you can pass to df.plot that colorizes the bars differently for a single column.
Since bars for different columns are colorized differently, an option is to transpose the dataframe before plotting,
ax = df.T.plot(kind='bar', label='index', colormap='Paired')
This would now draw the data as part of a subgroup. Therefore some tweaking needs to be applied to set the limits and xlabels correctly.
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()
ax = df.T.plot(kind='bar', label='index', colormap='Paired')
ax.set_xlim(0.5, 1.5)
ax.set_xticks([0.8,0.9,1,1.1,1.2])
ax.set_xticklabels(range(len(df)))
plt.show()
While I guess this solution matches the criteria from the question, there is actually nothing wrong with using plt.bar. A single call to plt.bar is sufficient
plt.bar(range(len(df)), df["count"], color=plt.cm.Paired(np.arange(len(df))))
Complete code:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()
plt.bar(range(len(df)), df["count"], color=plt.cm.Paired(np.arange(len(df))))
plt.show()
A: You can colorize each column as you like with the parameter color.
For example (for example, with 3 variables):
df.plot.bar(color=['C0', 'C1', 'C2'])
Note: The strings 'C0', 'C1', ...' mentioned above are built-in shortcut color handles in matplotlib. They mean the first, second, third default colors in the active color scheme, and so on. In fact, they are just an example, you can use any custom color using the RGB code or any other color convention just as easily.
You can even highlight a specific column, for example, the middle one here:
df.plot.bar(color=['C0', 'C1', 'C0'])
To reproduce it in the example code given, one can use:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()
ax = df.T.plot(kind='bar', label='index', color=['C0', 'C1', 'C2', 'C3', 'C4'])
ax.set_xlim(0.5, 1.5)
ax.set_xticks([0.8,0.9,1,1.1,1.2])
ax.set_xticklabels(range(len(df)))
plt.show()
Example with different colors:
Example with arbitrary repetition of colors:
Link for reference: Assign line colors in pandas
|
stackoverflow
|
{
"language": "en",
"length": 479,
"provenance": "stackexchange_0000F.jsonl.gz:849156",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493417"
}
|
ea3b3c48b43791e51a22e477b2f83a827c43e3f1
|
Stackoverflow Stackexchange
Q: Android Studio can't find package when import org.robolectric I am using butterknife package:8.5.1, when I want to add robolectric, gradle says com.google.guava has conflit:
Error:Conflict with dependency 'com.google.guava:guava' in project ':app'. Resolved versions for app (18.0) and test app (20.0) differ. See http://g.co/androidstudio/app-test-app-conflict for details.
I checked the dependencies, and because ButterKnife is using guava 18, so I use
configurations.all {
resolutionStrategy {
force 'com.google.guava:guava:20.0'
}
}
try to avoid, now gradle will build without errors.
However, when I want to use the package, Android Studio always complains at
import org.robolectric.Robolectric;
It says it can't find org.robolectric. I have no idea what's going on, can someone help? Thank a lot.
Then I also tried
exclude group: 'com.google.guava', module: 'guava'
also the same result
I suspect it has something to do with com.google.guava, but I can't understand why it can't find the package. I can see robolectric package under "external libraries"
A: Actually, I found it's because my test is under androidTest folder, not test, which causes the package unavailable.
|
Q: Android Studio can't find package when import org.robolectric I am using butterknife package:8.5.1, when I want to add robolectric, gradle says com.google.guava has conflit:
Error:Conflict with dependency 'com.google.guava:guava' in project ':app'. Resolved versions for app (18.0) and test app (20.0) differ. See http://g.co/androidstudio/app-test-app-conflict for details.
I checked the dependencies, and because ButterKnife is using guava 18, so I use
configurations.all {
resolutionStrategy {
force 'com.google.guava:guava:20.0'
}
}
try to avoid, now gradle will build without errors.
However, when I want to use the package, Android Studio always complains at
import org.robolectric.Robolectric;
It says it can't find org.robolectric. I have no idea what's going on, can someone help? Thank a lot.
Then I also tried
exclude group: 'com.google.guava', module: 'guava'
also the same result
I suspect it has something to do with com.google.guava, but I can't understand why it can't find the package. I can see robolectric package under "external libraries"
A: Actually, I found it's because my test is under androidTest folder, not test, which causes the package unavailable.
A: Try this:
in
dependencies {
compile 'org.robolectric:robolectric:3.4' // instead of TestCompile
}
It worked for me.
|
stackoverflow
|
{
"language": "en",
"length": 187,
"provenance": "stackexchange_0000F.jsonl.gz:849172",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493464"
}
|
e04c6b4687dc13e5822399c6ee9b05f96998a365
|
Stackoverflow Stackexchange
Q: Android - How to access the File from a ParcelFileDescriptor? According to the FileProvider documentation the fileProvider.openFile() method returns
a new ParcelFileDescriptor with which you can access the file.
I have looked in ParcelFileDescriptor, but I cannot see how to access the File. So how do I access the File from a ParcelFileDescriptor?
|
Q: Android - How to access the File from a ParcelFileDescriptor? According to the FileProvider documentation the fileProvider.openFile() method returns
a new ParcelFileDescriptor with which you can access the file.
I have looked in ParcelFileDescriptor, but I cannot see how to access the File. So how do I access the File from a ParcelFileDescriptor?
|
stackoverflow
|
{
"language": "en",
"length": 54,
"provenance": "stackexchange_0000F.jsonl.gz:849182",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493497"
}
|
6c92bb65145c45308291052f6a57cfda96d550e1
|
Stackoverflow Stackexchange
Q: How can I generate n random numbers without a for loop I am trying to generate 4 random integers between 0-9.
I can easily achieve this using a for-loop:
digits = [random.randrange(10) for i in range(4)]
Assuming it is possible, I was wondering about other ways to yield the same result, perhaps without directly using a for-loop. I was experimenting with itertools and this didn't work:
digits = itertools.repeat(random.randrange(10), 4)
The main purpose of my question is to expose myself to additional methods.
Thanks.
A: numpy.random.randint(0, 10, size=4)
or to use itertools
list(map(random.randrange, itertools.repeat(10, 4)))
or even
list(map(random.randrange, [10]*4))
|
Q: How can I generate n random numbers without a for loop I am trying to generate 4 random integers between 0-9.
I can easily achieve this using a for-loop:
digits = [random.randrange(10) for i in range(4)]
Assuming it is possible, I was wondering about other ways to yield the same result, perhaps without directly using a for-loop. I was experimenting with itertools and this didn't work:
digits = itertools.repeat(random.randrange(10), 4)
The main purpose of my question is to expose myself to additional methods.
Thanks.
A: numpy.random.randint(0, 10, size=4)
or to use itertools
list(map(random.randrange, itertools.repeat(10, 4)))
or even
list(map(random.randrange, [10]*4))
A: What about using a generator and a while loop ?
from random import randrange
def rand(val, repeat=4):
j = 1
while j <= repeat:
yield randrange(val)
j += 1
final = list(rand(10))
Output:
[2, 6, 8, 8]
Also, using a recursion:
from random import randrange
def rand(val, repeat=4, b=1, temp=[]):
if b < repeat:
temp.append(randrange(val))
return rand(val, b= b+1, temp=temp)
else:
return temp + [randrange(val)]
final = rand(10)
print(final)
Output:
[1, 9, 3, 1]
A: This is not really something that I would do, but since you would like to expose yourself to additional methods, then taking advantage of the 0-9 range you can also obtain 4 such integers as follows:
map(int, "%04d"%random.randrange(10**4))
It actually generates a four digit string, and extracts the digits from it.
|
stackoverflow
|
{
"language": "en",
"length": 227,
"provenance": "stackexchange_0000F.jsonl.gz:849184",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493500"
}
|
07ef8c02a8779a4ef9d61a974a8ebbfec150eddb
|
Stackoverflow Stackexchange
Q: Use Keycloak Authorization Services with Spring Boot (resource server) How do I use Keycloak Authorization Services with Spring Boot resource server?
I have a client in keycloak set to bearer-only, and can protect resource paths using information from their documentation.
BUT not when "Authorization Enabled" set to true for my bearer-only client and I have setup resources, policies, permissions.
From the Keycloak documentation https://keycloak.gitbooks.io/documentation/authorization_services/topics/enforcer/keycloak-enforcement-filter.html
"You can enforce authorization decisions for your applications if you are using Keycloak OIDC adapters.
When you enable policy enforcement for your Keycloak application, the corresponding adapter intercepts all requests to your application and enforces the authorization decisions obtained from the server."
In application.properties I set:
keycloak.policy-enforcer-config.enforcement-mode=enforcing
and get error:
java.lang.NoClassDefFoundError: org.keycloak.authorization.client.ClientAuthenticator
I added dependency
<dependency> <!-- https://issues.jboss.org/browse/KEYCLOAK-3246 -->
<groupId>org.keycloak</groupId>
<artifactId>keycloak-authz-client</artifactId>
<version>3.1.0.Final</version>
</dependency>
but this gives errors as below when trying to access a resource
Client 'resourceserver-springboot' doesn't have secret available
org.keycloak.authorization.client.util.HttpResponseException: Unexpected response from server: 400 / Bad Request
A: Looks like you forgot to pass the secret in your config :
keycloak.credentials.secret=my_secret
|
Q: Use Keycloak Authorization Services with Spring Boot (resource server) How do I use Keycloak Authorization Services with Spring Boot resource server?
I have a client in keycloak set to bearer-only, and can protect resource paths using information from their documentation.
BUT not when "Authorization Enabled" set to true for my bearer-only client and I have setup resources, policies, permissions.
From the Keycloak documentation https://keycloak.gitbooks.io/documentation/authorization_services/topics/enforcer/keycloak-enforcement-filter.html
"You can enforce authorization decisions for your applications if you are using Keycloak OIDC adapters.
When you enable policy enforcement for your Keycloak application, the corresponding adapter intercepts all requests to your application and enforces the authorization decisions obtained from the server."
In application.properties I set:
keycloak.policy-enforcer-config.enforcement-mode=enforcing
and get error:
java.lang.NoClassDefFoundError: org.keycloak.authorization.client.ClientAuthenticator
I added dependency
<dependency> <!-- https://issues.jboss.org/browse/KEYCLOAK-3246 -->
<groupId>org.keycloak</groupId>
<artifactId>keycloak-authz-client</artifactId>
<version>3.1.0.Final</version>
</dependency>
but this gives errors as below when trying to access a resource
Client 'resourceserver-springboot' doesn't have secret available
org.keycloak.authorization.client.util.HttpResponseException: Unexpected response from server: 400 / Bad Request
A: Looks like you forgot to pass the secret in your config :
keycloak.credentials.secret=my_secret
A: *
*Add keycloak.json to your resources,(Usually keycloak adapter looks
for a keycloak.json for configs)
OR
*
*Add config into your application.properties file.
Also create a bean to resolve your application.properties for the
keycloak adapter
@Bean
open fun keycloakConfigResolver(): KeycloakSpringBootConfigResolver {
return KeycloakSpringBootConfigResolver()
}
|
stackoverflow
|
{
"language": "en",
"length": 213,
"provenance": "stackexchange_0000F.jsonl.gz:849185",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493504"
}
|
1c9878e67f884baf06dc37c32a0ad16238671c07
|
Stackoverflow Stackexchange
Q: Does TypeORM supports raw SQL queries for input and output? I would like to know if there is a feature of TypeORM that supports raw sql queries for Insert Update Delete Select etc..
A: According to this issue comment, TypeORM enables you to use any queries to your heart's content. using entityManager.query() Here is the documentation.
UPDATE
Link above is outdated, try this instead entity-manager-api.
const rawData = await manager.query(`SELECT * FROM USERS`);
|
Q: Does TypeORM supports raw SQL queries for input and output? I would like to know if there is a feature of TypeORM that supports raw sql queries for Insert Update Delete Select etc..
A: According to this issue comment, TypeORM enables you to use any queries to your heart's content. using entityManager.query() Here is the documentation.
UPDATE
Link above is outdated, try this instead entity-manager-api.
const rawData = await manager.query(`SELECT * FROM USERS`);
A: 2020 UPDATE, entityManager.query() basing the entityManager off the EntityManager class, was not working for me so had to do this:
import { getManager } from 'typeorm';
const entityManager = getManager();
const someQuery = await entityManager.query(`
SELECT
fw."X",
fw."Y",
ew.*
FROM "table1" as fw
JOIN "table2" as ew
ON fw."X" = $1 AND ew.id = fw."Y";
`, [param1]);
https://orkhan.gitbook.io/typeorm/docs/working-with-entity-manager
A: try out this (April, 2022, typeorm ^0.3.6)
import { DataSource } from "typeorm";
(async () => {
const AppDatasource = new DataSource({
type: "mysql",
host: "localhost",
port: 3306,
username: "root",
password: "root",
database: "your-database",
synchronize: false,
logging: false,
entities: ['src/entity/**/*.ts']
})
const appDataSource = await AppDataSource.initialize();
const queryRunner = await appDataSource.createQueryRunner();
var result = await queryRunner.manager.query(
`SELECT * FROM your-table LIMIT 100`
);
await console.log(result)
})()
A: You can use deprecated getConnection or repo instance:
const db = this.repo.manager; // or getConnection().manager
const users = await db.query(`SELECT * FROM "users";`);
const [{ total }] = await db.query(`SELECT COUNT(*) as total FROM "users";`);
// users.length === Number(total);
Metadata allows you to get table properties dynamically
// utilities...
const usersTableMeta = db.connection.getMetadata(UserEntity); // or getConnection().getMetadata(UserEntity);
const usersTable = `"${usersTableMeta.tableName}"`
// data...
const users = await db.query(`SELECT * FROM ${usersTable};`);
const admins = await db.query(`
SELECT id, name FROM ${usersTable}
WHERE ${usersTable}.role = 'admin';
`);
|
stackoverflow
|
{
"language": "en",
"length": 286,
"provenance": "stackexchange_0000F.jsonl.gz:849200",
"question_score": "51",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493554"
}
|
402078560c57ebf8891a87072e3a3fcdfd56207a
|
Stackoverflow Stackexchange
Q: Vue.js: uppercase doesn't work i have this code:
data: {
cols: ['nome', 'data', 'size', 'ext'],
items: []
},
I would need to turn the text into uppercase.
I tried this way, following the examples of the official site:
<th v-for="col in cols">
{{col | uppercase}}
</th>
However, the text remains in lowercase.
do you know why??
A: There's an alternative and simpler way to do this. Instead of using @wostex's approach for filters, you can use Javascript directly inside double bracket notation.
new Vue({
el: '#app',
data: {
cols: ['nome', 'data', 'size', 'ext']
}
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<table>
<thead>
<th v-for="col in cols">
{{ col.toUpperCase() }}
</th>
</thead>
</table>
</div>
|
Q: Vue.js: uppercase doesn't work i have this code:
data: {
cols: ['nome', 'data', 'size', 'ext'],
items: []
},
I would need to turn the text into uppercase.
I tried this way, following the examples of the official site:
<th v-for="col in cols">
{{col | uppercase}}
</th>
However, the text remains in lowercase.
do you know why??
A: There's an alternative and simpler way to do this. Instead of using @wostex's approach for filters, you can use Javascript directly inside double bracket notation.
new Vue({
el: '#app',
data: {
cols: ['nome', 'data', 'size', 'ext']
}
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<table>
<thead>
<th v-for="col in cols">
{{ col.toUpperCase() }}
</th>
</thead>
</table>
</div>
A: There are no built-in filters in Vue.js sinse 2.x, so you need to define a filter manually:
new Vue({
el: '#app',
data: {
cols: ['nome', 'data', 'size', 'ext']
},
filters: {
uppercase: function(v) {
return v.toUpperCase();
}
}
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<table>
<thead>
<th v-for="col in cols">
{{col | uppercase}}
</th>
</thead>
</table>
</div>
A: you only have to do the next:
`<th v-for="col in cols">
{{col = col.toUpperCase()}}
</th>`
A: There are two ways to add filter:
*
*when new Vue
new Vue({
el: '#app',
data: {},
methods: {},
filters: {
uppercase: function (value) {
if (!value) return ''
return value.charAt(0).toUpperCase() + value.slice(1)
}
}
})
*before new Vue (Global)
Vue.filter('uppercase', function (value) {
if (!value) return ''
return value.charAt(0).toUpperCase() + value.slice(1)
})
A: I know you asked for VueJS / Javascript implementation, but I wanted to share what I did from my end as well. I highly recommend just use CSS on this part to save some processing. Yes, I know the uppercase first word implementation in Vue speed is only less significant, but if you prefer saving brain power, then CSS text-transform: capitalize would do just fine since its only UI that you are concerned of, right? Here's some reference https://www.w3schools.com/cssref/pr_text_text-transform.asp
|
stackoverflow
|
{
"language": "en",
"length": 320,
"provenance": "stackexchange_0000F.jsonl.gz:849201",
"question_score": "11",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493564"
}
|
17abbe49601a6e8a688a75a66ce11250036ded58
|
Stackoverflow Stackexchange
Q: Argument of '#selector' does not refer to an '@objc' method, property or initializer Can anyone tell me why this code gives the error message "Argument of '#selector' does not refer to an '@objc' method, property or initializer"?
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector:#selector(updateTimer(until: 3)), userInfo: nil, repeats: true)
Here's the function:
func updateTimer(until endTime: Int) {
counter -= 1
timeLabel.text = String(counter)
if counter == endTime {
step += 1
}
}
What I have tried:
1. Adding @objc in front of the function.
A: The selector of a target / action method must be declared either without parameter or with one parameter passing the affected object.
In case of a Timer use the userInfo parameter to pass data.
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector:#selector(updateTimer(_:)), userInfo: 3, repeats: true)
func updateTimer(_ timer: Timer) {
let endTime = timer.userInfo as! Int
counter -= 1
timeLabel.text = String(counter)
if counter == endTime {
step += 1
}
}
If the enclosing class does not inherit form NSObject you have to add the @objc attribute to the action method.
|
Q: Argument of '#selector' does not refer to an '@objc' method, property or initializer Can anyone tell me why this code gives the error message "Argument of '#selector' does not refer to an '@objc' method, property or initializer"?
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector:#selector(updateTimer(until: 3)), userInfo: nil, repeats: true)
Here's the function:
func updateTimer(until endTime: Int) {
counter -= 1
timeLabel.text = String(counter)
if counter == endTime {
step += 1
}
}
What I have tried:
1. Adding @objc in front of the function.
A: The selector of a target / action method must be declared either without parameter or with one parameter passing the affected object.
In case of a Timer use the userInfo parameter to pass data.
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector:#selector(updateTimer(_:)), userInfo: 3, repeats: true)
func updateTimer(_ timer: Timer) {
let endTime = timer.userInfo as! Int
counter -= 1
timeLabel.text = String(counter)
if counter == endTime {
step += 1
}
}
If the enclosing class does not inherit form NSObject you have to add the @objc attribute to the action method.
|
stackoverflow
|
{
"language": "en",
"length": 179,
"provenance": "stackexchange_0000F.jsonl.gz:849279",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493778"
}
|
1515a04f49608d0fe618065a278823a6e119f7d0
|
Stackoverflow Stackexchange
Q: How to allow only specific credential for project in jenkins? I need to prevent using credentials by every projects. I.e. test1 project should be able to access only test1-cred and only if it is started by user1 from Gitlab or directly in Jenkins. Also this should be supported by Jenkins declarative pipeline. If you use specific credentials in Jenkinsfile which are not allowed for current project - Jenkins shouldn't allow to use them.
How can I implement such a behavior?
A: As far as I know there are three common places to configure credentials in Jenkins: by user, by folder or globally
It seems that the folder plugin would suit your use case. It allows to organize your projects in folders. For each folder you can configure access rights and credentials.
More informations on credentials: https://plugins.jenkins.io/credentials
|
Q: How to allow only specific credential for project in jenkins? I need to prevent using credentials by every projects. I.e. test1 project should be able to access only test1-cred and only if it is started by user1 from Gitlab or directly in Jenkins. Also this should be supported by Jenkins declarative pipeline. If you use specific credentials in Jenkinsfile which are not allowed for current project - Jenkins shouldn't allow to use them.
How can I implement such a behavior?
A: As far as I know there are three common places to configure credentials in Jenkins: by user, by folder or globally
It seems that the folder plugin would suit your use case. It allows to organize your projects in folders. For each folder you can configure access rights and credentials.
More informations on credentials: https://plugins.jenkins.io/credentials
|
stackoverflow
|
{
"language": "en",
"length": 137,
"provenance": "stackexchange_0000F.jsonl.gz:849283",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493790"
}
|
ef955b7e7e0fe24114e04ef11abaf1643b3a0a00
|
Stackoverflow Stackexchange
Q: Angular2 - Only Allow Alpha Characters TO Be Entered In An Input I am very new to Angular2 and cant seem to find my answer anywhere. I have an input (as show below) but I only want it to allow the following:
*
*A-Z
*a-z
*'
*-
*[SPACE]
I have no idea on how to do this. I have tried ng-pattern="/^[a-zA-Z\s]*$/", pattern="/^[a-zA-Z\s]*$/" and ng-pattern-restrict="/^[a-zA-Z\s]*$/".
HTML
<td>
<md-input-container>
<input mdInput [(ngModel)]="details.firstName" placeholder="First name(s)" ng-pattern="/^[a-zA-Z\s]*$/">
</md-input-container>
</td>
Ideally if a user enters a numeric character, I'd ether like it to be removed by itself or just not be allowed (not displayed) in the field
A: My fix was to do it in my component
firstName: ['', Validators.pattern('^[a-zA-Z \-\']+')],
|
Q: Angular2 - Only Allow Alpha Characters TO Be Entered In An Input I am very new to Angular2 and cant seem to find my answer anywhere. I have an input (as show below) but I only want it to allow the following:
*
*A-Z
*a-z
*'
*-
*[SPACE]
I have no idea on how to do this. I have tried ng-pattern="/^[a-zA-Z\s]*$/", pattern="/^[a-zA-Z\s]*$/" and ng-pattern-restrict="/^[a-zA-Z\s]*$/".
HTML
<td>
<md-input-container>
<input mdInput [(ngModel)]="details.firstName" placeholder="First name(s)" ng-pattern="/^[a-zA-Z\s]*$/">
</md-input-container>
</td>
Ideally if a user enters a numeric character, I'd ether like it to be removed by itself or just not be allowed (not displayed) in the field
A: My fix was to do it in my component
firstName: ['', Validators.pattern('^[a-zA-Z \-\']+')],
A: You need to use following to make pattern work
<input mdInput [(ngModel)]="details.firstName" placeholder="First name(s)" [pattern]="'^[a-zA-Z \-\']$'">
A: Angular Reactive Form Validation - To accept only alphabets and space.
firstName: [
'',
[
Validators.required,
Validators.maxLength(50),
Validators.pattern('^[a-zA-Z ]*$')
]
],
A: Use this :
ng-pattern="/^[a-zA-Z]*$/"
A: You can use following directive that allow to type strings which pass arbitrary regexp
import {Directive, HostListener, Input} from '@angular/core';
@Directive({selector: '[allowedRegExp]'})
export class AllowedRegExpDirective {
@Input() allowedRegExp: string;
@HostListener('keydown',['$event']) onKeyDown(event: any) {
let k=event.target.value + event.key;
if(['ArrowLeft','ArrowRight','ArrowUp','ArroDown','Backspace','Tab','Alt'
'Shift','Control','Enter','Delete','Meta'].includes(event.key)) return;
let re = new RegExp(this.allowedRegExp);
if(!re.test(k)) event.preventDefault();
}
}
example usage: 0-5 characters from your question
<input [allowedRegExp]="'^[a-zA-Z '-]{0,5}$'" type="text" ... >
|
stackoverflow
|
{
"language": "en",
"length": 224,
"provenance": "stackexchange_0000F.jsonl.gz:849291",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493815"
}
|
09b934048e4ee6431a7724fadebd0d907ad7951b
|
Stackoverflow Stackexchange
Q: Filling preallocated `pandas.DataFrame` I need to append a lot (1 440 000 000) of rows to a pandas.DataFrame.
I know the number of rows in advance, so I can preallocate it, then fill it with data in a C-like manner.
So far the best idea I have is pretty ugly:
>>> N = 1000000
>>> sham = [-1] * (N * len(THRESHOLDS) * len(OBJECTS)) # 1440000000
>>> DATA = pd.DataFrame({'threshold': pd.Categorical(sham, categories=THRESHOLDS, ordered=True),
... 'expected': pd.Series(sham, dtype=np.float16),
... 'iteration': pd.Series(sham, dtype=np.int32),
... 'analyser': pd.Categorical(sham, categories=ANALYSERS),
... 'object': pd.Categorical(sham, categories=OBJECTS),
... },
... columns=['threshold', 'expected', 'iteration', 'analyser', 'object'])
>>> ptr = 0
>>> for t in THRESHOLDS:
... for o in OBJECTS:
... for a in ANALYSERS:
... for i in range(N):
... DATA.iloc[ptr] = t, expectedMonteCarlo(o, a, t), i, a, o
... ptr += 1
The question is, how can I make my code cleaner? I mean especially:
*
*preallocate DATA without inflating it with sham list,
*append rows to preallocated DATA without use of index?
The main problem is memory efficiency. Otherwise I would go for appending records to list object, and then converting it to pandas.DataFrame.
|
Q: Filling preallocated `pandas.DataFrame` I need to append a lot (1 440 000 000) of rows to a pandas.DataFrame.
I know the number of rows in advance, so I can preallocate it, then fill it with data in a C-like manner.
So far the best idea I have is pretty ugly:
>>> N = 1000000
>>> sham = [-1] * (N * len(THRESHOLDS) * len(OBJECTS)) # 1440000000
>>> DATA = pd.DataFrame({'threshold': pd.Categorical(sham, categories=THRESHOLDS, ordered=True),
... 'expected': pd.Series(sham, dtype=np.float16),
... 'iteration': pd.Series(sham, dtype=np.int32),
... 'analyser': pd.Categorical(sham, categories=ANALYSERS),
... 'object': pd.Categorical(sham, categories=OBJECTS),
... },
... columns=['threshold', 'expected', 'iteration', 'analyser', 'object'])
>>> ptr = 0
>>> for t in THRESHOLDS:
... for o in OBJECTS:
... for a in ANALYSERS:
... for i in range(N):
... DATA.iloc[ptr] = t, expectedMonteCarlo(o, a, t), i, a, o
... ptr += 1
The question is, how can I make my code cleaner? I mean especially:
*
*preallocate DATA without inflating it with sham list,
*append rows to preallocated DATA without use of index?
The main problem is memory efficiency. Otherwise I would go for appending records to list object, and then converting it to pandas.DataFrame.
|
stackoverflow
|
{
"language": "en",
"length": 189,
"provenance": "stackexchange_0000F.jsonl.gz:849312",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493883"
}
|
4a138ae0f08e3c28eec56262d17abd7471a666eb
|
Stackoverflow Stackexchange
Q: Setting text in EditText Kotlin I am trying to set text in a EditText but it says:
Type mismatch.
Required: Editable
Found: String
My code is as follow:
String name = "Paramjeet"
val nametxt = findViewById (R.id.nametxt) as EditText
nametxt.text = name
Don't say to use setText because I am using kotlin, not Java.
A: Or you can use an extension property:
var EditText.value
get() = this.text.toString()
set(value) {
this.setText(value)
}
and use .value= instead of .text=
|
Q: Setting text in EditText Kotlin I am trying to set text in a EditText but it says:
Type mismatch.
Required: Editable
Found: String
My code is as follow:
String name = "Paramjeet"
val nametxt = findViewById (R.id.nametxt) as EditText
nametxt.text = name
Don't say to use setText because I am using kotlin, not Java.
A: Or you can use an extension property:
var EditText.value
get() = this.text.toString()
set(value) {
this.setText(value)
}
and use .value= instead of .text=
A: Or cast to TextView but I believe this should be fixed on kotlin side for sure for convenience of developers !
(someEditText as TextView).text = "someTextValue"
Or with some extensions:
val EditText.asTextView: TextView get() = this as TextView
var EditText.value: CharSequence?
get() = asTextView.text
set(value) {
asTextView.text = value
}
You can write:
someEditText.asTextView.text = "someTextValue"
or
someEditText.value = "someTextValue"
But sadly you just cannot write simple someEditText.text = "someTextValue"
A: Use setText(String), since editText.text expects an Editable, not a String.
A: Use setText(String) as EditText.text requires an editable at firstplace not String
WHY ?
Nice explanation by Michael given under this link. Do visit this link for more detail
When generating a synthetic property for a Java getter/setter pair Kotlin first looks for a getter. The getter is enough to create a synthetic property with a type of the getter. On the other hand the property will not be created if only a setter presents.
When a setter comes into play property creation becomes more difficult. The reason is that the getter and the setter may have different type. Moreover, the getter and/or the setter may be overridden in a subclass.
A: There are several working answers here, but if you still want to use the property format and have your code look clean, you could write an extension:
fun String.toEditable(): Editable = Editable.Factory.getInstance().newEditable(this)
You can then use it as such:
mEditText.text = myString.toEditable()
A: Methods that follow the Java conventions for getters and setters (no-argument methods with names starting with get and single-argument methods with names starting with set) are represented as properties in Kotlin.
But, While generating a property for a Java getter/setter pair Kotlin at first looks for a getter. The getter is enough to infer the type of property from the type of the getter. On the other hand, the property will not be created if only a setter is present( because Kotlin does not support set-only properties at this time ) .
When a setter comes into play, property generation process becomes a bit ambiguous. The reason is that the getter and the setter may have different type. Moreover, the getter and/or the setter may be overridden in a subclass ,
which exactly is the case of EditText in android.
In above case the Android TextView class contains a getter
CharSequence getText()
and a setter void
setText(CharSequence)
If I had a variable of type TextView my code would have worked fine.
But I used EditText class which contains an overridden getter
Editable getText()
which means that you can get an Editable for an EditText and set an Editable to an EditText. Therefore, Kotlin reasonably creates a synthetic property text of type Editable. As String class is not Editable, that’s why I cannot assign a String instance to the text property of the EditText class.
It Seems like JetBrains forgot to specify the dominant role of getter methods while generating kotlin properties for Java getter and setter methods. Anyways, I have submitted pull request to Jet brains kotlin website through github.
I have detailed above problem in this medium post too How Does Kotlin Generate Property from Java Getters and Setters (Undocumented by Jetbrains)
A: If you want to use getter .text from principle, use:
nametxt.text = Editable.Factory.getInstance().newEditable(name)
A: Simple Solution
Just use edittext.setText(yourdata) instead of edittext.text because the EditText is editable, the edittext.text is used for TextView
For Example:
var name:String = "Muzammil"
edittext.setText(name)
That's it its work for me.
A: Use like this:
edtTitle.setText(intent.getStringExtra(EXTRA_TITLE))
edtDesc.setText(intent.getStringExtra(EXTRA_DESC))
A: I had the same issue in my projects, I give you an example that shows how to retrieve and set data in the layouts using Kotlin:
there is one button save_button and two text edit field edit_name and edit_password.
//when cliquing on the button 'save_button'
save_button.setOnClickListener {
// geting the value from the two fields by using .text.toString()
val email = edit_name.text.toString()
val password = edit_password.text.toString()
// showing the result on the systeme's log
Log.d("Main activity","your email is " + email )
Log.d("Main activity", "your password is $password" )
// Then shows these values into the text view palete using .setText()
text_view.setText("$email " + "$password")
}
A: val editable = Editable.Factory.getInstance().newEditable(savedString)
editText.text = editable
A: setText(String), so you must setText your string to editText, so in your case is : nametxt.setText(name)
A: Try using nametxt.post: nametxt.post({nametxt.setText("your text")})
A: Look at the API of EditText:
void setText (CharSequence text, TextView.BufferType type)
Editable getText ()
Link: https://developer.android.com/reference/android/widget/EditText.html
A: var name:String = "hello world"
textview.text = name
(or)
var editText:String = "hello world"
textview.setText(name)
|
stackoverflow
|
{
"language": "en",
"length": 833,
"provenance": "stackexchange_0000F.jsonl.gz:849321",
"question_score": "265",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44493908"
}
|
2d38b3d3a43c3a8418b0a638a347112adb0118ef
|
Stackoverflow Stackexchange
Q: Forget / Remove Stored WiFi Network in iOS Programmatically Since adding WiFi Network Programmatically in iOS is nearly impossible without jailbreaking the Iphone :(
Is it possible to Forget / Remove an already stored WiFi Network Programmatically with SWIFT or Objective-C without jailbreaking the iphone?
A: Unfortunately not, as this is not something done in the scope of an application.
And if it was possible, it seems like a sure way to not get your app approve for the App Store.
|
Q: Forget / Remove Stored WiFi Network in iOS Programmatically Since adding WiFi Network Programmatically in iOS is nearly impossible without jailbreaking the Iphone :(
Is it possible to Forget / Remove an already stored WiFi Network Programmatically with SWIFT or Objective-C without jailbreaking the iphone?
A: Unfortunately not, as this is not something done in the scope of an application.
And if it was possible, it seems like a sure way to not get your app approve for the App Store.
|
stackoverflow
|
{
"language": "en",
"length": 82,
"provenance": "stackexchange_0000F.jsonl.gz:849358",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494018"
}
|
b917f95e8d2c3078ac993cecca82e808c168e629
|
Stackoverflow Stackexchange
Q: change back button arrow color in ionic 3 How to change back button color in ionic 3? (From white to black color). It's screenshot with this button:
A: You can just do it by using the css.
.back-button-icon-md {
color: darkblue;
}
Note: md is for android . For ios replace md to ios, For windows replace md to wp.
|
Q: change back button arrow color in ionic 3 How to change back button color in ionic 3? (From white to black color). It's screenshot with this button:
A: You can just do it by using the css.
.back-button-icon-md {
color: darkblue;
}
Note: md is for android . For ios replace md to ios, For windows replace md to wp.
A: You can change it by just using css. Place the following style rule in the app.scss file:
ion-header ion-icon.back-button-icon.icon {
color: map-get($colors, dark);
}
That would use the dark color from your $colors array (variables.scss file):
$colors: (
//...
dark: #222
);
|
stackoverflow
|
{
"language": "en",
"length": 104,
"provenance": "stackexchange_0000F.jsonl.gz:849376",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494078"
}
|
6ae729c12f371fa5373b4130dff6b18148d15436
|
Stackoverflow Stackexchange
Q: How to display a field of a object linked by a foreign key in odoo / openerp? I try to display the company_registry number of the client into the account.invoice_form.
In python, the field is addressed by (my_invoice_object).partner_id.company_registry
In xml I tried several things but nothing worked. Here is one of my attempts :
<record id="view_invoice_form_tis" model="ir.ui.view">
<field name="name">view_invoice_form_tis</field>
<field name="model">account.invoice</field>
<field name="inherit_id" ref="account.invoice_form"/>
<field name="arch" type="xml">
<xpath expr="//field[@name='move_id']" position="after">
<field name="partner_id.company_registry"/>
</xpath>
</field>
</record>
Does anybody has the trick ?
Herve
A: You can do one thing. Add a new field in your model and save your required values to that field. Then display your new field.
In XML dot operation won't work
|
Q: How to display a field of a object linked by a foreign key in odoo / openerp? I try to display the company_registry number of the client into the account.invoice_form.
In python, the field is addressed by (my_invoice_object).partner_id.company_registry
In xml I tried several things but nothing worked. Here is one of my attempts :
<record id="view_invoice_form_tis" model="ir.ui.view">
<field name="name">view_invoice_form_tis</field>
<field name="model">account.invoice</field>
<field name="inherit_id" ref="account.invoice_form"/>
<field name="arch" type="xml">
<xpath expr="//field[@name='move_id']" position="after">
<field name="partner_id.company_registry"/>
</xpath>
</field>
</record>
Does anybody has the trick ?
Herve
A: You can do one thing. Add a new field in your model and save your required values to that field. Then display your new field.
In XML dot operation won't work
A: What are you doing totally wrong. You have to first learn odoo. You can get technical guide from odoo documentation site.
for this thing you have to put related field in .py file, then you can add field in view.
Hope this help.
|
stackoverflow
|
{
"language": "en",
"length": 159,
"provenance": "stackexchange_0000F.jsonl.gz:849381",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494095"
}
|
50d700a3281f8caf3aeedef7efa3d5215e756e0d
|
Stackoverflow Stackexchange
Q: How do we exlude some folder in the root src folder when running ng build In my application generated by angular-cli there is angular-cli.json file which control ng operations.
But how do we exclude some folder inside src which is specified in the root?
"apps": [{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"polyfills": "polyfills.ts",
"test": "test.ts",
"tsconfig": "tsconfig.app.json",
"testTsconfig": "tsconfig.spec.json",
"prefix": "app",
"styles": [
"styles.css"
],
"scripts": [],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}],
Im thinking to add something like "exclude": [ "folder_name1", "folder_name1" ] but i cannot find any solution that agree in this.
A: ng-build will run tsc to compile target files, you can add exclude settings into tsconfig.app.json to exclude some specific files or folder.
{
"compilerOptions": {
...
},
"exclude": [
"folder" // example
]
}
|
Q: How do we exlude some folder in the root src folder when running ng build In my application generated by angular-cli there is angular-cli.json file which control ng operations.
But how do we exclude some folder inside src which is specified in the root?
"apps": [{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"polyfills": "polyfills.ts",
"test": "test.ts",
"tsconfig": "tsconfig.app.json",
"testTsconfig": "tsconfig.spec.json",
"prefix": "app",
"styles": [
"styles.css"
],
"scripts": [],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}],
Im thinking to add something like "exclude": [ "folder_name1", "folder_name1" ] but i cannot find any solution that agree in this.
A: ng-build will run tsc to compile target files, you can add exclude settings into tsconfig.app.json to exclude some specific files or folder.
{
"compilerOptions": {
...
},
"exclude": [
"folder" // example
]
}
A: This configuration is in tsconfig-json https://www.typescriptlang.org/docs/handbook/tsconfig-json.html
{
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"outFile": "../../built/local/tsc.js",
"sourceMap": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
|
stackoverflow
|
{
"language": "en",
"length": 175,
"provenance": "stackexchange_0000F.jsonl.gz:849416",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494222"
}
|
bc449ed34089208aa280b4edeaecd268f01c00b0
|
Stackoverflow Stackexchange
Q: Set .history folder as ignored by intellisense I need to ignore .history folder from intellisense.
Now it looks like this when I start typing Focus:
As you can see intellisense will offer me every Identical class found in .history folder and this is very very confusing (and find correct one).
I try find something in vscode settings, and on editor site but no success.
.history folder is ignored from git, display in explorer, and tslint:
"files.exclude": {
"**/.history": true ...
},
"files.watcherExclude": {
"**/.history/**": true ...
},
"tslint.exclude": ["**/.history/**"] ...
How to achieve ignore .history from intellisense?
Next part is based on the answer from Matt
An important assumption:
Visual Studio Code itself does not contain automatic import and you need an extension for it.
Solution:
I am using extension Auto Import (steoates.autoimport) which contains the setting autoimport.filesToScan. I changed default value from "**/*.{ts,tsx}" to "{src,e2e,node_modules}/**/*.{ts,tsx}" and now everything work as I expected.
A: Those suggestions are coming whatever extension you have installed that is providing auto-import functionality. Please check to see if that extension has its own exclude setting that you also need to configure
|
Q: Set .history folder as ignored by intellisense I need to ignore .history folder from intellisense.
Now it looks like this when I start typing Focus:
As you can see intellisense will offer me every Identical class found in .history folder and this is very very confusing (and find correct one).
I try find something in vscode settings, and on editor site but no success.
.history folder is ignored from git, display in explorer, and tslint:
"files.exclude": {
"**/.history": true ...
},
"files.watcherExclude": {
"**/.history/**": true ...
},
"tslint.exclude": ["**/.history/**"] ...
How to achieve ignore .history from intellisense?
Next part is based on the answer from Matt
An important assumption:
Visual Studio Code itself does not contain automatic import and you need an extension for it.
Solution:
I am using extension Auto Import (steoates.autoimport) which contains the setting autoimport.filesToScan. I changed default value from "**/*.{ts,tsx}" to "{src,e2e,node_modules}/**/*.{ts,tsx}" and now everything work as I expected.
A: Those suggestions are coming whatever extension you have installed that is providing auto-import functionality. Please check to see if that extension has its own exclude setting that you also need to configure
A: In your settings.json, you could add this:
"autoimport.filesToScan": "./index.{ts,tsx} ./App.{ts,tsx} ./src/**.*.{ts,tsx}"
Or, if you prefer:
"autoimport.filesToScan": "./{index,App,src/**}.{ts,tsx}"
|
stackoverflow
|
{
"language": "en",
"length": 205,
"provenance": "stackexchange_0000F.jsonl.gz:849435",
"question_score": "14",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494280"
}
|
4bbb183d5e6249e9aee0f4190be8d6da4a1c5661
|
Stackoverflow Stackexchange
Q: show git branches with date of last commit I was working on a branch a couple of weeks ago but I can't remember what the branch was called (there are many). I'd like to be able to do something like:
git branch --print-last-commit
and for it to output something like:
branch 1 - 2017-02-12
branch 2 - 2016-12-30
etc.
Is there any way to do this?
A: This will print BranchName - CommitMessage - Date as (YYYY-MM-DD). You can manipulate/edit this command line to suit your need.
git for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:short)%(color:reset))'
Note that it will print for all local branches, not just current branch. You can create an alias for convenience.
[alias]
branchcommits = !git for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:short)%(color:reset))'
and run git branchcommits in git bash prompt.
|
Q: show git branches with date of last commit I was working on a branch a couple of weeks ago but I can't remember what the branch was called (there are many). I'd like to be able to do something like:
git branch --print-last-commit
and for it to output something like:
branch 1 - 2017-02-12
branch 2 - 2016-12-30
etc.
Is there any way to do this?
A: This will print BranchName - CommitMessage - Date as (YYYY-MM-DD). You can manipulate/edit this command line to suit your need.
git for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:short)%(color:reset))'
Note that it will print for all local branches, not just current branch. You can create an alias for convenience.
[alias]
branchcommits = !git for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:short)%(color:reset))'
and run git branchcommits in git bash prompt.
A: You can use below command to get all last commit per branch
for branch in `git branch -r | grep -v HEAD`;do echo -e `git show --format="%ci %cr" $branch | head -n 1` \\t$branch; done | sort -r
More info at https://gist.github.com/jasonrudolph/1810768
A: I know this post is old, though with the help of other answers, I came out with another solution that does not involve a bash for loop.
$ paste <(git branch | xargs -I {} git --no-pager show -q --format="%ci %cr" {} | tail -n +1) \
<(git branch) | sort -h | tail -5
2021-10-12 11:24:21 -0700 2 weeks ago adamryman/foobar
2021-10-12 15:20:18 -0700 2 weeks ago adamryman/foobarbaz
2021-10-26 16:46:25 -0700 3 days ago adamryman/baz
2021-10-27 19:00:14 -0700 2 days ago adamryman/foobaz
2021-10-28 14:03:48 -0700 21 hours ago adamryman/barfoo
|
stackoverflow
|
{
"language": "en",
"length": 275,
"provenance": "stackexchange_0000F.jsonl.gz:849441",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494296"
}
|
6faa354d2fed5a5577edabcf00ffad06da3dd4c1
|
Stackoverflow Stackexchange
Q: Rails language name using I18n locale I want to match the locale code to the specific language name. Is there any build in function in I18n/rails which would return the language name to the corresponding locales. Is installing a gem is the only way?
A: Without installing an additional gem, you could make your own key/value pairs (either store it in a json file or store it to DB) and then lookup key eg "de" and read the value (in this case, "German"). It requires a bit of manual work (or setup a rake task or something to build it for you in appropriate format from some info source) but you aren't dependent on an additional gem in that case (which, without going thoroughly through the code, might have a far greater impact on your app performance/memory wise than your custom implementation for your specific need for all you know).
I am not aware of any rails built in functions that would return the entire language name, though. You can return the language abbreviation (eg for use in html lang attribute), but I think it stops there as far as the built in functions are concerned).
|
Q: Rails language name using I18n locale I want to match the locale code to the specific language name. Is there any build in function in I18n/rails which would return the language name to the corresponding locales. Is installing a gem is the only way?
A: Without installing an additional gem, you could make your own key/value pairs (either store it in a json file or store it to DB) and then lookup key eg "de" and read the value (in this case, "German"). It requires a bit of manual work (or setup a rake task or something to build it for you in appropriate format from some info source) but you aren't dependent on an additional gem in that case (which, without going thoroughly through the code, might have a far greater impact on your app performance/memory wise than your custom implementation for your specific need for all you know).
I am not aware of any rails built in functions that would return the entire language name, though. You can return the language abbreviation (eg for use in html lang attribute), but I think it stops there as far as the built in functions are concerned).
A: It seems there is no method for this in I18n.
If you just need current language name, you can easily include it in corresponding locale file:
# config/locales/en.yml
en:
language_name: "English"
And get it as usual: I18n.t('language_name') or I18n.t('language_name', locale: :en).
For general purposes you could use: https://github.com/hexorx/countries or initialize your own mapping as a ruby hash: { en: 'English', ... }.
A: Have a look the following post in google groups (Gist). I hope there is no default support for the required conversion in rails.
|
stackoverflow
|
{
"language": "en",
"length": 284,
"provenance": "stackexchange_0000F.jsonl.gz:849449",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494323"
}
|
cf33f996f092aa43d30fbd0d78337dcb16f96d61
|
Stackoverflow Stackexchange
Q: How can get this tool tip on top? I am having trouble getting my tooltips on the top, some of the tool-tips are not visible on smaller screen sizes
I have set its position and z-index, but still it is not showing.
A: Changing the value of z-index will not show it as #price-table-fix is hiding all overflowed content that is outside the block.
Add rules and property below and it should fix it.
#price-table-fix {
overflow: visible;
}
|
Q: How can get this tool tip on top? I am having trouble getting my tooltips on the top, some of the tool-tips are not visible on smaller screen sizes
I have set its position and z-index, but still it is not showing.
A: Changing the value of z-index will not show it as #price-table-fix is hiding all overflowed content that is outside the block.
Add rules and property below and it should fix it.
#price-table-fix {
overflow: visible;
}
|
stackoverflow
|
{
"language": "en",
"length": 80,
"provenance": "stackexchange_0000F.jsonl.gz:849469",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494390"
}
|
f325918541177697c30c2e811db5dde5d1ce5493
|
Stackoverflow Stackexchange
Q: Back edges in a graph I'm having a hard time understanding Tarjan's algorithm for articulation points. I'm currently following this tutorial here: https://www.hackerearth.com/practice/algorithms/graphs/articulation-points-and-bridges/tutorial/. What I really can't see, and couldn't see in any other tutorial, is what exactly a "back edge" means. Considering the graph given there, I know 3-1 and 4-2 are back edges, but are 2-1, 3-2, and 4-3 back edges too? Thank you.
A: Consider the following (directed) graph traversal with DFS. Here the colors of the nodes represent the following:
*
*The floral-white nodes are the ones that are yet to be visited
*The gray nodes are the nodes that are visited and on stack
*The black nodes are the ones that are popped from the stack.
Notice that when the node 13 discovers the node 0 through the edge 13->0 the node 0 is still on the stack. Here, 13->0 is a back edge and it denotes the existence of a cycle (the triangle 0->1->13).
|
Q: Back edges in a graph I'm having a hard time understanding Tarjan's algorithm for articulation points. I'm currently following this tutorial here: https://www.hackerearth.com/practice/algorithms/graphs/articulation-points-and-bridges/tutorial/. What I really can't see, and couldn't see in any other tutorial, is what exactly a "back edge" means. Considering the graph given there, I know 3-1 and 4-2 are back edges, but are 2-1, 3-2, and 4-3 back edges too? Thank you.
A: Consider the following (directed) graph traversal with DFS. Here the colors of the nodes represent the following:
*
*The floral-white nodes are the ones that are yet to be visited
*The gray nodes are the nodes that are visited and on stack
*The black nodes are the ones that are popped from the stack.
Notice that when the node 13 discovers the node 0 through the edge 13->0 the node 0 is still on the stack. Here, 13->0 is a back edge and it denotes the existence of a cycle (the triangle 0->1->13).
A: In essence, when you do a DFS, if there are cycles in your graph between nodes A, B and C and you have discovered the edges A-B, later you discover the edge B-C, then, since you have reached node C, you will discover the edge C-A, but you need to ignore this path in your search to avoid infinite loops. So, in your search A-B and B-C were not back edges, but C-A is a back edge, since this edge forms a cycle back to an already visited node.
A:
...a Back Edge is an edge that connects a vertex to a vertex that is discovered before it's parent.
from your source.
Think about it like this: When you apply a DFS on a graph you fix some path that the algorithm chooses. Now in the given case: 0->1->2->3->4. As in the article mentioned, the source graph contains the edges 4-2 and 3-1. When the DFS reaches 3 it could choose 1 but 1 is already in your path so it is a back edge and therefore, as mentioned in the source, a possible alternative path.
Addressing your second question: Are 2-1, 3-2, and 4-3 back edges too? For a different path they can be. Suppose your DFS chooses 0->1->3->2->4 then 2-1 and 4-3 are back edges.
A: From article mentioned:
Given a DFS tree of a graph, a Back Edge is an edge that connects a
vertex to a vertex that is discovered before it's parent.
2-1, 3-2, 4-3 are not "Back edge" because they link the vertices with their parents in DFS tree.
A: Here is the code for a better understand:
#include<bits/stdc++.h>
using namespace std;
struct vertex{
int node;
int start;
int finish;
int color;
int parent;
};
int WHITE=0, BLACK=1, GREY=2;
vector<int> adjList[8];
int num_of_verts = 8;
struct vertex vertices[8];
int t=0;
bool DFS_visit(int u){
bool cycleExists = false;
vertices[u].color=GREY;
t++;
vertices[u].start= t;
for( int i=0; adjList[u][i]!=-1; i++){
if( vertices[adjList[u][i]].color == WHITE ){
if(!cycleExists) cycleExists = DFS_visit(adjList[u][i]);
else DFS_visit(adjList[u][i]);
}
else {
cout << "Cycle detected at edge - ("<<u<<", "<<adjList[u][i]<<")"<<endl;
cycleExists = true;
}
}
vertices[u].color=BLACK;
t++;
vertices[u].finish= t;
return cycleExists;
}
void DFS(){
for(int i=0;i<num_of_verts;i++){
vertices[i].color=WHITE;
vertices[i].parent=NULL;
}
t=0;
for(int i=0;i<num_of_verts;i++){
if(vertices[i].color==WHITE){
cout << "Traversing component "<<i<<"-"<<endl;
bool cycle = DFS_visit(i);
cycle==1? cout<<"Cycle Exists\n\n":cout <<"Cycle does not exist\n\n";
}
}
}
int main(){
adjList[0] = {4, -1};
adjList[1] = {0, 5, -1};
adjList[2] = {1, 5, -1};
adjList[3] = {6, 7, -1};
adjList[4] = {1, -1};
adjList[5] = {-1};
adjList[6] = {2, 5, -1};
adjList[7] = {3, 6, -1};
DFS();
return 0;
}
|
stackoverflow
|
{
"language": "en",
"length": 591,
"provenance": "stackexchange_0000F.jsonl.gz:849479",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494426"
}
|
411e6bc1d5bdd34023d09d1c6ca51ad3731e6541
|
Stackoverflow Stackexchange
Q: How to list files in a directory in python? I am unable to list files in a directory with this code
import os
from os import listdir
def fn(): # 1.Get file names from directory
file_list=os.listdir(r"C:\Users\Jerry\Downloads\prank\prank")
print (file_list)
#2.To rename files
fn()
on running the code it gives no output !
A: The function call fn() was inside the function definition def fn(). You must call it outside by unindenting the last line of your code:
import os
def fn(): # 1.Get file names from directory
file_list=os.listdir(r"C:\Users")
print (file_list)
#2.To rename files
fn()
|
Q: How to list files in a directory in python? I am unable to list files in a directory with this code
import os
from os import listdir
def fn(): # 1.Get file names from directory
file_list=os.listdir(r"C:\Users\Jerry\Downloads\prank\prank")
print (file_list)
#2.To rename files
fn()
on running the code it gives no output !
A: The function call fn() was inside the function definition def fn(). You must call it outside by unindenting the last line of your code:
import os
def fn(): # 1.Get file names from directory
file_list=os.listdir(r"C:\Users")
print (file_list)
#2.To rename files
fn()
A: You should use something like this
for file_ in os.listdir(exec_dir):
if os.path.isdir(exec_dir+file):
print file_
I hope this is useful.
A: if you want to list all files including sub dirs.
you can use this recursive solution
import os
def fn(dir=r"C:\Users\aryan\Downloads\opendatakit"):
file_list = os.listdir(dir)
res = []
# print(file_list)
for file in file_list:
if os.path.isfile(os.path.join(dir, file)):
res.append(file)
else:
result = fn(os.path.join(dir, file))
if result:
res.extend(fn(os.path.join(dir, file)))
return res
res = fn()
print(res)
print(len(res))
|
stackoverflow
|
{
"language": "en",
"length": 167,
"provenance": "stackexchange_0000F.jsonl.gz:849481",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494431"
}
|
f72286d7e836eabd906720be86bdd9787b07fba9
|
Stackoverflow Stackexchange
Q: Cast from generic type to unrelated type sub-class always fails I have a class which is derived from generic type class.
open class Model<T>: BaseModel where T: SomeData {
}
There is another class derived from SomeData.
open class NetworkData: SomeData {
}
Now I have a class which serves as base class for many models.
open class ParentModel: Model<NetworkData> {
}
There are two child classes derived from ParentModel.
open class SonModel: ParentModel {
}
open class DaughterModel: ParentModel {
}
There many other classes derived from Model generic type.
In one of the situation I want to use this generic type as function argument and later type-cast it to specialize class.
I have done following code to achieve the purpose
func someName<T: SomeData>(model: Model<T>) {
guard let model = model as? DaughterModel else {
//Some code here
}
//Main logic goes here
}
However, on the line
guard let model = model as? DaughterModel
I am getting following error
Cast from 'Model' to unrelated type 'DaughterModel' always fails.
How to fix the error? Any help is greatly appreciated.
|
Q: Cast from generic type to unrelated type sub-class always fails I have a class which is derived from generic type class.
open class Model<T>: BaseModel where T: SomeData {
}
There is another class derived from SomeData.
open class NetworkData: SomeData {
}
Now I have a class which serves as base class for many models.
open class ParentModel: Model<NetworkData> {
}
There are two child classes derived from ParentModel.
open class SonModel: ParentModel {
}
open class DaughterModel: ParentModel {
}
There many other classes derived from Model generic type.
In one of the situation I want to use this generic type as function argument and later type-cast it to specialize class.
I have done following code to achieve the purpose
func someName<T: SomeData>(model: Model<T>) {
guard let model = model as? DaughterModel else {
//Some code here
}
//Main logic goes here
}
However, on the line
guard let model = model as? DaughterModel
I am getting following error
Cast from 'Model' to unrelated type 'DaughterModel' always fails.
How to fix the error? Any help is greatly appreciated.
|
stackoverflow
|
{
"language": "en",
"length": 181,
"provenance": "stackexchange_0000F.jsonl.gz:849512",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494529"
}
|
9673812f0872d19bd8fae71d62f9eff0cddf145f
|
Stackoverflow Stackexchange
Q: How can I set custom voice command with Google Assistant that wake my app? I want to set custom voice command for my app. For example if my app name is apple I want to wake my app by saying apple. Or something like apple turn of the lamp.
Does android have something like that? If not can I use a receiver to detect voice commands and wait for apple voice? For voice detection use Google Voice detection.
Thanks.
|
Q: How can I set custom voice command with Google Assistant that wake my app? I want to set custom voice command for my app. For example if my app name is apple I want to wake my app by saying apple. Or something like apple turn of the lamp.
Does android have something like that? If not can I use a receiver to detect voice commands and wait for apple voice? For voice detection use Google Voice detection.
Thanks.
|
stackoverflow
|
{
"language": "en",
"length": 80,
"provenance": "stackexchange_0000F.jsonl.gz:849516",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494543"
}
|
e888b5d21b620a5dea88434080fc5285facf0582
|
Stackoverflow Stackexchange
Q: .NET core with FakeItEasy Can FakeItEasy work with .NET core? I have installed it through NuGet but I can't reference it in the project as using FakeItEasy because it doesn't find it. I have checked under NuGet dependencies and I see it as FakeItEasy (3.3.2)
A: Yes, FakeItEasy > 3.0.0 is compatible with .NET Standard 1.6 which means it will run in .NET Core 1.0 and higher.
You may have problems restoring and using packages, try running dotnet restore from command line and closing and re-opening visual studio completely. Also check if dotnet build gives the same error message as VS.
|
Q: .NET core with FakeItEasy Can FakeItEasy work with .NET core? I have installed it through NuGet but I can't reference it in the project as using FakeItEasy because it doesn't find it. I have checked under NuGet dependencies and I see it as FakeItEasy (3.3.2)
A: Yes, FakeItEasy > 3.0.0 is compatible with .NET Standard 1.6 which means it will run in .NET Core 1.0 and higher.
You may have problems restoring and using packages, try running dotnet restore from command line and closing and re-opening visual studio completely. Also check if dotnet build gives the same error message as VS.
|
stackoverflow
|
{
"language": "en",
"length": 102,
"provenance": "stackexchange_0000F.jsonl.gz:849527",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494574"
}
|
2bc2f0cce375317ddea6d71596bc60855dd735ed
|
Stackoverflow Stackexchange
Q: Jenkins pipeline "waitUntil" - change delay between attempts We use a Jenkins pipeline for our builds and tests. After the build, we run automated tests on several measurement devices.
For a better overview about the needed testing time, I created a test stage which is periodically checking the status of the tests. When all tests are finished, the pipeline is done. I use the "waitUntil" implementation of Jenkins pipeline for this functionality.
My problem is: The pause between the attemps gets more and more after every try. This is a quite good idea. BUT: After a while, the pause between the attemps gets up to 16 hours and more. This value is too high for my needs because I want to know the needed test time exactly.
My question is: Does anyone know a way to change this behaviour of "waitUntil"?
I know I could use a "while" loop but I would prefer to solve this using "waitUntil".
stage ">>> Waiting for testruns"
waitUntil {
sleep(10)
return(checkIfTestsAreFinished())
}
A: New versions of Jenkins have capped this to never go over 15 seconds (see https://issues.jenkins-ci.org/browse/JENKINS-34554 ).
|
Q: Jenkins pipeline "waitUntil" - change delay between attempts We use a Jenkins pipeline for our builds and tests. After the build, we run automated tests on several measurement devices.
For a better overview about the needed testing time, I created a test stage which is periodically checking the status of the tests. When all tests are finished, the pipeline is done. I use the "waitUntil" implementation of Jenkins pipeline for this functionality.
My problem is: The pause between the attemps gets more and more after every try. This is a quite good idea. BUT: After a while, the pause between the attemps gets up to 16 hours and more. This value is too high for my needs because I want to know the needed test time exactly.
My question is: Does anyone know a way to change this behaviour of "waitUntil"?
I know I could use a "while" loop but I would prefer to solve this using "waitUntil".
stage ">>> Waiting for testruns"
waitUntil {
sleep(10)
return(checkIfTestsAreFinished())
}
A: New versions of Jenkins have capped this to never go over 15 seconds (see https://issues.jenkins-ci.org/browse/JENKINS-34554 ).
A: In waitUntil, if the processing in the block returns false, then the waitUntil step waits a bit longer and tries again. “a bit longer” means, a 0.25 second wait time. If it needs to loop again, it multiplies that by a factor of 1.2 to get 0.3 seconds for the next wait cycle. On each succeeding cycle, the last wait time is multiplied again by 1.2 to get the time to wait. So, the sequence goes as 0.25, 0.3, 0.36, 0.43, 0.51... until 15 secs(as it is mentioned in one of the answers below, Jenkins solved it).
See the image below:
If you are using older Jenkins version then possible solution could be to use timeout
timeout(time: 1, unit: 'HOURS'){
// you can change format in seconds, minutes, hours
// you can decide your know timeout limit.
waitUntil {
try {
//sleep(10)// you don't need this
return(checkIfTestsAreFinished())
} catch (exception) {
return false
}
}//waituntil
}//timeout
Please note the behavior is from Jenkins LTS 2.235.3.
A: Jenkins command waitUntil is not supposed to launch something synchronously.
To know the required time you must add a timestamp into the test output parse it and calc separately.
|
stackoverflow
|
{
"language": "en",
"length": 382,
"provenance": "stackexchange_0000F.jsonl.gz:849557",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494668"
}
|
5761fecfa299dd89b3b6f8dc5e75564340063cf7
|
Stackoverflow Stackexchange
Q: Ansible: how to register variable in uri module?
This is my code or checking wheter the website is valid and running:
- hosts: master
become: true
tasks:
- name: "Checking server availibility"
uri:
url: http://www.google.pl
timeout: 5
register: command_result
ignore_errors: yes
- debug: msg= "{{ command_result }}"
So command_result variable always returns this output regardless of the website availability:
ok: [Centos.v1] => {
"changed": false,
"msg": "Hello world!"
}
I would like to know if the first task was succesful or not but i can't do that when the output of registered variable is always the same.
How to setup my variable properly to read the return code?
and also
Is there some other way to check if an error occured in the previous task?
A: This has nothing to do with registering.
Remove the space character after msg=, otherwise you pass an empty string to the debug module and it prints Hello World! as a result (its default behaviour).
Better yet, use var parameter and YAML syntax:
- debug:
var: command_result
|
Q: Ansible: how to register variable in uri module?
This is my code or checking wheter the website is valid and running:
- hosts: master
become: true
tasks:
- name: "Checking server availibility"
uri:
url: http://www.google.pl
timeout: 5
register: command_result
ignore_errors: yes
- debug: msg= "{{ command_result }}"
So command_result variable always returns this output regardless of the website availability:
ok: [Centos.v1] => {
"changed": false,
"msg": "Hello world!"
}
I would like to know if the first task was succesful or not but i can't do that when the output of registered variable is always the same.
How to setup my variable properly to read the return code?
and also
Is there some other way to check if an error occured in the previous task?
A: This has nothing to do with registering.
Remove the space character after msg=, otherwise you pass an empty string to the debug module and it prints Hello World! as a result (its default behaviour).
Better yet, use var parameter and YAML syntax:
- debug:
var: command_result
|
stackoverflow
|
{
"language": "en",
"length": 173,
"provenance": "stackexchange_0000F.jsonl.gz:849568",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494715"
}
|
0e1cd17831e58942655a0df06ebdfc0b589b5bb0
|
Stackoverflow Stackexchange
Q: How do we return ggplot graphs through plumber web api? I was plotting a bar plot using ggplot and I created this function as a web api using plumber package in R.
library(plumber)
library(ggplot2)
#' @get /histogram_test
#' @png
histogram_test <- function(){
mtcars=mtcars
b=ggplot(mtcars,aes(mtcars$cyl))
b+geom_bar()
}
Then I run:
r <- plumb("plum_api.R")
r$run(port=8000)
But this does not return the plot on the browser.
A: So it works if in the last line we just use the print command as:
print(b+geom_bar()).
|
Q: How do we return ggplot graphs through plumber web api? I was plotting a bar plot using ggplot and I created this function as a web api using plumber package in R.
library(plumber)
library(ggplot2)
#' @get /histogram_test
#' @png
histogram_test <- function(){
mtcars=mtcars
b=ggplot(mtcars,aes(mtcars$cyl))
b+geom_bar()
}
Then I run:
r <- plumb("plum_api.R")
r$run(port=8000)
But this does not return the plot on the browser.
A: So it works if in the last line we just use the print command as:
print(b+geom_bar()).
|
stackoverflow
|
{
"language": "en",
"length": 81,
"provenance": "stackexchange_0000F.jsonl.gz:849607",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494822"
}
|
99e7fc0b08cfef14bf39b51b42bbe750d553364c
|
Stackoverflow Stackexchange
Q: Realm access from incorrect thread in Espresso Before each espresso test, I have an annotation @Before where I initialize my RealmManager.realm.
Code snippet of my object Realm:
init {
Realm.init(SaiApplication.context)
val builder = RealmConfiguration.Builder().schemaVersion(SCHEMA_VERSION)
builder.migration(runMigrations())
if (!BuildConfig.DEBUG) builder.encryptionKey(getOrCreateDatabaseKey())
if (SaiApplication.inMemoryDatabase) builder.inMemory()
Realm.setDefaultConfiguration(builder.build())
try {
errorOccurred = false
realm = Realm.getDefaultInstance()
} catch (e: Exception) {
errorOccurred = true
realm = Realm.getInstance(RealmConfiguration.Builder()
.schemaVersion(SCHEMA_VERSION).name(errorDbName).build())
e.log()
deleteRealmFile(realm.configuration.realmDirectory)
}
}
But when I run my tests, I get next error:
Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created
So how i can correctly init my realm in my tests?
One of the solutions that I found interesting, create a fake init realm.
A: To manipulate the UI thread's Realm instance from your UI tests, you need to initialize the Realm instance on the UI thread using instrumentation.runOnMainSync(() -> {...});.
@Before
public void setup() {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
instrumentation.runOnMainSync(new Runnable() {
@Override
public void run() {
// setup UI thread Realm instance configuration
}
});
}
|
Q: Realm access from incorrect thread in Espresso Before each espresso test, I have an annotation @Before where I initialize my RealmManager.realm.
Code snippet of my object Realm:
init {
Realm.init(SaiApplication.context)
val builder = RealmConfiguration.Builder().schemaVersion(SCHEMA_VERSION)
builder.migration(runMigrations())
if (!BuildConfig.DEBUG) builder.encryptionKey(getOrCreateDatabaseKey())
if (SaiApplication.inMemoryDatabase) builder.inMemory()
Realm.setDefaultConfiguration(builder.build())
try {
errorOccurred = false
realm = Realm.getDefaultInstance()
} catch (e: Exception) {
errorOccurred = true
realm = Realm.getInstance(RealmConfiguration.Builder()
.schemaVersion(SCHEMA_VERSION).name(errorDbName).build())
e.log()
deleteRealmFile(realm.configuration.realmDirectory)
}
}
But when I run my tests, I get next error:
Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created
So how i can correctly init my realm in my tests?
One of the solutions that I found interesting, create a fake init realm.
A: To manipulate the UI thread's Realm instance from your UI tests, you need to initialize the Realm instance on the UI thread using instrumentation.runOnMainSync(() -> {...});.
@Before
public void setup() {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
instrumentation.runOnMainSync(new Runnable() {
@Override
public void run() {
// setup UI thread Realm instance configuration
}
});
}
A: What i do.
I just added next function in my AppTools, which check package with tests:
fun isTestsSuite() = AppResources.appContext?.classLoader.toString().contains("tests")
Then modifed init of Realm:
init {
Realm.init(AppResources.appContext)
val builder = RealmConfiguration.Builder().schemaVersion(SCHEMA_VERSION)
builder.migration(runMigrations())
if (!isTestsSuite()) builder.encryptionKey(getOrCreateDatabaseKey()) else builder.inMemory()
Realm.setDefaultConfiguration(builder.build())
try {
errorOccurred = false
realm = Realm.getDefaultInstance()
} catch (e: Exception) {
errorOccurred = true
realm = Realm.getInstance(RealmConfiguration.Builder()
.schemaVersion(SCHEMA_VERSION).name(errorDbName).build())
e.log()
deleteRealmFile(realm.configuration.realmDirectory)
}
}
|
stackoverflow
|
{
"language": "en",
"length": 236,
"provenance": "stackexchange_0000F.jsonl.gz:849616",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494846"
}
|
ba375f77f4381f8acd7d771431311fb886f560d7
|
Stackoverflow Stackexchange
Q: iOS 11 dropInteraction performDrop for files How can I use dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) to accept other type of files than images? Say for instnce that I drag a PDF or MP3 from the files app. How can I accept this file and get the data?
I thought I could use NSURL.self, but that only seems to work for URL's dragged from Safari och a textview.
A: Within dropInteraction you call session.loadObjects(ofClass:), which you probably already have, and have tried UIImage and NSURL.
ofClass needs to conform to NSItemProviderReading (Documentation). The default classes that conform to it are NSString, NSAttributedString, NSURL, UIColor, and UIImage. For anything else, I think you will need to make a custom class conforming to the protocol, using public.mp3 as the UTI. Your custom class will have a init(itemProviderData: Data, typeIdentifier: String) initializer that should give you a bag of bytes (itemProviderData) that is the MP3s data. From there, you should be able to write out your file as needed.
|
Q: iOS 11 dropInteraction performDrop for files How can I use dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) to accept other type of files than images? Say for instnce that I drag a PDF or MP3 from the files app. How can I accept this file and get the data?
I thought I could use NSURL.self, but that only seems to work for URL's dragged from Safari och a textview.
A: Within dropInteraction you call session.loadObjects(ofClass:), which you probably already have, and have tried UIImage and NSURL.
ofClass needs to conform to NSItemProviderReading (Documentation). The default classes that conform to it are NSString, NSAttributedString, NSURL, UIColor, and UIImage. For anything else, I think you will need to make a custom class conforming to the protocol, using public.mp3 as the UTI. Your custom class will have a init(itemProviderData: Data, typeIdentifier: String) initializer that should give you a bag of bytes (itemProviderData) that is the MP3s data. From there, you should be able to write out your file as needed.
A: An example for PDF (com.adobe.pdf UTI) implementing NSItemProviderReading could be something like this:
class PDFDocument: NSObject, NSItemProviderReading {
let data: Data?
required init(pdfData: Data, typeIdentifier: String) {
data = pdfData
}
static var readableTypeIdentifiersForItemProvider: [String] {
return [kUTTypePDF as String]
}
static func object(withItemProviderData data: Data, typeIdentifier: String) throws -> Self {
return self.init(pdfData: data, typeIdentifier: typeIdentifier)
}
}
Then in your delegate you need to handle this PDFDocument:
extension YourClass: UIDropInteractionDelegate {
func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
return session.canLoadObjects(ofClass: PDFDocument.self))
}
.
.
.
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
session.loadObjects(ofClass: PDFDocument.self) { [unowned self] pdfItems in
if let pdfs = pdfItems as? [PDFDocument], let pdf = pdfs.first {
// Whatever you want to do with the pdf
}
}
}
}
|
stackoverflow
|
{
"language": "en",
"length": 298,
"provenance": "stackexchange_0000F.jsonl.gz:849623",
"question_score": "12",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494871"
}
|
d9e36b90a3e24adc1a7e0f07a0a0bb82930db083
|
Stackoverflow Stackexchange
Q: Move ownership of a member from one struct to another? I have 2 structs:
struct MyVector {
storage: Vec<u32>,
}
struct MyVectorBuilder {
storage: Vec<u32>,
}
impl MyVectorBuilder {
fn new() -> MyVectorBuilder {
MyVectorBuilder { storage: Vec::new() }
}
fn build_my_vector(&mut self) -> MyVector {
// Doesn't compile: ^^^^ cannot move out of borrowed content
MyVector { storage: self.storage }
}
}
Is there a way to tell the compiler that MyVectorBuilder will not be used following a call to build_my_vector() so it will let me move the storage to MyVector?
A: Yes. Pass ownership of MyVectorBuilder into MakeMyVector
fn make_my_vector(self) -> MyVector {
MyVector { storage: self.storage }
}
|
Q: Move ownership of a member from one struct to another? I have 2 structs:
struct MyVector {
storage: Vec<u32>,
}
struct MyVectorBuilder {
storage: Vec<u32>,
}
impl MyVectorBuilder {
fn new() -> MyVectorBuilder {
MyVectorBuilder { storage: Vec::new() }
}
fn build_my_vector(&mut self) -> MyVector {
// Doesn't compile: ^^^^ cannot move out of borrowed content
MyVector { storage: self.storage }
}
}
Is there a way to tell the compiler that MyVectorBuilder will not be used following a call to build_my_vector() so it will let me move the storage to MyVector?
A: Yes. Pass ownership of MyVectorBuilder into MakeMyVector
fn make_my_vector(self) -> MyVector {
MyVector { storage: self.storage }
}
A:
Is there a way to tell the compiler that MyVectorBuilder will not be used followning a call to BuildMyVector() so it will let me move the storage to MyVector ?
Yes, taking MyVectorBuilder by value:
fn build_my_vector(self) -> MyVector {
MyVector { storage: self.storage }
}
In general, I recommend that the build step of a builder takes its argument by value for precisely this reason.
If building twice is necessary, the builder can implement Clone.
|
stackoverflow
|
{
"language": "en",
"length": 189,
"provenance": "stackexchange_0000F.jsonl.gz:849631",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494888"
}
|
8b7edd5623e652ac61f0b60fa89230fa0f760153
|
Stackoverflow Stackexchange
Q: Spring Data findTop10- Ten queries instead of one I have Spring Data method like this:
List<RegionBasics> findTop10ByRegionMappingsActiveTrue();
What I expect is that it will find top 10 records from db in one query but What I see in logs is (I didn't paste whole logs in order to keep this readable but this select query is invoke 10 times):
select regionmapp0_.id as id1_2_1_, regionmapp0_.is_active as is_activ2_2_1_, regionmapp0_.region_basic_id as region_b3_2_1_, regionbasi1_.id as id1_1_0_, regionbasi1_.hotel_count as hotel_co2_1_0_, regionbasi1_.name_long as name_lon3_1_0_, regionbasi1_.name as name4_1_0_, regionbasi1_.type as type5_1_0_ from region_mappings regionmapp0_ left outer join region_basics regionbasi1_ on regionmapp0_.region_basic_id=regionbasi1_.id where regionmapp0_.region_basic_id=?
How can I ensure that this method will hit db only once (instead of 10)?
My Model:
@Data
@NoArgsConstructor
@Entity
@Table(name = "region_basics")
public class RegionBasics {
@Id
Integer id;
@Column
String type;
@Column
String name;
@Column(name = "name_long")
String longName;
@Column(name = "hotel_count")
Integer hotelCount;
@OneToOne(mappedBy="regionBasics")
RegionMappings regionMappings;
}
A: I think you should join fetching the RegionMappings:
Like this: @Query("SELECT rb FROM RegionBasics r JOIN FETCH r.regionMappings rm WHERE rm.active=true")
With pageable parameter new PageRequest(0,10)
|
Q: Spring Data findTop10- Ten queries instead of one I have Spring Data method like this:
List<RegionBasics> findTop10ByRegionMappingsActiveTrue();
What I expect is that it will find top 10 records from db in one query but What I see in logs is (I didn't paste whole logs in order to keep this readable but this select query is invoke 10 times):
select regionmapp0_.id as id1_2_1_, regionmapp0_.is_active as is_activ2_2_1_, regionmapp0_.region_basic_id as region_b3_2_1_, regionbasi1_.id as id1_1_0_, regionbasi1_.hotel_count as hotel_co2_1_0_, regionbasi1_.name_long as name_lon3_1_0_, regionbasi1_.name as name4_1_0_, regionbasi1_.type as type5_1_0_ from region_mappings regionmapp0_ left outer join region_basics regionbasi1_ on regionmapp0_.region_basic_id=regionbasi1_.id where regionmapp0_.region_basic_id=?
How can I ensure that this method will hit db only once (instead of 10)?
My Model:
@Data
@NoArgsConstructor
@Entity
@Table(name = "region_basics")
public class RegionBasics {
@Id
Integer id;
@Column
String type;
@Column
String name;
@Column(name = "name_long")
String longName;
@Column(name = "hotel_count")
Integer hotelCount;
@OneToOne(mappedBy="regionBasics")
RegionMappings regionMappings;
}
A: I think you should join fetching the RegionMappings:
Like this: @Query("SELECT rb FROM RegionBasics r JOIN FETCH r.regionMappings rm WHERE rm.active=true")
With pageable parameter new PageRequest(0,10)
|
stackoverflow
|
{
"language": "en",
"length": 174,
"provenance": "stackexchange_0000F.jsonl.gz:849646",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44494933"
}
|
b3bcfe932773114960e6e7b40c1df1492af99a5c
|
Stackoverflow Stackexchange
Q: _TABLE_SUFFIX on multiple joins In BigQuery, standard SQL, how to use _TABLE_SUFFIX on several tables ? See example:
select *
from `table1.*` t1
left join `table2.*` t2 on t1.lel=t2.lel
where _TABLE_SUFFIX between '2017-01-01' and '2017-01-02' <--- this can't be used
Am I obliged to create a subquery of table2 with a table_suffix apply to it first ?
A: In your query _TABLE_SUFFIX is ambiguous, since BigQuery cannot tell whether it comes from t1 or t2. You can disambiguate it with explicit prefix t1. or t2., i.e.
select *
from `table1.*` t1
left join `table2.*` t2 on t1.lel=t2.lel
where t1._TABLE_SUFFIX between '2017-01-01' and '2017-01-02'
|
Q: _TABLE_SUFFIX on multiple joins In BigQuery, standard SQL, how to use _TABLE_SUFFIX on several tables ? See example:
select *
from `table1.*` t1
left join `table2.*` t2 on t1.lel=t2.lel
where _TABLE_SUFFIX between '2017-01-01' and '2017-01-02' <--- this can't be used
Am I obliged to create a subquery of table2 with a table_suffix apply to it first ?
A: In your query _TABLE_SUFFIX is ambiguous, since BigQuery cannot tell whether it comes from t1 or t2. You can disambiguate it with explicit prefix t1. or t2., i.e.
select *
from `table1.*` t1
left join `table2.*` t2 on t1.lel=t2.lel
where t1._TABLE_SUFFIX between '2017-01-01' and '2017-01-02'
A: also you can add another table_suffix condition for example ,
select *
from `table1.*` t1
left join `table2.*` t2 on t1.lel=t2.lel
where t1._TABLE_SUFFIX between '2017-01-01' and '2017-01-02'
and t2._TABLE_SUFFIX between '2017-01-01' and '2017-01-02'
the different between Mosha answer is that his query will scan all the tables in the left join (higher cost and lower performer) will in the example i sent it will scan only the tables that answer to the conditions in the table suffix,
the only issue with that approach is that bigquery run it like its inner join and not left , for example if you will add condition and t2.tel is null you will received no 0 results
|
stackoverflow
|
{
"language": "en",
"length": 218,
"provenance": "stackexchange_0000F.jsonl.gz:849664",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44495014"
}
|
05f30093524d97afe5bd9ba072a3616db56af773
|
Stackoverflow Stackexchange
Q: How to fix Method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift in Swift 4? I am updating my app from Swift 3 to Swift 4 and after migration, there are a few errors. One of them is Method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift in IQToolbar of IQKeyboardManager, how to fix this?
A: - You can also use Singleton solve this problem such as:
static let shared : AudioTools = {
$0.initialize()
return $0
}(AudioTools())
Your Objective-C method--->initialize
override class func initialize(){code here}
change:
func initialize(){code here}
Your method here:
func playSound(fileName:String?) {
code here
}
use in Swift3:
let audioPlayer = AudioTools.playMusic(fileName: fileName)
use in Swift4
let audioPlayer = AudioTools.shared.playMusic(fileName: fileName)
|
Q: How to fix Method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift in Swift 4? I am updating my app from Swift 3 to Swift 4 and after migration, there are a few errors. One of them is Method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift in IQToolbar of IQKeyboardManager, how to fix this?
A: - You can also use Singleton solve this problem such as:
static let shared : AudioTools = {
$0.initialize()
return $0
}(AudioTools())
Your Objective-C method--->initialize
override class func initialize(){code here}
change:
func initialize(){code here}
Your method here:
func playSound(fileName:String?) {
code here
}
use in Swift3:
let audioPlayer = AudioTools.playMusic(fileName: fileName)
use in Swift4
let audioPlayer = AudioTools.shared.playMusic(fileName: fileName)
|
stackoverflow
|
{
"language": "en",
"length": 124,
"provenance": "stackexchange_0000F.jsonl.gz:849679",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44495077"
}
|
bea1371db344887772349d94e8fc74166bb29f34
|
Stackoverflow Stackexchange
Q: Not a valid format string - info which language is wrong I use getString(R.string.xxxx, "Test", "Test2") in my code and get the the error "Format string xxxx is not a valid format string..."!
So far so good, but how can I see which language is wrong?
I have over 30 langauges and don't want to check each file by hand every time.
Is there any way to find the wrong language file/files?
A: Try this code:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
Resources r = getResources();
Configuration c = r.getConfiguration();
Locale[] loc = Locale.getAvailableLocales();
for (int i = 0; i < loc.length; i++) {
c.locale = loc[i];
Resources res = new Resources(getAssets(), metrics, c);
String s1 = res.getString(R.string.app_name);
Log.d("LOCALE",loc[i].getDisplayCountry()+" : "+ s1 );
}
In android studio:
Right-click the strings.xml file, and select Open Translations Editor.
More info in developer.android.com
|
Q: Not a valid format string - info which language is wrong I use getString(R.string.xxxx, "Test", "Test2") in my code and get the the error "Format string xxxx is not a valid format string..."!
So far so good, but how can I see which language is wrong?
I have over 30 langauges and don't want to check each file by hand every time.
Is there any way to find the wrong language file/files?
A: Try this code:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
Resources r = getResources();
Configuration c = r.getConfiguration();
Locale[] loc = Locale.getAvailableLocales();
for (int i = 0; i < loc.length; i++) {
c.locale = loc[i];
Resources res = new Resources(getAssets(), metrics, c);
String s1 = res.getString(R.string.app_name);
Log.d("LOCALE",loc[i].getDisplayCountry()+" : "+ s1 );
}
In android studio:
Right-click the strings.xml file, and select Open Translations Editor.
More info in developer.android.com
|
stackoverflow
|
{
"language": "en",
"length": 141,
"provenance": "stackexchange_0000F.jsonl.gz:849715",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44495183"
}
|
2d5fc1340f9f2037f0ae3334d7846a4355936471
|
Stackoverflow Stackexchange
Q: React-Slick Carousel - Disable keyboard arrows Can anyone help me how can i disable keyboard arrows, to be more clearly when i press the right or left arrow at keyboard i dont want to move forward on carousel slider.
The point is to disable the arrows on keyboards (not moving forward or backward).
Make keyboard: false
A: React Slick has props "accessibility" you need set it to "false" in your component.
Also slider has many ather props in doc https://react-slick.neostack.com/docs/api.
|
Q: React-Slick Carousel - Disable keyboard arrows Can anyone help me how can i disable keyboard arrows, to be more clearly when i press the right or left arrow at keyboard i dont want to move forward on carousel slider.
The point is to disable the arrows on keyboards (not moving forward or backward).
Make keyboard: false
A: React Slick has props "accessibility" you need set it to "false" in your component.
Also slider has many ather props in doc https://react-slick.neostack.com/docs/api.
|
stackoverflow
|
{
"language": "en",
"length": 81,
"provenance": "stackexchange_0000F.jsonl.gz:849728",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44495231"
}
|
6764bb16205214ad21bde155a31aa19bfa68095c
|
Stackoverflow Stackexchange
Q: unable to bintrayUpload HTTP 404 Subject was not found I'm facing this error for long time:
Execution failed for task ':lib-change-scene:bintrayUpload'.
Could not create package 'RajuSE/change-scene/change-scene': HTTP/1.1 404 Not Found [message:Subject 'R
ajuSE' was not found]
Sometimes this task even freezes on 98% and doesn't proceed.
Refer Issues I posted on github:
https://github.com/bintray/gradle-bintray-plugin/issues/189
https://github.com/bintray/gradle-bintray-plugin/issues/188
Update : I'm able upload library using uploading zip solution.. it is has been approved.. but definitely looking for gradle way solution.
A: Seems like your username on bintray is rajuse all non capital letters.
But you still put an orgName with the value RajuSE.
If you are trying to upload to your user context than remove the orgName.
In Bintray you can upload content to either an organization or a user.
Please make sure your bintray username configuration are same (case sensitive) as your actual username.
|
Q: unable to bintrayUpload HTTP 404 Subject was not found I'm facing this error for long time:
Execution failed for task ':lib-change-scene:bintrayUpload'.
Could not create package 'RajuSE/change-scene/change-scene': HTTP/1.1 404 Not Found [message:Subject 'R
ajuSE' was not found]
Sometimes this task even freezes on 98% and doesn't proceed.
Refer Issues I posted on github:
https://github.com/bintray/gradle-bintray-plugin/issues/189
https://github.com/bintray/gradle-bintray-plugin/issues/188
Update : I'm able upload library using uploading zip solution.. it is has been approved.. but definitely looking for gradle way solution.
A: Seems like your username on bintray is rajuse all non capital letters.
But you still put an orgName with the value RajuSE.
If you are trying to upload to your user context than remove the orgName.
In Bintray you can upload content to either an organization or a user.
Please make sure your bintray username configuration are same (case sensitive) as your actual username.
|
stackoverflow
|
{
"language": "en",
"length": 142,
"provenance": "stackexchange_0000F.jsonl.gz:849747",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44495288"
}
|
3c985b44f833b1b4d2cb19f24a22e072619c996b
|
Stackoverflow Stackexchange
Q: How can I generate both an aar and apk of my Android project I am developing an Android library in Android Studio.
I have also created a dummy android application project to import that library and test it. For that reason I have imported my android library as a Library into this android application. My problem is that when I generate the apk in the output folder I can only see the apk and there is no folder for the generated aar.
How can I generate my aar?
A: So i figured this out, it wasn't difficult but I'll just post the answer here just in case I save someone of time. When I selected build apk the aar isn't built in the outputs of the main project, however it's built in the outputs of the respective library.
|
Q: How can I generate both an aar and apk of my Android project I am developing an Android library in Android Studio.
I have also created a dummy android application project to import that library and test it. For that reason I have imported my android library as a Library into this android application. My problem is that when I generate the apk in the output folder I can only see the apk and there is no folder for the generated aar.
How can I generate my aar?
A: So i figured this out, it wasn't difficult but I'll just post the answer here just in case I save someone of time. When I selected build apk the aar isn't built in the outputs of the main project, however it's built in the outputs of the respective library.
|
stackoverflow
|
{
"language": "en",
"length": 139,
"provenance": "stackexchange_0000F.jsonl.gz:849771",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44495361"
}
|
abe0576b6fc1723d9c5b50c2dc2f57308e2906dd
|
Stackoverflow Stackexchange
Q: com.typesafe.config.ConfigException$Missing: No configuration setting found for key I am using typeSafe config to load the properties from application.properties present under src/main/resources into Scala code. While running the code from eclipse, the properties are getting loaded. But while running as a jar file,its throwing me an error.
com.typesafe.config.ConfigException$Missing: No configuration setting found for key
A: Thanks Wang for giving me a clue. Yes, the jar file contains the property file. But it was not able to find the file, as the property file was present in resouces folder. I got to know when I unzip the jar file. In code had provided the below.
val config=ConfigFactory.load("application.properties")
When i changed it to-
val config=ConfigFactory.load("resources/application.properties")
i am getting the properties. THANKS ALL.
|
Q: com.typesafe.config.ConfigException$Missing: No configuration setting found for key I am using typeSafe config to load the properties from application.properties present under src/main/resources into Scala code. While running the code from eclipse, the properties are getting loaded. But while running as a jar file,its throwing me an error.
com.typesafe.config.ConfigException$Missing: No configuration setting found for key
A: Thanks Wang for giving me a clue. Yes, the jar file contains the property file. But it was not able to find the file, as the property file was present in resouces folder. I got to know when I unzip the jar file. In code had provided the below.
val config=ConfigFactory.load("application.properties")
When i changed it to-
val config=ConfigFactory.load("resources/application.properties")
i am getting the properties. THANKS ALL.
|
stackoverflow
|
{
"language": "en",
"length": 120,
"provenance": "stackexchange_0000F.jsonl.gz:849795",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44495429"
}
|
33b90845df50ce53de7b541c17883591d48ed038
|
Stackoverflow Stackexchange
Q: RabbitMq Consumer on AWS Lambda From what I know, Lambdas are for listening to events and running a piece of code on response to those events.
The events need to be AWS services or HTTP endpoints.
If I have a RabbitMq service running on an EC2 server (Not using SQS), is it possible to have a consumer deployed on Lambda?
If possible, would this be the right thing to do?
Also, since lambdas are billed on compute time, I shouldn't be billed for when the queue is idle, right?
A: You can probably install this on the same server as the rabbitMQ, and make it trigger the lambdas. I haven't tried myself though
https://github.com/AirHelp/rabbit-amazon-forwarder
As far as I understand, lambdas are billed by the running time, and you pay based on amount of memory (per gigabyte/second). So making a lambda wait all the time will probably be pretty expensive and hard to manage since it will time out. If you already have a server with RabbitMQ, use that for consuming the queue and calling the lambdas.
|
Q: RabbitMq Consumer on AWS Lambda From what I know, Lambdas are for listening to events and running a piece of code on response to those events.
The events need to be AWS services or HTTP endpoints.
If I have a RabbitMq service running on an EC2 server (Not using SQS), is it possible to have a consumer deployed on Lambda?
If possible, would this be the right thing to do?
Also, since lambdas are billed on compute time, I shouldn't be billed for when the queue is idle, right?
A: You can probably install this on the same server as the rabbitMQ, and make it trigger the lambdas. I haven't tried myself though
https://github.com/AirHelp/rabbit-amazon-forwarder
As far as I understand, lambdas are billed by the running time, and you pay based on amount of memory (per gigabyte/second). So making a lambda wait all the time will probably be pretty expensive and hard to manage since it will time out. If you already have a server with RabbitMQ, use that for consuming the queue and calling the lambdas.
A: You can now configure Amazon MQ for RabbitMQ as an event source for AWS Lambda.
Check the AWS blog.
https://aws.amazon.com/blogs/compute/using-amazon-mq-for-rabbitmq-as-an-event-source-for-lambda/
|
stackoverflow
|
{
"language": "en",
"length": 198,
"provenance": "stackexchange_0000F.jsonl.gz:849845",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44495577"
}
|
2ee147e55f23cb8e5db62168ffaeced585572444
|
Stackoverflow Stackexchange
Q: Accessing functions within the closure, from imported modules I want to achieve the following setup:
// app.js
(function () {
const add = function() {
// add
}
const substract = function() {
// substract
}
require('./module1');
require('./module2');
})()
// module1.js
add();
substract();
The problem is that when the functions are called from within the module1.js, they are undefined (all this is bundled with webpack).
I know the solution of "exporting" and "importing" between the various modules/files. I am just wondering if I can I achieve this setup in order to avoid imports in the many modules that I use (imagine, for example, having to import them to 50 modules/files).
What is the proper way to achieve this setup (if possible)?
Thanx in advance.
A: Try this if you can:
// app.js
(function addSubst() {
const add = function() {
// add
}
const substract = function() {
// substract
}
require('./module1');
require('./module2');
})()
// module1.js
import {addSubst} from 'app';//app.js
add();
substract();
better explanation and for more languajes here
|
Q: Accessing functions within the closure, from imported modules I want to achieve the following setup:
// app.js
(function () {
const add = function() {
// add
}
const substract = function() {
// substract
}
require('./module1');
require('./module2');
})()
// module1.js
add();
substract();
The problem is that when the functions are called from within the module1.js, they are undefined (all this is bundled with webpack).
I know the solution of "exporting" and "importing" between the various modules/files. I am just wondering if I can I achieve this setup in order to avoid imports in the many modules that I use (imagine, for example, having to import them to 50 modules/files).
What is the proper way to achieve this setup (if possible)?
Thanx in advance.
A: Try this if you can:
// app.js
(function addSubst() {
const add = function() {
// add
}
const substract = function() {
// substract
}
require('./module1');
require('./module2');
})()
// module1.js
import {addSubst} from 'app';//app.js
add();
substract();
better explanation and for more languajes here
A: The scope of the IIFE function ends after it call it self and the inside add ,substract , they will have not refrence after the IIFE you should try to export both varibles from this file . If you try to apply the clousure
function currentModule() {
const add = function() {
// add
}
const substract = function() {
// substract
}
return { add : add, substract : substract}
})
var instanceHere = currentModule();
instanceHere.Add();
A: The way I managed to achieve this, was to create a global object (namespace) for my app.
(function() {
APP = window.APP || {};
APP.add = function() {
console.log('Adding...');
}
APP.substract = function() {
console.log('Substracting...');
}
// Import the modules.
require('./module1');
require('./module2');
})();
// module1.js
APP.add(); // Outputs "Adding..."
APP.substract(); // Outputs "Substracting..."
|
stackoverflow
|
{
"language": "en",
"length": 302,
"provenance": "stackexchange_0000F.jsonl.gz:849855",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44495614"
}
|
2a488125f37039662fac60a9a66868c5e6427c3c
|
Stackoverflow Stackexchange
Q: NDK use of undeclared identifier memcpy My Android Studio got updated last friday and since then will refuse to compile my Android/NDK project, returning several errors about "use of undeclared identifier 'memcpy'" and "use of undeclared identifier 'memcmp'".
I've tried to do a clean install of Android Studio and all the Android SDK without any success. Several of my colleagues also had the update but can still compile.
Does anyone have any idea of what could be the problem ?
A: I have the same problem too. But under the Studio's CodeInsight
I just add the following code, the problem can be solved.
#include <string.h>
|
Q: NDK use of undeclared identifier memcpy My Android Studio got updated last friday and since then will refuse to compile my Android/NDK project, returning several errors about "use of undeclared identifier 'memcpy'" and "use of undeclared identifier 'memcmp'".
I've tried to do a clean install of Android Studio and all the Android SDK without any success. Several of my colleagues also had the update but can still compile.
Does anyone have any idea of what could be the problem ?
A: I have the same problem too. But under the Studio's CodeInsight
I just add the following code, the problem can be solved.
#include <string.h>
|
stackoverflow
|
{
"language": "en",
"length": 106,
"provenance": "stackexchange_0000F.jsonl.gz:849874",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44495668"
}
|
16e01ac30b6044a82ea25f75ecf274ef2a713df6
|
Stackoverflow Stackexchange
Q: multiline in textview not working with sppannable text I am using TextView to display text. I need to display max 3 line of text. To accomplish this , i have used maxLines property.
<TextView
android:id="@+id/textFeedText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="3"
android:textColor="@color/colorFeedDate"
android:textSize="@dimen/d13sp"/>
Now i need to set sppannable text in textview. Following is my code to set clickable span.
SpannableString spannableString = new SpannableString(requiredString);
ClickableSpan clickSpan = new ClickableSpan() {
@Override
public void onClick(View view) {
}
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(ContextCompat.getColor(mContext, R.color.colorAppBlue));
ds.setUnderlineText(false);
}
};
spannableString.setSpan(clickSpan, indexOfStart, indexOfEnd - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.append(spannableString);
textView.setMovementMethod(LinkMovementMethod.getInstance());
It display okay. Now when i tap on textview then sometimes multiline property not seems working. Textview text scrolls vertically. And display following view.
Anyone has faced such issue?
Thanks.
|
Q: multiline in textview not working with sppannable text I am using TextView to display text. I need to display max 3 line of text. To accomplish this , i have used maxLines property.
<TextView
android:id="@+id/textFeedText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="3"
android:textColor="@color/colorFeedDate"
android:textSize="@dimen/d13sp"/>
Now i need to set sppannable text in textview. Following is my code to set clickable span.
SpannableString spannableString = new SpannableString(requiredString);
ClickableSpan clickSpan = new ClickableSpan() {
@Override
public void onClick(View view) {
}
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(ContextCompat.getColor(mContext, R.color.colorAppBlue));
ds.setUnderlineText(false);
}
};
spannableString.setSpan(clickSpan, indexOfStart, indexOfEnd - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.append(spannableString);
textView.setMovementMethod(LinkMovementMethod.getInstance());
It display okay. Now when i tap on textview then sometimes multiline property not seems working. Textview text scrolls vertically. And display following view.
Anyone has faced such issue?
Thanks.
|
stackoverflow
|
{
"language": "en",
"length": 126,
"provenance": "stackexchange_0000F.jsonl.gz:849916",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44495826"
}
|
dfed2c38a182483d9737a5e5e1dff8f5ce99f367
|
Stackoverflow Stackexchange
Q: How to save custom objects that implements Codable It's now easier with Swift 4 to encode / decode to and from JSON or Properties list.
But I can't find how to encode to Data using Codable, without using Objective-C methods initWithCoder and encodeWithCoder.
Considering this simple class:
struct Question: Codable {
var title: String
var answer: Int
var question: Int
}
How can I encode it to Data using CodingKeys and not initWithCoder and encodeWithCoder?
EDIT:
I also need to be able to deserialize objects previously saved in userdefaults using NSKeyedArchiver.
A: Swift 5: a great simple extension for UserDefaults:
extension UserDefaults {
func save<T: Codable>(_ object: T, forKey key: String) {
let encoder = JSONEncoder()
if let encodedObject = try? encoder.encode(object) {
UserDefaults.standard.set(encodedObject, forKey: key)
UserDefaults.standard.synchronize()
}
}
func getObject<T: Codable>(forKey key: String) -> T? {
if let object = UserDefaults.standard.object(forKey: key) as? Data {
let decoder = JSONDecoder()
if let decodedObject = try? decoder.decode(T.self, from: object) {
return decodedObject
}
}
return nil
}
}
Usage
save
UserDefaults.standard.save(currentUser, forKey: "currentUser")
get
let user: User? = UserDefaults.standard.getObject(forKey: "currentUser")
|
Q: How to save custom objects that implements Codable It's now easier with Swift 4 to encode / decode to and from JSON or Properties list.
But I can't find how to encode to Data using Codable, without using Objective-C methods initWithCoder and encodeWithCoder.
Considering this simple class:
struct Question: Codable {
var title: String
var answer: Int
var question: Int
}
How can I encode it to Data using CodingKeys and not initWithCoder and encodeWithCoder?
EDIT:
I also need to be able to deserialize objects previously saved in userdefaults using NSKeyedArchiver.
A: Swift 5: a great simple extension for UserDefaults:
extension UserDefaults {
func save<T: Codable>(_ object: T, forKey key: String) {
let encoder = JSONEncoder()
if let encodedObject = try? encoder.encode(object) {
UserDefaults.standard.set(encodedObject, forKey: key)
UserDefaults.standard.synchronize()
}
}
func getObject<T: Codable>(forKey key: String) -> T? {
if let object = UserDefaults.standard.object(forKey: key) as? Data {
let decoder = JSONDecoder()
if let decodedObject = try? decoder.decode(T.self, from: object) {
return decodedObject
}
}
return nil
}
}
Usage
save
UserDefaults.standard.save(currentUser, forKey: "currentUser")
get
let user: User? = UserDefaults.standard.getObject(forKey: "currentUser")
A: Well, you no longer need NSKeyedArchiver.
Try this:
let questionObj = Question(title: "WWDC, 2017", answer: 1,question:1)
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(questionObj) {
UserDefaults.standard.set(encoded, forKey: "K_Question")
}
let decoder = JSONDecoder()
if let questionData = UserDefaults.standard.data(forKey: "K_Question"),
let question = try? decoder.decode(Question.self, from: questionData) {
print(question.title)
print(question.answer)
print(question.question)
}
A: Well it can be achieved via JSONEncoder and JSONDecoder.
struct Question: Codable {
var title: String
var answer: Int
var question: Int
}
let questionObj = Question(title: "Swift", answer: "Open Source",question:1)
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(questionObj) {
if let json = String(data: encoded, encoding: .utf8) {
print(json)
}
let decoder = JSONDecoder()
if let decoded = try? decoder.decode(Question.self, from: encoded) {
print(decoded)
}
}
A: struct Question: Codable {
var title: String
var answer: Int
var question: Int
}
class UserDefaults_Question {
static let key = "myapp.trick.question"
static var value: UserDefaults_Question? {
get {
guard let data = UserDefaults.standard.data(forKey: key) else {
print("no model for key: \(key)")
return nil
}
guard let model = try? JSONDecoder().decode(UserDefaults_Question.self, from: data) else {
print("failed to decode model for key: \(key)")
return nil
}
print("did load model for key: \(key)")
return model
}
set {
guard let value = newValue, let data: Data = try? JSONEncoder().encode(value) else {
print("removing model for key: \(key)")
UserDefaults.standard.removeObject(forKey: key)
return
}
print("inserting model for key: \(key)")
UserDefaults.standard.set(data, forKey: key)
}
}
}
UserDefaults_Question.value = Question(title: "Next President", answer: 666, question: -1)
|
stackoverflow
|
{
"language": "en",
"length": 423,
"provenance": "stackexchange_0000F.jsonl.gz:849923",
"question_score": "11",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44495842"
}
|
0af89d439a56967e6d910631c922efcc592b8a78
|
Stackoverflow Stackexchange
Q: IE scrollbar bug IE bug, how to remove scrollbar in this dropdown, I don't need this? In chrome works fine, no scrollbar.
My code:
<div class="form-group">
<label class=""> </label>
<select>
<option value=""></option>
<option value="Used">one</option>
<option value="UnderRepair">two</option>
<option value="WriteOff">three</option>
<option value="Destroyed">four</option>
</select>
</div>
A: If you want to hide scroll this might work
.form-group select{
-ms-overflow-style: none;
overflow: auto;
}
|
Q: IE scrollbar bug IE bug, how to remove scrollbar in this dropdown, I don't need this? In chrome works fine, no scrollbar.
My code:
<div class="form-group">
<label class=""> </label>
<select>
<option value=""></option>
<option value="Used">one</option>
<option value="UnderRepair">two</option>
<option value="WriteOff">three</option>
<option value="Destroyed">four</option>
</select>
</div>
A: If you want to hide scroll this might work
.form-group select{
-ms-overflow-style: none;
overflow: auto;
}
|
stackoverflow
|
{
"language": "en",
"length": 60,
"provenance": "stackexchange_0000F.jsonl.gz:849943",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44495904"
}
|
f8b5128038ea76f1cd76f5e814579503dced459c
|
Stackoverflow Stackexchange
Q: Java.exe error in Visual Studio 2015 I have my Xamarin Android project in Visual Studio 2015 i'm getting this error (java.exe" exited with code 2) when i add parameters in any XML (color,layout etc). I have found some solution increase heap size changing Heap Size 1G to 2G found no difference.
Anyone please help me . Thank you in advance.
|
Q: Java.exe error in Visual Studio 2015 I have my Xamarin Android project in Visual Studio 2015 i'm getting this error (java.exe" exited with code 2) when i add parameters in any XML (color,layout etc). I have found some solution increase heap size changing Heap Size 1G to 2G found no difference.
Anyone please help me . Thank you in advance.
|
stackoverflow
|
{
"language": "en",
"length": 61,
"provenance": "stackexchange_0000F.jsonl.gz:849947",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44495924"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.