text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: What does tf.nn.embedding_lookup function do? tf.nn.embedding_lookup(params, ids, partition_strategy='mod', name=None)
I cannot understand the duty of this function. Is it like a lookup table? Which means to return the parameters corresponding to each id (in ids)?
For instance, in the skip-gram model if we use tf.nn.embedding_lookup(embeddings, train_inputs), then for each train_input it finds the correspond embedding?
A: When the params tensor is in high dimensions, the ids only refers to top dimension. Maybe it's obvious to most of people but I have to run the following code to understand that:
embeddings = tf.constant([[[1,1],[2,2],[3,3],[4,4]],[[11,11],[12,12],[13,13],[14,14]],
[[21,21],[22,22],[23,23],[24,24]]])
ids=tf.constant([0,2,1])
embed = tf.nn.embedding_lookup(embeddings, ids, partition_strategy='div')
with tf.Session() as session:
result = session.run(embed)
print (result)
Just trying the 'div' strategy and for one tensor, it makes no difference.
Here is the output:
[[[ 1 1]
[ 2 2]
[ 3 3]
[ 4 4]]
[[21 21]
[22 22]
[23 23]
[24 24]]
[[11 11]
[12 12]
[13 13]
[14 14]]]
A: Yes, the purpose of tf.nn.embedding_lookup() function is to perform a lookup in the embedding matrix and return the embeddings (or in simple terms the vector representation) of words.
A simple embedding matrix (of shape: vocabulary_size x embedding_dimension) would look like below. (i.e. each word will be represented by a vector of numbers; hence the name word2vec)
Embedding Matrix
the 0.418 0.24968 -0.41242 0.1217 0.34527 -0.044457 -0.49688 -0.17862
like 0.36808 0.20834 -0.22319 0.046283 0.20098 0.27515 -0.77127 -0.76804
between 0.7503 0.71623 -0.27033 0.20059 -0.17008 0.68568 -0.061672 -0.054638
did 0.042523 -0.21172 0.044739 -0.19248 0.26224 0.0043991 -0.88195 0.55184
just 0.17698 0.065221 0.28548 -0.4243 0.7499 -0.14892 -0.66786 0.11788
national -1.1105 0.94945 -0.17078 0.93037 -0.2477 -0.70633 -0.8649 -0.56118
day 0.11626 0.53897 -0.39514 -0.26027 0.57706 -0.79198 -0.88374 0.30119
country -0.13531 0.15485 -0.07309 0.034013 -0.054457 -0.20541 -0.60086 -0.22407
under 0.13721 -0.295 -0.05916 -0.59235 0.02301 0.21884 -0.34254 -0.70213
such 0.61012 0.33512 -0.53499 0.36139 -0.39866 0.70627 -0.18699 -0.77246
second -0.29809 0.28069 0.087102 0.54455 0.70003 0.44778 -0.72565 0.62309
I split the above embedding matrix and loaded only the words in vocab which will be our vocabulary and the corresponding vectors in emb array.
vocab = ['the','like','between','did','just','national','day','country','under','such','second']
emb = np.array([[0.418, 0.24968, -0.41242, 0.1217, 0.34527, -0.044457, -0.49688, -0.17862],
[0.36808, 0.20834, -0.22319, 0.046283, 0.20098, 0.27515, -0.77127, -0.76804],
[0.7503, 0.71623, -0.27033, 0.20059, -0.17008, 0.68568, -0.061672, -0.054638],
[0.042523, -0.21172, 0.044739, -0.19248, 0.26224, 0.0043991, -0.88195, 0.55184],
[0.17698, 0.065221, 0.28548, -0.4243, 0.7499, -0.14892, -0.66786, 0.11788],
[-1.1105, 0.94945, -0.17078, 0.93037, -0.2477, -0.70633, -0.8649, -0.56118],
[0.11626, 0.53897, -0.39514, -0.26027, 0.57706, -0.79198, -0.88374, 0.30119],
[-0.13531, 0.15485, -0.07309, 0.034013, -0.054457, -0.20541, -0.60086, -0.22407],
[ 0.13721, -0.295, -0.05916, -0.59235, 0.02301, 0.21884, -0.34254, -0.70213],
[ 0.61012, 0.33512, -0.53499, 0.36139, -0.39866, 0.70627, -0.18699, -0.77246 ],
[ -0.29809, 0.28069, 0.087102, 0.54455, 0.70003, 0.44778, -0.72565, 0.62309 ]])
emb.shape
# (11, 8)
Embedding Lookup in TensorFlow
Now we will see how can we perform embedding lookup for some arbitrary input sentence.
In [54]: from collections import OrderedDict
# embedding as TF tensor (for now constant; could be tf.Variable() during training)
In [55]: tf_embedding = tf.constant(emb, dtype=tf.float32)
# input for which we need the embedding
In [56]: input_str = "like the country"
# build index based on our `vocabulary`
In [57]: word_to_idx = OrderedDict({w:vocab.index(w) for w in input_str.split() if w in vocab})
# lookup in embedding matrix & return the vectors for the input words
In [58]: tf.nn.embedding_lookup(tf_embedding, list(word_to_idx.values())).eval()
Out[58]:
array([[ 0.36807999, 0.20834 , -0.22318999, 0.046283 , 0.20097999,
0.27515 , -0.77126998, -0.76804 ],
[ 0.41800001, 0.24968 , -0.41242 , 0.1217 , 0.34527001,
-0.044457 , -0.49687999, -0.17862 ],
[-0.13530999, 0.15485001, -0.07309 , 0.034013 , -0.054457 ,
-0.20541 , -0.60086 , -0.22407 ]], dtype=float32)
Observe how we got the embeddings from our original embedding matrix (with words) using the indices of words in our vocabulary.
Usually, such an embedding lookup is performed by the first layer (called Embedding layer) which then passes these embeddings to RNN/LSTM/GRU layers for further processing.
Side Note: Usually the vocabulary will also have a special unk token. So, if a token from our input sentence is not present in our vocabulary, then the index corresponding to unk will be looked up in the embedding matrix.
P.S. Note that embedding_dimension is a hyperparameter that one has to tune for their application but popular models like Word2Vec and GloVe uses 300 dimension vector for representing each word.
Bonus Reading word2vec skip-gram model
A: Another way to look at it is , assume that you flatten out the tensors to one dimensional array, and then you are performing a lookup
(eg) Tensor0=[1,2,3], Tensor1=[4,5,6], Tensor2=[7,8,9]
The flattened out tensor will be as follows
[1,4,7,2,5,8,3,6,9]
Now when you do a lookup of [0,3,4,1,7] it will yeild [1,2,5,4,6]
(i,e) if lookup value is 7 for example , and we have 3 tensors (or a tensor with 3 rows) then,
7 / 3 : (Reminder is 1, Quotient is 2) So 2nd element of Tensor1 will be shown, which is 6
A: Since I was also intrigued by this function, I'll give my two cents.
The way I see it in the 2D case is just as a matrix multiplication (it's easy to generalize to other dimensions).
Consider a vocabulary with N symbols.
Then, you can represent a symbol x as a vector of dimensions Nx1, one-hot-encoded.
But you want a representation of this symbol not as a vector of Nx1, but as one with dimensions Mx1, called y.
So, to transform x into y, you can use and embedding matrix E, with dimensions MxN:
y = E x.
This is essentially what tf.nn.embedding_lookup(params, ids, ...) is doing, with the nuance that ids are just one number that represents the position of the 1 in the one-hot-encoded vector x.
A: Yes, this function is hard to understand, until you get the point.
In its simplest form, it is similar to tf.gather. It returns the elements of params according to the indexes specified by ids.
For example (assuming you are inside tf.InteractiveSession())
params = tf.constant([10,20,30,40])
ids = tf.constant([0,1,2,3])
print tf.nn.embedding_lookup(params,ids).eval()
would return [10 20 30 40], because the first element (index 0) of params is 10, the second element of params (index 1) is 20, etc.
Similarly,
params = tf.constant([10,20,30,40])
ids = tf.constant([1,1,3])
print tf.nn.embedding_lookup(params,ids).eval()
would return [20 20 40].
But embedding_lookup is more than that. The params argument can be a list of tensors, rather than a single tensor.
params1 = tf.constant([1,2])
params2 = tf.constant([10,20])
ids = tf.constant([2,0,2,1,2,3])
result = tf.nn.embedding_lookup([params1, params2], ids)
In such a case, the indexes, specified in ids, correspond to elements of tensors according to a partition strategy, where the default partition strategy is 'mod'.
In the 'mod' strategy, index 0 corresponds to the first element of the first tensor in the list. Index 1 corresponds to the first element of the second tensor. Index 2 corresponds to the first element of the third tensor, and so on. Simply index i corresponds to the first element of the (i+1)th tensor , for all the indexes 0..(n-1), assuming params is a list of n tensors.
Now, index n cannot correspond to tensor n+1, because the list params contains only n tensors. So index n corresponds to the second element of the first tensor. Similarly, index n+1 corresponds to the second element of the second tensor, etc.
So, in the code
params1 = tf.constant([1,2])
params2 = tf.constant([10,20])
ids = tf.constant([2,0,2,1,2,3])
result = tf.nn.embedding_lookup([params1, params2], ids)
index 0 corresponds to the first element of the first tensor: 1
index 1 corresponds to the first element of the second tensor: 10
index 2 corresponds to the second element of the first tensor: 2
index 3 corresponds to the second element of the second tensor: 20
Thus, the result would be:
[ 2 1 2 10 2 20]
A: Here's an image depicting the process of embedding lookup.
Concisely, it gets the corresponding rows of a embedding layer, specified by a list of IDs and provide that as a tensor. It is achieved through the following process.
*
*Define a placeholder lookup_ids = tf.placeholder([10])
*Define a embedding layer embeddings = tf.Variable([100,10],...)
*Define the tensorflow operation embed_lookup = tf.embedding_lookup(embeddings, lookup_ids)
*Get the results by running lookup = session.run(embed_lookup, feed_dict={lookup_ids:[95,4,14]})
A: embedding_lookup function retrieves rows of the params tensor. The behavior is similar to using indexing with arrays in numpy. E.g.
matrix = np.random.random([1024, 64]) # 64-dimensional embeddings
ids = np.array([0, 5, 17, 33])
print matrix[ids] # prints a matrix of shape [4, 64]
params argument can be also a list of tensors in which case the ids will be distributed among the tensors. For example, given a list of 3 tensors [2, 64], the default behavior is that they will represent ids: [0, 3], [1, 4], [2, 5].
partition_strategy controls the way how the ids are distributed among the list. The partitioning is useful for larger scale problems when the matrix might be too large to keep in one piece.
A: Adding to Asher Stern's answer,
params is
interpreted as a partitioning of a large embedding tensor. It can be a single tensor representing the complete embedding tensor,
or a list of X tensors all of same shape except for the first dimension,
representing sharded embedding tensors.
The function tf.nn.embedding_lookup is written considering the fact that embedding (params) will be large. Therefore we need partition_strategy.
A: The existing explanations are not enough.
The main purpose of this function is to efficiently retrieve the vectors for each word in a given sequence of word indices. Suppose we have the following matrix of embeddings:
embds = np.array([[0.2, 0.32,0.9],
[0.8, 0.62,0.19],
[0.0, -0.22,-1.9],
[1.2, 2.32,6.0],
[0.11, 0.10,5.9]])
Let's say we have the following sequences of word indices:
data=[[0,1],
[3,4]]
Now to get the corresponding embedding for each word in our data:
tf.nn.embedding_lookup(
embds, data
)
out:
array([[[0.2 , 0.32, 0.9 ],
[0.8 , 0.62, 0.19]],
[[1.2 , 2.32, 6. ],
[0.11, 0.1 , 5.9 ]]])>
Note If embds are not an array or tensor, the output will not be like this (I won't go into details). For example, if embds were a list, the output would be:
array([[0.2 , 0.32],
[0.8 , 0.62]], dtype=float32)>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34870614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "171"
}
|
Q: RUSAGE_SELF returns memory usage in bytes? I am still not very clear about the unit of RUSAGE_SELF after going through the documentation of Python resource.
What actually RUSAGE_SELF returns? Memory usage of the whole program in bytes?
resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
What exactly is the unit?
A: Sometimes CPython documentation needs to be used in conjunction with the C documentation, since CPython builds on C. In this case, you might find what you need in http://linux.die.net/man/2/getrusage - or perhaps the getrusage doc for some other *ix variant.
HTH
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21357240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: task scheduler not working for python win32 I am running the following Python code from jupyter and powershell and it is running flawlessly.
When I put this in window scheduler, it doesn't run. It doesn't show any error either. Could you please help solve the problem? Are there better options to schedule my Python code in window?
I am running python 3.10.
My code was running before:
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'dsrigyan@yahoo.com'
mail.Subject = 'data'
# mail.Body = 'data'
mail.HTMLBody = '''<p style="font-family:Corbel">
Hi Deepa,<br/>
Please find the data for yesterday.<br/>
Let me know if you has any questions.
</p>
<br/><br/><br/><br/>
<p style="font-family:Corbel">
<b>Deepankar Srigyan<br/>
BI & Analytics Manager
</p>
'''
attachment = attachment_file
mail.Attachments.Add(attachment)
mail.Send()
A: See creating a bat file for python script to understand how to launch your script with a .bat file, then launch that via windows scheduler rather than launching the python script directly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73208815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CSS Ordering Convention for which tags to specify first I typically place the rules in my CSS in the same order as they are in the HTML. But what about global rules like how I format my input,textarea,p,tr,th and stuff like that? Is there a convention on which order the rules should go in?
Obviously there are situations when the rules have to be in a certain order to work.
A: I just put "global" properties of CSS in their own stylesheet all together. So for instance: put in tr, td, input, table, etc in their own stylesheet and the rest of custom .classes and #divs in their own.
This simplifies it the best and keeps it organized.
A: Global CSS rules can go on a file (i.e. global-style.css) - these will apply to all pages.
Specific CSS rules can go a separate file (i.e. login-style.css) - on this second file, you can override the default look-feel of the global CSS if desired.
You would only include the second file in the HTML files you need the different look-feel (from the global one)
A: I use one line per rule notation now, try to keep it organized and easy to read. It minimizes scrolling and it is easier to sort the rules that way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4879344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Chrome not animating until css are loaded In my head I include very small css file for loading animation. I am downloading large Angular2 application, and I want to display loading.
What I experience is that animation does not start until all css are loaded from server.
<link rel="stylesheet" href="~/dist/load.css" />
<link rel="stylesheet" href="~/dist/vendor.css" />
I tried to load vendor.css with async, defer, async defer. Tried to place it before </body> tag. I even try to replace animation with gif. Same thing, gif is displayed when vendor.css is loaded.
In network tab in Developer tools I choose Slow 3G. The moment that vendor.css file is loaded animation starts.
If I remove vendor.css from html animation starts immediately.
How can I start animation before other css file is loaded?
A: I found solution in placing this code before </body> tag:
<script type="text/javascript">
const head = document.head, link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = "/dist/vendor.css";
head.appendChild(link);
</script>
But it does not explain Chrome (possible other browsers too) behaviour I described in question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47606673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Best way to update a list of structs Let's say that I have a list of structs, with an id as one of its keys:
users = [
%User{id: 1, attempts: 5},
%User{id: 2, attempts: 12},
%User{id: 3, attempts: 2}
]
What would the best way (the most elixir way) to update the number of attempts to 99 of the user with id == 2 to get a new users list:
updated_users = [
%User{id: 1, attempts: 5},
%User{id: 2, attempts: 99},
%User{id: 3, attempts: 2}
]
Thanks for helping!
A: Enum.map(users, fn
%User{id: 2} = user -> %User{user | attempts: 99}
user -> user
end)
You can encapsulate it into some module and give it nice name :)
A: Arguably, most elixirish approach would be to use Access behaviour and Kernel.put_in/3:
put_in users,
[Access.filter(&match?(%User{id: 2}, &1)),
Access.key(:attempts)],
99
#⇒ [
# %User{attempts: 5, id: 1},
# %User{attempts: 99, id: 2},
# %User{attempts: 2, id: 3}
#]
This might be easily extended to update multiple elements by changing the filter function.
A: If you are doing many updates, it's probably best to build a map, so that you don't have to iterate the list for each update.
[
%User{attempts: 5, id: 1},
%User{attempts: 12, id: 2},
%User{attempts: 2, id: 3}
]
|> Map.new(fn user -> {user.id, user} end)
|> Map.update!(2, &%User{&1 | attempts: 99})
|> Map.values()
You can do as many Map.update!/3 calls as you need, to update different ids.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58475762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Background image not displaying in JLabel/JFrame in Java game I am making a java game and at it's heart, it consists of a JFrame that holds a a JLabel that holds the background image. Early in the project this was being displayed. However, after I implemented a Game render method that put healthbars and a character on screen, the background image no longer displays. Here is the Game's render() and main() methods.
public class Game extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
public static final int WIDTH = 1200, HEIGHT = 600, SCALE = 1;
public static boolean running = false;
public Thread gameThread;
private BufferedImage playerSpriteSheet;
private ImageManager im;
private static Player player;
private static HealthBar healthBars;
public void init(){
ImageLoader loader = new ImageLoader();
playerSpriteSheet = loader.load("/spriteSheet.png");
SpriteSheet pss = new SpriteSheet(playerSpriteSheet);
im = new ImageManager(pss);
player = new Player(0, 0, im);
healthBars = new HealthBar(200, 200);
this.addKeyListener(new KeyManager());
}
public synchronized void start() {
if(running)return;
running = true;
gameThread = new Thread(this);
gameThread.start();
}
public synchronized void stop() {
if(!running)return;
running = false;
try {
gameThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
init();
long lastTime = System.nanoTime();
final double amountOfTicks = 60D;
double ns = 1_000_000_000/amountOfTicks;
double delta = 0;
long now = System.nanoTime();
while(running)
{
delta += (now - lastTime)/ns;
lastTime = now;
if(delta >= 1)
{
tick();
delta--;
}
render();
}
stop();
}
public void tick() {
player.tick();
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null)
{
createBufferStrategy(3); //Use 5 at most
return;
}
Graphics g = bs.getDrawGraphics();
//RENDER HERE
player.render(g);
healthBars.render(g);
//END RENDER
g.dispose();
bs.show();
}
public static void main(String[] args)
{
JLabel backgroundImage;
JLabel controlKeyPanel;
JLabel statusLabel;
Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
JFrame frame = new JFrame("Java Game");
frame.setResizable(false);
frame.setSize(WIDTH * SCALE, HEIGHT * SCALE);
frame.setLayout(new BorderLayout());
backgroundImage = new JLabel(new ImageIcon("/background.png"));
String htmlButtonGuide = "<html>← - Move Left<br>→ - Move Right<br>A - Attack<br>S - Fire Gun<br>P - Position<br>esc - Exit</html>";
controlKeyPanel = new JLabel(htmlButtonGuide);
statusLabel = new JLabel("Game Status");
frame.add(backgroundImage, BorderLayout.CENTER); //This should be displaying the background image
frame.add(controlKeyPanel, BorderLayout.EAST);
frame.add(statusLabel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(game);
frame.setVisible(true);
game.start();
}
public static Player getPlayer() {
return player;
}
}
Here is the catch, and where I think part of the issue is visible. Inside the render() method there are these 2 lines:
player.render(g);
healthBars.render(g);
If I put player.render(g) first, then both the player and health bars appear on the screen. However, if I put healthBars.render(g) before player.render(g), then the player doesn't appear. This really confuses me, because I would expect the one that renders second causes the first one to be hidden behind, but the opposite happens. Could anyone point me in the right direction?
A: *
*BufferStrategy doesn't play well with Swing, as you've taken control of the painting process
*Canvas can't be transparent, so it will hide anything beneath it...
*When you use frame.add(game) you are replaceing what ever use to be at BorderLayout.CENTER
Instead of mixing lightweight (Swing) and heavy weight (AWT) components, paint the background image as part of your render process
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null)
{
createBufferStrategy(3); //Use 5 at most
return;
}
Graphics g = bs.getDrawGraphics();
//RENDER HERE
// Paint background here...
player.render(g);
healthBars.render(g);
//END RENDER
g.dispose();
bs.show();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25635204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android UI issue after update the ConstraintLayout to 1.1.0 After updating the ConstraintLayout to 1.1.0 the layout is showing white background only.its working fine in constraint-layout:1.0.2'.Please check my XML.In constraint-layout:1.0.2' it show the result. in 1.1.0 is showing only the outline card view only.plese refer my XML for more details.I want to update my ConstraintLayout
Please check image
-->
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mCardviewPropertytype"
android:layout_width="160dp"
tools:background="@color/gray_black"
android:layout_height="180dp"
android:layout_margin="8dp"
app:cardCornerRadius="8dp"
app:cardElevation="2dp">
<android.support.constraint.ConstraintLayout
android:layout_width="160dp"
android:layout_height="180dp"
android:layout_gravity="center"
android:layout_margin="8dp">
<android.support.constraint.ConstraintLayout
android:id="@+id/ImgPropertySelect"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="@drawable/half_circle"
app:layout_constraintRight_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
tools:visibility="visible"
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_centerInParent="true"
app:srcCompat="@drawable/ic_done_white_" />
</android.support.constraint.ConstraintLayout>
<!-- <ImageView
android:id="@+id/ImgPropertySelect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/selection_curve"
app:layout_constraintRight_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />-->
<android.support.constraint.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5" />
<ImageView
tools:visibility="visible"
android:id="@+id/imageViewPropertyType"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="@drawable/residential_villa_img"
android:layout_marginLeft="16dp"
app:layout_constraintBottom_toTopOf="@+id/guideline"
app:layout_constraintLeft_toRightOf="parent"
/>
<TextView
tools:text="@string/nearResidentialArea"
android:id="@+id/textViewTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:text="TextView"
android:textColor="@color/gray_black"
android:textSize="20dp"
app:layout_constraintLeft_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/guideline" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
A: The question is why the layout worked under 1.0.2 at all. What you see under 1.1.0 is how the layout is really defined. There are a couple of constraints that moved the images and text out of the layout and produced the blank area that you see. I made the corrections to the following XML and all looks OK. (I changed the colors and drawables used since I didn't have ready access to what you used, but you can change them back easily enough.)
<android.support.v7.widget.CardView
android:id="@+id/mCardviewPropertytype"
android:layout_width="160dp"
tools:background="@android:color/darker_gray"
android:layout_height="180dp"
android:layout_margin="8dp"
app:cardCornerRadius="8dp"
app:cardElevation="2dp">
<android.support.constraint.ConstraintLayout
android:layout_width="160dp"
android:layout_height="180dp"
android:layout_gravity="center"
android:layout_margin="8dp">
<android.support.constraint.ConstraintLayout
android:id="@+id/ImgPropertySelect"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="@mipmap/ic_launcher"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
tools:visibility="visible"
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_centerInParent="true"
app:srcCompat="@mipmap/ic_launcher" />
</android.support.constraint.ConstraintLayout>
<android.support.constraint.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5" />
<ImageView
tools:visibility="visible"
android:id="@+id/imageViewPropertyType"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="@mipmap/ic_launcher"
android:layout_marginLeft="16dp"
app:layout_constraintBottom_toTopOf="@+id/guideline"
app:layout_constraintLeft_toLeftOf="parent"
/>
<TextView
tools:text="Near residential area"
android:id="@+id/textViewTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:text="TextView"
android:textColor="@android:color/darker_gray"
android:textSize="20dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/guideline" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
A: Use this
app:cardBackgroundColor="@color/gray_black"
Instead of
tools:background="@color/gray_black"
Also
Use android:text="@string/nearResidentialArea"
instead of tools:text="@string/nearResidentialArea"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50288776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Expression performance of overload operator?
*
*(i++) and (i = i + 1)
*(i += n) and (i = i + n)
which is better (performance)?
A: It doesn't matter
The compiler will convert statements like that to (what it thinks, and often is) their most efficient form.
I'd recommend you write statements like this in the same way as the rest of your code base in order to keep consistency.
If you are just doing your own thing on a personal project you can either do what you prefer or what is common for your particular language.
A: It does not matter, the performance is the same. In 1978 when C was invented these would map to different PDP-11 instructions, resulting in faster performance of ++ and +=. These days, however, the operations are optimized into the same exact sequences of instructions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9367525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to properly apply filter for the query presented? I have a table as under
declare @t table(bucket bigint null)
insert into @t select 1 union all select 2 union all select -1 union all select 5
Now let me write the below query (filter by Bucket 0 - All values are coming)
declare @Bucket bigint = 0 –filter by 0
select * from @t
where 1=1
AND (@Bucket is Null or @Bucket ='' or bucket=@Bucket)
Result
1
2
-1
5
But if I filter Bucket by 2 or any other value, I get the results properly
declare @Bucket bigint = 2 –filter by 2
select * from @t
where 1=1
AND (@Bucket is Null or @Bucket ='' or bucket=@Bucket)
Result
2
If I filter by null or blank I get proper result
declare @Bucket bigint = '' –filter by ''
select * from @t
where 1=1
AND (@Bucket is Null or @Bucket ='' or bucket=@Bucket)
Result
1
2
-1
5
Why this behavior for bucket 0? And how to solve?
A: You can try to use @Bucket bigint = NULL for @Bucket default value.
because NULL mean unknow
or you can set a value which should not in bucket column be the default value.
declare @Bucket bigint = NULL
select *
from @t
where (@Bucket is Null or bucket = @Bucket)
NOTE
but If @Bucket bigint is bigint it should not be ''
Edit
CREATE TABLE T(
Bucket bigint
);
declare @Bucket bigint = 0
INSERT INTO T VALUES (1);
INSERT INTO T VALUES (2);
INSERT INTO T VALUES (-1);
INSERT INTO T VALUES (5);
INSERT INTO T VALUES (0);
select * from T
where (@Bucket is Null or (@Bucket ='' and @Bucket <> 0) or bucket=@Bucket)
A: FIXED
declare @t table(bucket bigint);
INSERT INTO @t VALUES (1);
INSERT INTO @t VALUES (2);
INSERT INTO @t VALUES (-1);
INSERT INTO @t VALUES (5);
INSERT INTO @t VALUES (0);
declare @Bucket bigint = 0 --filter by 0
select * from @t
where 1=1
AND (@Bucket is Null or cast(@Bucket as nvarchar) = '' or bucket=@Bucket)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53121834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Switching threads multiple times in Rx chain Let's assume I have a following case for Android:
*
*Request list of groups from network
*Show some UI elements for each group
*Request items for each group
*Show UI elemets for
each item
I want to do this using RxJava:
webService.requestGroups()
.flatMap(group -> {
view.showGroup(group);
return webService.requestItems(group);
})
.toList()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(items -> view.showItems(items));
As you can see I have 2 calls for view objects, each of them must be executed on main thread. And 2 calls for webService, which must be executed on background thread.
The problem with this code: first call to view will be executed on background which cause an Android RuntimeException (Only original thread may touch views or something) If I transfer .observeOn to the beginning of chain - second webService call will be executed in main thread.
How can I "swim" through threads multiple times in RxJava chain?
A: From the Rx doc for SubscribeOn:
The SubscribeOn operator designates which thread the Observable will begin operating on, no matter at what point in the chain of operators that operator is called. ObserveOn, on the other hand, affects the thread that the Observable will use below where that operator appears. For this reason, you may call ObserveOn multiple times at various points during the chain of Observable operators in order to change on which threads certain of those operators operate.
The SubscribeOn operator can only be applied once and sets the starting thread. ObserveOn can be used to go from one thread to another at any point in the stream. So I think the following should do what you want:
webService.requestGroups()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap(group -> {
view.showGroup(group);
return webService.requestItems(group)
.subscribeOn(Schedulers.io());
})
.toList()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(items -> view.showItems(items));
But in my opinion this is too complicated. I would just subscribe to the first observable, and then start a new chain for each group, like this:
webService.requestGroups()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(group -> {
view.showGroup(group);
webService.requestItems(group)
.subscribeOn(Schedulers.io()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(items -> view.showItems(items));
});
A: Building on Samuel's answer, you could do it with an even simpler, non-nested syntax:
webService.requestGroups()
.subscribeOn(Schedulers.io()) // the first operator (requestGroups) on the IO thread
.observeOn(AndroidSchedulers.mainThread()) //everything below on the main thread
.map(group -> {
view.showGroup(group);
return group;
})
.observeOn(Schedulers.io()) //everything below on the IO thread
.flatMap(group -> {
return webService.requestItems(group);
})
.toList()
.observeOn(AndroidSchedulers.mainThread()) //everything below on the main thread
.subscribe(items -> view.showItems(items));
Two rules of thumb here:
*
*subscribeOn dictates on which thread the observable will begin executing, its placement in the chain is irrelevant and it should appear only once.
*observeOn tells on which thread all subsequent operators will execute (until another observeOn is encountered); it may appear multiple times in the chain, changing execution thread of different code pieces (like in the example above).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46070235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Android ClickableSpan not calling onClick I am creating a ClickableSpan, and it is displaying properly with
the proper text underlined. However, the clicks are not registering.
Do you know what I am doing wrong???
Thanks, Victor
Here is the code snippet:
view.setText("This is a test");
ClickableSpan span = new ClickableSpan() {
@Override
public void onClick(View widget) {
log("Clicked");
}
};
view.getText().setSpan(span, 0, view.getText().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
A: After some trial and error, the sequence of setting the tv.setMovementMethod(LinkMovementMethod.getInstance()); does matter.
Here's my full code
String stringTerms = getString(R.string.sign_up_terms);
Spannable spannable = new SpannableString(stringTerms);
int indexTermsStart = stringTerms.indexOf("Terms");
int indexTermsEnd = indexTermsStart + 18;
spannable.setSpan(new UnderlineSpan(), indexTermsStart, indexTermsEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ForegroundColorSpan(getColor(R.color.theme)), indexTermsStart, indexTermsEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
Log.d(TAG, "TODO onClick.. Terms and Condition");
}
}, indexTermsStart, indexTermsEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
int indexPolicyStart = stringTerms.indexOf("Privacy");
int indexPolicyEnd = indexPolicyStart + 14;
spannable.setSpan(new UnderlineSpan(), indexPolicyStart, indexPolicyEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ForegroundColorSpan(getColor(R.color.theme)), indexPolicyStart, indexPolicyEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
Log.d(TAG, "TODO onClick.. Privacy Policy");
}
}, indexPolicyStart, indexPolicyEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView textViewTerms = (TextView) findViewById(R.id.sign_up_terms_text);
textViewTerms.setText(spannable);
textViewTerms.setClickable(true);
textViewTerms.setMovementMethod(LinkMovementMethod.getInstance());
A: Direct Approach in Kotlin
val textHeadingSpannable = SpannableString(resources.getString(R.string.travel_agent))
val clickSpan = object : ClickableSpan(){
override fun onClick(widget: View) {
// Handel your click
}
}
textHeadingSpannable.setSpan(clickSpan,104,136,Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
tv_contact_us_inquire_travel_agent.movementMethod = LinkMovementMethod.getInstance()
tv_contact_us_inquire_travel_agent.text = textHeadingSpannable
A: Have you tried setting the MovementMethod on the TextView that contains the span? You need to do that to make the clicking work...
tv.setMovementMethod(LinkMovementMethod.getInstance());
A: Kotlin util function:
fun setClickable(textView: TextView, subString: String, handler: () -> Unit, drawUnderline: Boolean = false) {
val text = textView.text
val start = text.indexOf(subString)
val end = start + subString.length
val span = SpannableString(text)
span.setSpan(ClickHandler(handler, drawUnderline), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
textView.linksClickable = true
textView.isClickable = true
textView.movementMethod = LinkMovementMethod.getInstance()
textView.text = span
}
class ClickHandler(
private val handler: () -> Unit,
private val drawUnderline: Boolean
) : ClickableSpan() {
override fun onClick(widget: View?) {
handler()
}
override fun updateDrawState(ds: TextPaint?) {
if (drawUnderline) {
super.updateDrawState(ds)
} else {
ds?.isUnderlineText = false
}
}
}
Usage:
Utils.setClickable(textView, subString, {handleClick()})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8641343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "189"
}
|
Q: c# EF Model has foreign key to another model Consider the following two models:
public class Category
{
public int Id {get;set;}
public string Name {get;set;}
public int Type {get; set;}
..other properties
}
public class Person
{
public int PersonId {get; set;}
public string Name {get; set;}
public int CategoryId {get; set;}
[ForeignKey["CategoryId"])
public virtual Category Category {get; set;}
}
I have a repository class that carries out something like the following to get all Person thats have a category of a particular type:
var result = repo.FindBy<Person>(p=>p.Category.Type == 1).ToList()
My repository method as requested by Ivan:
public IQueryable<T> FindBy<T>(Expression<Func<T, bool>> filter) where T : class
{
return _context.Set<T>().Where(filter).AsQueryable();
}
I get an "Object Not set to" error on the .Type property because I believe it is not linking the two models. I believe this is because the foreign keys do not match (is it using Reflection?).
I am not able to rename Category.Id to Category.CategoryId in the database.
Is there anything i can do on either models to be able to link the Category whenever I select from the Person table by setting a data annotation on either property?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42541825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a chance that street and zipcode data wasn't enough to populate full address I have a form where I ask the user to input their mailing address. Would there be any issues with asking only street address and zipcode and omitting city and state?
User zipcode in conjunction with zipcode database would result in having full address of the user. Would that be reliable considering that zipcode database is accurate?
A: I wouldn't do that.
*
*A ZIP code can contain two different towns, each with a "#123 Main Street" address.
*A ZIP code may cross state lines, which means you don't have enough information for shipping/tax details.
*You'll have a very hard time dealing with any customers who live outside of the USA.
A: Marcin,
There is not a one to one relationship between city and zipcode. A city can have multiple zipcodes. A zipcode can cross city lines.
Brian
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6604394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Implementing additional constraints in R's nnls I am using the R interface to the Lawson-Hanson NNLS implementation of an algorithm for non-negative linear least squares that solves ||A x - b||^2 with the constraint that all elements of vector x ≥ 0. This works fine but I would like to add further constrains. Of interest to me are:
*
*Also minimize "energy" of x:
||A x - b||^2 + m*||x||^2
*Minimize "energy in the x derivative"
||A x - b||^2 + m ||H x||^2, where H is the sum of identity and a matrix with -1 on the first off-diagonal
*Most generally, minimize ||A x - b||^2 + m ||H x - f||^2.
Is there are a way to coax nnls to do this by some clever way of restating the problems 1.-3. Above? The reason I have hope for such a thing is that there is a little-throw away comment in a paper by Whitall et al (sorry for the paywall) that claims that "fortunately, NNLS can be adopted from the original form above to accommodate something in problem 3".
A: I take it m is a scalar, right? Consider the simple case m=1; you can generalize for other values of m by letting H* = sqrt(m) H and f* = sqrt(m) f and using the solution method given here.
So now you're trying to minimise ||A x - b||^2 + ||H x - f||^2.
Let A* = [A' | H']' and let b* = [b' | f']' (i.e. stack up A on top of H and b on top of f) and solve the original problem of
non-negative linear least squares on ||A* x - b*||^2 with the constraint that all elements of vector x ≥ 0 .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8107660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Terraform and Jenkins Guys I want to automate terraform with Jenkins pipeline
And My terraform is installed on different Vm and Jenkins
Also.
I know there is the Terraform Plugin. But it seems like The Terraform
Has to be installed on the same vm as Jenkins(or on /var/lib/jenkins/workspace)
Is there anyway to get this done?
Please share your suggestions.
A: Yes, the fastest way to have it done is use master/slave setup for you jenkins. So, what you need to do is to add slave to the machine on which your terraform is running.
A: Generally, it's a good idea to keep your Jenkins machine as clean as possible, therefore you should avoid installing extra packages on it like Terraform. A better approach for this problem would be creating a Dockerfile with your Terraform binary and all the plugins that you need already built-in, then all you need to do in your Jenkins pipeline is build and execute your Terraform docker.
This is an example of such Dockerfile:
FROM hashicorp/terraform:0.11.7
RUN apk add --no-cache bash python3 && \
pip3 install --no-cache-dir awscli
RUN mkdir -p /plugins
# AWS provider
ENV AWS_VERSION=1.16.0
ENV AWS_SHA256SUM=1150a4095f18d02258d1d52e176b0d291274dee3b3f5511a9bc265a0ef65a948
RUN wget https://releases.hashicorp.com/terraform-provider-aws/${AWS_VERSION}/terraform-provider-aws_${AWS_VERSION}_linux_amd64.zip && \
echo "${AWS_SHA256SUM} terraform-provider-aws_${AWS_VERSION}_linux_amd64.zip" | sha256sum -c - && \
unzip *.zip && \
rm -f *.zip && \
mv -v terraform-provider-aws_* /plugins/
COPY . /app
WORKDIR /app
ENTRYPOINT []
The Terraform documentation also contains a section on best practices running Terraform in CI:
https://www.terraform.io/guides/running-terraform-in-automation.html
A: I have created a Global Shared Library awesome-jenkins-utils with which you can use different version of terraform simultaneously in same pipeline. Additionally you can easily map build parameters to terraform variables
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50090845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Git workflow for different versions of a framework We have the following setup: Three apps which are similar to each other with the common code extracted into a framework. Each app is managed in their own git repository and includes the framework as a git submodule.
The problem is that the apps are now developed in parallel with new features being added to the framework that other apps don't need to support right away. Currently we have different branches of the framework for all apps. One app uses the master branch of the framework because most of the time new features were first introduced in this app.
Framework branches
*
*master (used by App A)
*appB
*appC
When a new feature is introduced in appB that needed changes in the framework these changes were made to branch appB. If these changes were later needed in App A, branch appB was merged into master. This means that all changes in appB had to be merged into master.
This system worked but had some flaws
*
*merging a feature from one branch to another meant we had to merge all the changes
*easy to loose track what had been merged already or what is going to be merged when merging one branch into another
*Marking breaking changes was done using commit messages, which made the last point even more important
We are currently searching for a new workflow. I was think about having the following branches
*
*master
*appA
*appB
*appC
So for each app one branch and a master branch that includes all the changes. When new features are developed a feature branch should be created and then applied to master as well as to all app branches the feature is needed right away. Other apps can merge the feature branch when they need the feature later on.
I see the following problems with this
*
*How can I merge a feature branch onto multiple branches and only merge the changes that happened in the branch. I know of "git rebase onto ..." but I am not quite sure if I can use this command multiple times.
*Should I use git cherry-pick for merging features into multiple branches? I would rather not do this, because I can think that this will be error prone when not selecting all changes that were made in a feature branch
*How to keep track of which feature(branch) had been applied to which app. Can I use branch --no-merge or will that only work if the branches have the same ancestor?
Is my purposed way the best way to accomplish this or should I rethink my strategy completely?
A: As explain in "Git & Working on multiple branches", the two practical solutions when applying commits to multiple branches (which is what you would do with your "feature branches" option) are:
*
*merge (which should allow you to keep reusing that feature branch, as it would keep track of what has already been merge to a specific banch): a rebase --interactive might be in order for you to re-order the commits, putting first the ones you want to merge, and then the ones you are nnot ready yet to merge.
*cherry-picking (and it now supports a range of commits), but I always have been wary of cherry-picking.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9018254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Is Stream.findAny a short-circuit operation? Consider this code
Object found = collection.stream()
.filter( s -> myPredicate1(s))
.filter( s -> myPredicate2(s))
.findAny()
Will it process entire stream, and call both myPredicate1 and myPredicate2 for all elements of the collection? Or will as many predicates be called as are needed to actually find the value?
A: Yes it is, as the Stream.findAny() documentation states:
This is a short-circuiting terminal operation.
It's a common misconception that objects in stream are "pushed" towards consuming operation. It's actually the other way around - the consuming operation pulls each element.
For sequential streams only as many predicates will be called as are needed to find matching value.
Parallel streams may execute more predicates, but will also stop execution as soon as an element is found.
public class StreamFilterLazyTest {
static int stI = 0;
static class T {
public T() {
super();
this.i = ++stI;
}
int i;
int getI() {
System.err.println("getI: "+i);
return i;
}
}
public static void main(String[] args) {
T[] arr = {new T(), new T(), new T(), new T(), new T(), new T(), new T(), new T(), new T(), new T()};
Optional<T> found = Arrays.stream(arr).filter(t -> t.getI() == 3).findAny();
System.out.println("Found: "+found.get().getI());
}
}
will print:
getI: 1
getI: 2
getI: 3
Found: 3
A: The javadoc for findAny() states:
"This is a short-circuiting terminal operation."
"The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations ..."
This means that findAny() on a sequential stream will only "pull" enough elements to find the first one. On a parallel stream, it could pull more than enough, depending on the implementation.
The package javadoc also states:
"Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed."
This means that the filter() predicates only occur when the findAny() terminal pulls them.
In short:
Q: Is filter + findAny still a short-circuit operation?
A: Yes.
A: Well it does not matter if sequential or parallel streams are used, they are still going to traverse as many elements as are required to find the first that matches. It might be different if you use findFirst and you have a Stream made of an ordered collection.
findFirst in this case has to preserver the order.
In this case, due to parallelism, the second, then third elements might be processed before the first, but still only the first will be returned.
A: Stream#findAny is a short-circuiting terminal operation. it will visit Predicates to matching & short-circuited one by one since Stream#filter return a new stream each time.
Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.
As @Holger mentioned in comment that it can makes filters be short-circuited as below:
if(predicate1.test(value) && predicate2.test(value)){
....
}
Test
Iterator<Predicate<Integer>> predicates = Stream.<Predicate<Integer>>of(
it -> false,
it -> {
throw new AssertionError("Can't be short-circuited!");
}
).iterator();
Predicate<Integer> expectsToBeShortCircuited = it -> predicates.next().test(it);
Stream.of(1).filter(expectsToBeShortCircuited).filter(expectsToBeShortCircuited)
// |
// |
// here is short-circuited since the stream is empty now
.findAny();
A: You can use peek to verify this
== Sequential ==
Alpha1 Alpha2 Beta1 Beta2 Gamma1 Gamma2 Dolphin1 Fargo1 Fargo2 Found:
Fargo Applications: 9
== Parallel ==
Arnold1 Jim1 Loke1 Alpha1 Mustard1 Lenny1 Mustard2 Mark1 Alpha2 Mark2
Beta1 Beta2 Gamma1 Fargo1 Gamma2 Dolphin1 Fargo2 Found: Fargo
Applications: 17
YMMV depending on number of cores etc.
Produced by below
package test.test;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
public class Snippet {
static AtomicInteger predicateApplications;
public static void main(String arr[]) {
System.out.println("== Sequential == \n");
sequential();
System.out.println(" == Parallel == \n");
parallel();
}
private static void sequential() {
Stream<String> stream = Stream.of("Alpha", "Beta", "Gamma", "Dolphin", "Fargo", "Mustard", "Lenny", "Mark",
"Jim", "Arnold", "Loke");
execute(stream);
}
private static void parallel() {
Stream<String> parallelStream = Stream
.of("Alpha", "Beta", "Gamma", "Dolphin", "Fargo", "Mustard", "Lenny", "Mark", "Jim", "Arnold", "Loke")
.parallel();
execute(parallelStream);
}
private static void execute(Stream<String> stream) {
predicateApplications = new AtomicInteger(0);
Optional<String> findAny = stream.peek(s -> print(s + "1")).filter(s -> s.contains("a"))
.peek(s -> print(s + "2")).filter(s -> s.startsWith("F")).findAny();
String found = findAny.orElse("NONE");
System.out.println("\nFound: " + found);
System.out.println("Applications: " + predicateApplications.get());
}
private static void print(String s) {
System.out.print(s + " ");
predicateApplications.incrementAndGet();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44180155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Dynamic setting the timestamp fields in superset dashboards I'm building few dashboards in Apache superset. All my available timestamp fields are in UTC timezone. (for example fields are, class_start_time & class_end_time).
I want that in the timezone the dashboard is opened all the timestamp fields will be automatically converted.
For example, I'm opening dashboard in Norway , so the UTC data should be converted to CET timezone of Norway.
I have tried to add some value here in Hours offset but its not working.
Can you please guide how we can achieve this.?
Just for reference :
In Kibana dashboards (ELK stack) have feature to automatically convert the timezone into which it is being opened. So I need same thing in Superset.
A: Normally you would be able to set this with environment variables when you start the program or container. In Apache Superset, this is not possible. There is an ongoing discussion on Github about this issue. One GitHub user posts the problem and workaround, which is far from workable:
Daylight savings causes issues where users have to update datasource
timezone offset for each datasource twice per year.
So the only thing you can do is update the hours offset twice a year. To make matters even worse, if you use Postgresql, this may not even be possible due to a bug as described here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73727629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MS Access SQL Left Joins Not Working Can't get this ms JET sql query (querying a 2007 Access database that I didn't write) to work. Error mentions "too few parameters, expects 4". I believe it has to do with my JOINs.
Anyone know what I'm missing?
SELECT TOP 500 [Load Items].[LoadItemsID] AS load_order_line_id,
lo.[LoadOrderID] AS load_order_id,
sp.[Description] AS product_description,
sp.[Common Name] AS product_common_name,
c.[Bill To Name] AS company_name,
lp.[Ship Date] AS ship_date,
al.[Ordered] AS order_quantity,
al.[Price] AS sell_price,
a.[Order Date] AS order_date,
a.[Due Date] AS due_date
FROM ((((((([Load Items]
LEFT JOIN [Acknowledgement Lines] AS al
ON al.[AcknowledgmentLineID] = [Load Items].[AcknowledgmentLineID])
LEFT JOIN [Product] AS p
ON p.[ProductID] = al.[ProductID])
LEFT JOIN [Product Master] AS pm
ON pm.[ProductMasterID] = p.[ProductMasterID])
LEFT JOIN [Species] AS sp
ON sp.[SpeciesID] = pm.[SpeciesID])
LEFT JOIN [Acknowledgement] AS a
ON a.[AcknowledgmentID] = al.[AcknowledgmentID])
LEFT JOIN [Customer] AS c
ON c.[CustomerID] = a.[CustomerID])
LEFT JOIN [Load Orders] AS lo
ON lo.[LoadOrderID] = [Load Items].[LoadOrderID])
LEFT JOIN [Load Planner] AS lp
ON lp.[LoadPlannerID] = lo.[LoadPlannerID]
GROUP BY [Load Items].[LoadItemsID],
lo.[LoadOrderID],
sp.[Description],
sp.[Common Name],
c.[Bill To Name],
lp.[Ship Date],
al.[Ordered],
al.[Price],
a.[Order Date],
a.[Due Date];
A: The most likely cause is typos in field names. Each bracketed field name that doesn't correctly match the field name that you are trying to access in the tables is one missing parameter, as far as the parser is concerned.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51071236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Complex query on more than one child in cloud functions Here is the structure of my firebase database:
/UserData
/DeviceMgmt
/Counters
/NumberOfAll:
/NumberOfSelected
/TotalDownloaded
...
/Devices
/pushId1
/uid
/signOutTime
/toSelect=true (optional)
/downloaded
/lastDownload
/pushId2
/pushId3
...
And this is my cloud function:
exports.markDevicesForDownload = functions.database.ref('/UserData/DeviceMgmt/Counters/NumberOfSelected').onUpdate( (change) => {
const changeRef = change.after.ref;
const deviceMgmtRef = changeRef.parent.parent; // /UserData/DeviceMgmt
if (change.after.val() === 0 ) { //NumberOfSelected gets 0 value
return deviceMgmtRef.once('value')
.then((snap) => {
const devicesRef = snap.child('Devices').ref;
var average;
var numberOfAllDevices;
var totalDownloaded;
numberOfAllDevices = snap.child('Counters/NumberOfAll').val();
totalDownloaded = snap.child('Counters/TotalDownloaded').val();
average = Math.round(totalDownloaded/numberOfAllDevices);
return devicesRef
.orderByChild('signOutTime')
.equalTo(0)
.once('value',(devices) => {
return devices.ref
.orderByChild('downloaded')
.endAt(average)
.once('value',(devices) => {
devices.forEach((device) => {
device.child('toSelect').ref.set(true);
});
});
});
});
} else {
return false;
}
});
The function triggers when the counter NumberOfSelected = 0;
This happens when under any of device pushId there is no child toSelect. Then the query on downloaded child makes all devices with downloaded less than average set toSelect=true.
I wanted to limit the devices only to those which have signOutTime equal 0.
Somehow that query does not work and all devices are considered.
What I did wrong???
A: I would push all async tasks into a promise array and then return them all when all tasks complete:
exports.markDevicesForDownload = functions.database.ref('/UserData/DeviceMgmt/Counters/NumberOfSelected').onUpdate((change) => {
const changeRef = change.after.ref;
const deviceMgmtRef = changeRef.parent.parent; // /UserData/DeviceMgmt
if (change.after.val() === 0) { //NumberOfSelected gets 0 value
return deviceMgmtRef.once('value')
.then((snap) => {
const promises = [];
const devicesRef = snap.child('Devices').ref;
var average;
var numberOfAllDevices;
var totalDownloaded;
numberOfAllDevices = snap.child('Counters/NumberOfAll').val();
totalDownloaded = snap.child('Counters/TotalDownloaded').val();
average = Math.round(totalDownloaded / numberOfAllDevices);
const dR = devicesRef
.orderByChild('signOutTime')
.equalTo(0)
.once('value', (devices) => {
const dW = devices.ref
.orderByChild('downloaded')
.endAt(average)
.once('value', (devices) => {
devices.forEach((device) => {
if (device.child("signOutTime").val() === 0){
promises.push(device.child('toSelect').ref.set(true));
}
});
});
promises.push(dW);
});
promises.push(dR);
return Promise.all(promises);
});
} else {
return false;
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51499191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RoR: How to use *_path in a model? I need to generate a “report” in a model. This “report” has to include links. However, all the *_path functions seems to be unavailable in the model classes (a simple test show me that new_post_path raises an Exception in my models, but works fine in my controllers)
Is there any way to use polymorphic_url or, at least, *_path methods in my models ?
A: if you:
include ActionController::PolymorphicRoutes
In your model:
class SomeModel < ActiveRecord::Base
include ActionController::PolymorphicRoutes
end
you get polymorphic_path and polymorphic_url. These can then be used by passing self into the methods if you're generating a route for the current AR object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3398230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: At what point should data be sent back to server? A good example would be the stackexchange "rate" button. When a post is upvoted the arrow changes color immediately. However there is a grace period for one to edit one's vote decision (oops! voted by mistake?). Is the upvote action processed immediately or does is only process after a set time period, or when the user leaves the page? How exactly is this rating processed?
What is the standard for handling dynamic page edits (e.g. stackexchange rating, facebook posts?)
A: Generally I would recommend that you make the changes immediately. If there's to be a "grace period", then implement that on the server side (you can do it client side too if it will improve user experience).
So if someone upvotes a post, it is saved immediately via ajas, but then if they change their minds within the grace period, the server undoes the vote. Once the "grace period" is up, the server rejects the change.
A Facebook post would (obviously) be saved when you click "Post", etc. -- but it wouldn't be saved before then.
Something like Blogger or Google Docs is another issue altogether -- where it's automatic saving every x number of seconds. That is purely up to the developer. Generally you want to make it as often as possible without impacting performance or decreasing the user experience.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4714181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get releases for golang/go with go-github Learning Go and try to get the release list of golang/go with go-github.
Here is my code:
package main
import (
"github.com/google/go-github/github"
"fmt"
)
func main() {
client := github.NewClient(nil)
opt := &github.ListOptions{Page: 2, PerPage: 10}
releases, rsp, err := client.Repositories.ListReleases("golang", "go", opt)
if err != nil {
fmt.Println(err)
}
fmt.Printf("\n%+v\n", releases)
fmt.Printf("\n%+v\n", rsp)
}
When I run it, the release list is empty (as below):
[]
github.Rate{Limit:60, Remaining:59, Reset:github.Timestamp{2015-12-05 14:47:55 +1100 AEDT}}
I don't know what I am doing wrong.
A: Edit:
Taking a closer look at the Go repository, the releases are actually just tags and not Github releases, that's why it's returning an empty array. Try this:
// https://api.github.com/repos/jp9000/obs-studio/releases
releases, rsp, err := client.Repositories.ListReleases("jp9000", "obs-studio", opt)
This should correctly return all releases for jp9000's obs-studio repository.
Original Answer:
Looking at the docs, the code looks good but this might be an issue with Github's API though. For instance, if you go to https://api.github.com/repos/golang/go/releases you get an empty array, but if you search for the tags using https://api.github.com/repos/golang/go/tags it lists all tasks without any problem.
And if you go to https://api.github.com/repos/golang/go/releases/1 you get a 404. I took these addresses from the Github Developer's page: https://developer.github.com/v3/repos/releases/#list-releases-for-a-repository
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34100738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Can't insert any values in Judy I'm getting strange behavior with Judy Array. The documentation just says you can use it like an usual PHP array. But whatever I do it seems to me that it won't store any information.
For example if I do this:
$this->_history = new Judy(Judy::STRING_TO_MIXED);
$this->_history['test'] = 'testString';
echo $this->_history['test']; // output nothing; no warnings no text nothing
var_dump($this->_history); // class Judy#126 (0) { }
$this->_history->getType() // correctly (int) 5
$this->_history->getTypeFoo() // warning no method
Am I doing something wrong? Did I forget something? I tested it both an an Ubuntu and Debian System, both the same.
Also funny is, that when I run the bench-script which is provided in the pecl package and extracted under /usr/share/php/doc/Judy/examples/judy-bench-string_to_int.php the Judy Array works fine.
Here's how I installed it:
sudo aptitude install libjudydebian1 libjudy-dev
sudo pecl install judy
It said installation was succesful and I added extension=judy.so to php.ini.
What should I do to get Judy working?
A: Well it works now. But actually I don't know why. I shouldn't care.
I copied the working code from the bench-*.php file from the /docs into my own file and it worked. Here's the code:
echo "\n-- Judy STRING_TO_INT \n";
echo "Mem usage: ". memory_get_usage() . "\n";
echo "Mem real: ". memory_get_usage(true) . "\n";
$s=microtime(true);
$judy = new Judy(Judy::STRING_TO_MIXED);
for ($i=0; $i<500; $i++)
$judy["$i"] = 'test';
var_dump($judy);
unset($judy["102"]);
echo $judy["192"];
var_dump($judy["102"]);
echo "Size: ".$judy->size()."\n";
$e=microtime(true);
echo "Elapsed time: ".($e - $s)." sec.\n";
echo "Mem usage: ". memory_get_usage() . "\n";
echo "Mem real: ". memory_get_usage(true) . "\n";
echo "\n";
unset($judy);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19482950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Associative table many on many with varying level of entity specificity I have the need to associate a message or a group of messages with a display or a group of displays.
A message has a type, and a display has a type and a location ( for example, a city)
I would like to associate a message or all messages of a certain type to a display or all display of a certain type and/or location.
My first idea was to build an associative table many on many, with the foreign keys:
*
*Message_id
*Message_type_id
*Display_id
*Display_location_id
*Display_type_id
And when adding an entry, set a value for the fields i am interested in ( for example message_type and display_location), and null to the others.
However, i was interested in the downsides of this approach, and wondering if there are better methods to handle this kind of problems. After some days searching (in vain) for this kind of pattern when designing a database, i ultimately decided to ask here.
Thanks for the help.
A: The approach is sound.
It occurs to me that you only need Message_id and Display_id in the "intersection entity", as the other columns would probably come from the "parent" entity.
Message_type_id
Display_location_id
Display_type_id
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44624803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does Apple Catalyst support iPhone There are many resources and tutorials mentioning iPad and/or iOS being compatible with Apple's Catalyst framework,
So, the same source-code runs on Mac OS X as well.
But does Catalyst support iPhone?
(Please tell me your personal experience to clarify this, and not that the name of iPhone operating-system is iOS)
A: Mac Catalyst allows iOS apps to be built for and run on macOS.
So, by definition, Catalyst apps support iOS, and usually the iPhone. The only case in which they wouldn't is if the app was specifically an iPad-only app that runs on Catalyst on the Mac, but was not enabled to run on the iPhone.
More about Catalyst: https://developer.apple.com/mac-catalyst/
You asked for personal experience: I have apps in the App Store for iOS, iPad, and Mac, via both Catalyst and non-Catalyst builds.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66150433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Selectize.js destroy() method changes select value I'm using selectize.js in my project. What I need to do is clone part of the form (with selectized elements) and append it to the end of the form.
I've decided to destroy selectized elements before cloning, and after appending new subform initialize selectize again.
Here is a code for destroying selectized elements:
var selectElements = $(plusButtonElement).parents(".subform_wrapper").first().find("> .subform_fields_wrapper").find("select");
$.each(selectElements, function(index, element){
console.log(element);
console.log($(element).val()); //Here we got value "10"
$(element)[0].selectize.destroy();
console.log($(element).val()); //Here we got value "A6"
});
It works - elements transform to the regular selects, BUT value of the select elements are changing. Did anyone face with this problem?
I checked selectize.js source and the only thing I can say is that value is changed in this code:
self.$input
.html('')
.append(revertSettings.$children)
.removeAttr('tabindex')
.removeClass('selectized')
.attr({tabindex: revertSettings.tabindex})
.show();
A: Hi Tamara yes I think this is a bug of the Selectize.js.
I alter the following destroy method in selectize.js
destroy: function() {
var self = this;
var selectedValue = self.$input.val();
var eventNS = self.eventNS;
var revertSettings = self.revertSettings;
self.trigger('destroy');
self.off();
self.$wrapper.remove();
self.$dropdown.remove();
self.$input
.html('')
.append(revertSettings.$children)
.removeAttr('tabindex')
.removeClass('selectized')
.attr({tabindex: revertSettings.tabindex})
.show();
self.$control_input.removeData('grow');
self.$input.removeData('selectize');
$(window).off(eventNS);
$(document).off(eventNS);
$(document.body).off(eventNS);
delete self.$input[0].selectize;
self.$input.val(selectedValue);
},
Here you can download my selectize.js file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27911184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Debug Dockerized Flask app in VSCode not breaking on breakpoints I followed this tutorial to set up debug in my VSCode.
My launch.json file is below.
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"connect": {
"host": "localhost",
"port": 5678
},
"pathMappings": [
{
"localRoot": "${workspaceFolder}/server/project/views",
"remoteRoot": "/server/project/views"
}
]
}
]
}
My code does break on raised and user uncaught exceptions but it does not break on the breakpoints that I set. The code is reaching the breakpoints and I checked it using print statements, but my breakpoints are not working. VSCode debugger does seem to listen to my docker app (seen in the logs in screenshot) but not sure why it is not breaking at my breakpoints. However, it does give an error saying:
pydev debugger: unable to find translation for:
"/home/vvarma9/DTNetworkRepos/ip2m-metrr/server/project/utils/assessments.py"
in ["/home/vvarma9/DTNetworkRepos/ip2m-metrr/server/project/views/",
"/home/vvarma9/DTNetworkRepos/ip2m-metrr/server/project/views"]
(please revise your path mappings).
Kindly help!
A: Make sure your local and remote paths are correct. You can check your remote path by logging into the container's terminal. There you can find the absolute path of your "app".
I also cannot tell where you ${workspaceFolder} is actually is. Could be DTNetworkRepos or ip2m-metrr. You will need to make sure you clarify the path.
Also it would help if you posted up your folder stucture, Docker file for the server project and docker compose for all your container projects. Docker file will explain your path on the remote server. Dockerfile & Docker-compose file will ensure us that you have the right cmd or entrypoint for your environment. It may not line up with the tutorial that you set up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73328360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to use geometry manager grid inside . which already has slaves managed by pack I found the code below on the net, and I tried to adapt it to my personal needs in my code but I have as error: tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack.
Here is the code I found on the net that allows to display large images by clicking on small images :
import tkinter as tk
nb_rows = 10
images = (
("images/small_images/small_image1.png", "images/big_images/big_image1.png"),
("images/small_images/small_image2.png", "images/big_images/big_image2.png"),
("images/small_images/small_image3.png", "images/big_images/big_image3.png"),
("images/small_images/small_image4.png", "images/big_images/big_image4.png"),
# ...
)
def visualize(event):
event.widget.unbind("<Button-1>")
window = tk.Toplevel(event.widget)
window._image = tk.PhotoImage(file=event.widget._filenames[1])
tk.Label(window, image=window._image).pack()
window.protocol("WM_DELETE_WINDOW", lambda: on_close(window))
def on_close(window):
window.master.bind("<Button-1>", visualize)
window.destroy()
root = tk.Tk()
labels, row, column = [], 0, -1
for index, filenames in enumerate(images):
label = tk.Label(root)
label["image"] = label._image = tk.PhotoImage(file=filenames[0])
label._filenames = filenames
label.bind("<Button-1>", visualize)
if not index % nb_rows:
column, row = 0, row + 1
label.grid(column=column, row=row)
row += 1
labels.append(label)
root.mainloop()
here is part of my code that works correctly, and I want to integrate the code above on the left side (Text left) and adapt it to be functional :
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from tkinter import *
root=Tk()
root.iconbitmap(r'images/cev.ico')
text_part1_loc35R="\n===============================\n"
text_part2_loc35R="Emetteur Directif 1 :\n"
text_part3_loc35R="===============================\n"+\
"Puissance directe (P+BL) : 4.47 w\n"+\
"Puissance reflechie (P+BL) : 0.13 w\n"+\
"Puissance directe (BLS) : 0.09 w\n"+\
"Puissance reflechie (BLS) : 0.00 w\n"+\
"===============================\n"
text_part4_loc35R="Emetteur Clearance 1 :\n"
text_part5_loc35R="===============================\n"+\
"Puissance directe (P+BL) : 0.55 w\n"+\
"Puissance reflechie (P+BL) : 0.09 w\n"+\
"Puissance directe (BLS) : N/A w\n"+\
"Puissance reflechie (BLS) : N/A w\n"+\
"###############################\n\n"
generalites = Frame(root,bg="powder blue",width=750,height=250)
generalites.pack()
##########################################
#les sous frames de generalites(top,bottom):
generalites_top=Frame(generalites,relief=RIDGE,bd=18,bg='cadet blue')
generalites_top.pack(side=TOP,fill=X)
titre_generalites_top=Label(generalites_top,text='Generalites Techniques LOC 35R',font=('arial',22,'bold'),bg='cadet blue',padx=120)
titre_generalites_top.pack()
###############################################
generalites_bottom=Frame(generalites,bg='powder blue',width=750,height=270)
generalites_bottom.pack(side=BOTTOM)
#################################################
generalites_bottom_left=Frame(generalites_bottom,bg='powder blue',width=375)
generalites_bottom_left.pack(side=LEFT)
generalites_bottom_right=Frame(generalites_bottom,bg='powder blue',width=375)
generalites_bottom_right.pack(side=LEFT)
##################################################
T_generalites_left = Text(generalites_bottom_left,padx=20, height=26, width=30)
s_generalites_left = Scrollbar(generalites_bottom_left, command=T_generalites_left.yview)
T_generalites_left.configure(yscrollcommand=s_generalites_left.set)
T_generalites_left.tag_configure('style_loc35R',font=('arial',12,'bold'),foreground='blue',justify='center')
photo1=PhotoImage(file='images/test/image1.png')
photo2=PhotoImage(file='images/test/image2.png')
photo3=PhotoImage(file='images/test/image3.png')
photo4=PhotoImage(file='images/test/image4.png')
photo5=PhotoImage(file='images/test/image5.png')
for (j,k) in [('\nphoto 1\n',photo1),('\n\nphoto 2\n',photo2),('\n\nphoto 3\n',photo3),('\n\nphoto 4\n',photo4),('\n\nphoto 5\n',photo5)]:
T_generalites_left.insert(END,j,'style_loc35R')
T_generalites_left.image_create(END, image=k)
T_generalites_left.insert(END,'\n\n')
T_generalites_left.pack(side=LEFT,anchor=NW)
s_generalites_left.pack(side=LEFT, fill=Y)
T_generalites_right = Text(generalites_bottom_right, bg='powder blue',font=('arial',14,'bold'),padx=15, height=18, width=52)
s_generalites_right = Scrollbar(generalites_bottom_right, command=T_generalites_right.yview)
T_generalites_right.configure(yscrollcommand=s_generalites_right.set)
T_generalites_right.tag_configure('style_loc35R', foreground='blue',justify='center',font=('arial', 12, 'bold'))
T_generalites_right.insert(END,text_part1_loc35R)
T_generalites_right.insert(END,text_part2_loc35R,'style_loc35R')
T_generalites_right.insert(END,text_part3_loc35R)
T_generalites_right.insert(END,text_part4_loc35R,'style_loc35R')
T_generalites_right.insert(END,text_part5_loc35R)
T_generalites_right.pack(side=LEFT)
s_generalites_right.pack(side=RIGHT, fill=Y)
root.mainloop()
Thanks for help
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55799607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Assigning colors to a d3.js bar chart? I'm trying to create a color-coded bar chart using d3. I am SO CLOSE. Here's my bl.ocks chart:
http://bl.ocks.org/sconnors37/b99070b055f125c9dff1/1cb53954be3f20e3c4492066eccd749b5cf04bbe
What I'm trying to do is assign color values based on the "teams" field in my .tsv file. So grey for Mercedes, red for Ferrari, etc. I have the teams in the var color domain and the colors in the var color range, and I'm pulling var color into the bar attrib.
For some reason though, the entire chart is just taking on the first item in the range - I changed it from grey to red just to see if that was what was going on, and it is.
So! How do I get the rest of my colors to pull through onto the bar chart? Help me, stackoverflow, you're my only hope.
A: In your .tsv file the last column team is not separated from the previous column by a tab, but rather through two spaces. If you look at the data passed to the d3.tsv callback I think you will find that you have one date team column instead of a date and team column.
This means that the field d.team is undefined and ordinal(undefined) will just return the first value from the range.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28946525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Material-UI CardContent has a 3px Bottom Padding Note: I already looked into this question: Cant remove padding-bottom from Card Content in Material UI
But the accepted answer did not fix my issue.
I am using the Material UI React Library attempting to recreate the below image:
I am completely new to using the Material UI, so most of my code will likely not be optimized and probably does not follow best practices. Indeed, I'd be interested to hear how it could be made better.
Here is my code thus far:
<Card className={classes.card}>
<CardActionArea containerStyle={{ paddingBottom: 0 }}>
<CardMedia
className={classes.media}
title="Contemplative Reptile"
image="none"
>
<div className={classes.heading}>
<AccessAlarmIcon className={classes.icon}/>
<Typography className={classes.mainText} variant="h5" component="h2">Delayed</Typography>
<Typography className={classes.subText} variant="subtitle1" component="h5">9:30pm Departure</Typography>
</div>
</CardMedia>
<CardContent className={classes.content}>
<img className={classes.mainPic} src="http://images1.fanpop.com/images/image_uploads/Golden-Gate-Bridge-san-francisco-1020074_1024_768.jpg"></img>
</CardContent>
</CardActionArea>
</Card>
With these styles:
const styles = {
card: {
maxWidth: 300,
},
media: {
height: 60,
backgroundColor: "#FF1547",
padding: 16
},
icon: {
color: "white",
fontSize: 25,
marginRight: 10
},
mainText: {
color: "white",
display: "inline-block",
position: "relative",
top: -3
},
subText: {
color: "white",
marginLeft: 36,
},
heading: {
padding: 0
},
mainPic: {
width: 300,
height: 200,
marginBottom: 0,
padding: 0
},
content: {
padding: "0 !important",
'&:last-child': {
paddingBottom: "0 !important",
},
}
};
This is what it looks like when rendered:
Notice the bottom padding. The Chrome Developer Tools show a 3px bottom padding under the User Agent Stylesheet. I imported a CSS Reset which did not help.
Again, I'm sure that my styles and JSX could be made better, but efficiency, optimization, and elegance were not of my concern.
Thanks,
Jamie
A: That padding at the bottom is actually caused by the box-shadow styling tied to the "elevation" property of Paper (which Card is based on). Setting the elevation to 0 gets rid of it:
<Card className={classes.card} elevation={0}>
However that also gets rid of the raised look of the card. The correct way to deal with this is to specify the image in a CardMedia element rather than using a separate img tag inside a CardContent element.
<CardMedia
className={classes.mainPic}
image="http://images1.fanpop.com/images/image_uploads/Golden-Gate-Bridge-san-francisco-1020074_1024_768.jpg"
/>
Here's a CodeSandbox showing this:
You can also see this approach used in this demo:
https://material-ui.com/demos/cards/#ui-controls
A: See if this is what you want. I changed mainPic and content.
This syntax containerStyle={{ paddingBottom: 0 }} does not seem correct even gets the alert in the browser. Maybe you want to change the styleor classes={{root}} of the api CardActionArea.
mainPic: {
width: 300,
marginBottom: 0,
padding: 0,
borderRadius: '0 0 4px 4px',
},
content: {
height: 225,
padding: "0 !important",
'&:last-child': {
paddingBottom: "0 !important",
},
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54263946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Exception when adding new method in a working Service using gRPC-Web and protobuf-net I am getting the following exception:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: The type initializer for 'DefaultProxyCache1' threw an exception. System.TypeInitializationException: The type initializer for 'DefaultProxyCache1' threw an exception. ---> System.ArgumentException: Invalid generic arguments
Parameter name: typeArguments
at (wrapper managed-to-native) System.Reflection.RuntimeMethodInfo.MakeGenericMethod_impl(System.Reflection.RuntimeMethodInfo,System.Type[])
at System.Reflection.RuntimeMethodInfo.MakeGenericMethod (System.Type[] methodInstantiation) <0x342def8 + 0x000d6> in :0
at ProtoBuf.Grpc.Internal.ContractOperation.TryGetClientHelper () [0x0001b] in //src/protobuf-net.Grpc/Internal/ContractOperation.cs:291
at ProtoBuf.Grpc.Internal.ProxyEmitter.EmitFactory[TService] (ProtoBuf.Grpc.Configuration.BinderConfiguration binderConfig) [0x00477] in //src/protobuf-net.Grpc/Internal/ProxyEmitter.cs:238
at ProtoBuf.Grpc.Internal.ProxyEmitter.CreateFactory[TService] (ProtoBuf.Grpc.Configuration.BinderConfiguration binderConfig) [0x0006d] in //src/protobuf-net.Grpc/Internal/ProxyEmitter.cs:123
at ProtoBuf.Grpc.Configuration.ClientFactory+DefaultProxyCache`1[TService]..cctor () [0x00000] in //src/protobuf-net.Grpc/Configuration/ClientFactory.cs:81
My project uses gRPC-Web, Blazor web assembly and protobuf-net
This is my service contract:
[ServiceContract(Name = "Services.Customer")]
public interface ICustomerService
{
ValueTask<Customer> CreateCustomer(Customer customerDTO);
ValueTask<CustomerResultSet> GetCustomers();
}
The implementation is:
public class CustomerService : ICustomerService
{
private readonly CustomerUseCases customerLogic;
public CustomerService(CustomerUseCases customerLogic)
{
this.customerLogic = customerLogic;
}
public async ValueTask<Customer> CreateCustomer(Customer customerDTO)
{
var result = await customerLogic.CreateCustomer(customerDTO);
return customerDTO;
}
public async ValueTask<CustomerResultSet> GetCustomers()
{
CustomerResultSet result = new CustomerResultSet { Customers = await customerLogic.GetCustomer() };
return result;
}
}
As for the Datacontracts:
[DataContract]
public class CustomerResultSet
{
[DataMember(Order = 1)]
public IEnumerable<Customer> Customers { get; set; }
}
And,
[DataContract]
public partial class Customer
{
[DataMember(Order = 1)]
public int CustomerId { get; set; }
[DataMember(Order = 2)]
public string CustomerName { get; set; }
}
Before I was returning a List of customers in the service but I realize I needed a class to model the message in order to protobuf-net be able to serialize that is why CustomerResultSet. Still, it is not working.
Any help much appreciated
A: That is... odd. I can't repro it here, so I'm guessing it is something specific to Blazor. I've checked what the code does in the "regular" frameworks, and at least for me it seems to do the right things - using UnaryValueTaskAsync<Customer, Customer>() and UnaryValueTaskAsync<Empty, CustomerResultSet>(), which is what I would expect. I've improved the exception handling in that code path, to at least give us a clue what it is trying to do, so my suggestion is:
*
*update to protobuf-net.Grpc version >= 1.0.119 (I'll get it deployed as soon as CI finishes)
*retry, and let me know exactly what it says now
Alternatively, if you have a minimal repro including the blazor bits on, say, a GitHub repo, I can happily take a look there.
(tip: I try to keep an eye on both Stack Overflow and GitHub, but GitHub is probably more appropriate for this kind of question - I'd happily say that this is a bug, so: https://github.com/protobuf-net/protobuf-net.Grpc/issues)
A: I was having a similar problem.
System.InvalidOperationException: Error obtaining client-helper 'UnaryValueTaskAsync' (from: 'System.Guid', to: 'Test.DTO.OpResult'): Invalid generic arguments
My entire ServiceContract on that service stopped working. This happened after I added
ValueTask ChangeCompany(Guid companyGuid);
I changed it to
ValueTask ChangeCompany(string companyGuid);
And that got it working again. The error was a bit confusing since i wasn't using ChangeCompany, but like a said, not calls were working.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62732593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What is the input data structure for HERMES toolbox for EEG connectivity analysis? I wanted to use HERMES for connectivity analysis of my EEG dataset which includes 32 subjects and 40 trials for each subject. There are two conditions/classes. I do not know how my data should be defined to be known by HERMES!
Could you please kindly tell me what should the structure of input to HERMES be?
Or is there a better alternative like Brainstorm to use in my MATLAB scripts (I mean without using its GUI manually and do my connectivity analysis automatically by using loops instead)?
Any help in this regards is greatly appreciated.
HERMES toolbox
Brainstorm toolbox
A: HERMES accepts MAT files (*.mat) and Fieldtrip structures.
MAT files should consist on one single matrix with as many columns as channels and as many rows as temporal points (and, in the case of event-related data, the third dimension will be for the different trials).
For example, for one subject and condition: a matrix of (30 channels x 1000 samples (x 50 trials)).
Therefore, to be able to load your data easily, you'll need to obtain your MAT files as described above.
Thanks to Guiomar Niso for providing this answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34895301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error installing PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56 on Magento 1.9.2.4 I'm getting the following error and have no idea why. All my extensions are properly installed to not effect any code code.
Any ideas?
sudo sh ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh
./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 14: ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 127: not found
./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 14: ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 127: not found
./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 25: ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 0: not found
Checking if patch can be applied/reverted successfully...
-e ERROR: Patch can't be applied/reverted successfully.
checking file app/code/core/Mage/Admin/Model/Session.php
checking file app/code/core/Mage/Adminhtml/Block/Checkout/Formkey.php
checking file app/code/core/Mage/Adminhtml/Block/Notification/Symlink.php
checking file app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Date.php
checking file app/code/core/Mage/Adminhtml/Model/Config/Data.php
checking file app/code/core/Mage/Adminhtml/controllers/Catalog/Product/GalleryController.php
checking file app/code/core/Mage/Checkout/controllers/MultishippingController.php
checking file app/code/core/Mage/Checkout/controllers/OnepageController.php
Hunk #1 succeeded at 350 (offset 1 line).
Hunk #2 succeeded at 370 (offset 1 line).
Hunk #3 succeeded at 417 (offset 1 line).
Hunk #4 succeeded at 446 (offset 1 line).
Hunk #5 succeeded at 485 (offset 1 line).
checking file app/code/core/Mage/Checkout/etc/system.xml
checking file app/code/core/Mage/Cms/Model/Wysiwyg/Images/Storage.php
Hunk #1 succeeded at 282 (offset -1 lines).
checking file app/code/core/Mage/Core/Controller/Front/Action.php
checking file app/code/core/Mage/Core/Controller/Request/Http.php
checking file app/code/core/Mage/Core/Model/File/Validator/Image.php
checking file app/code/core/Mage/Core/etc/system.xml
checking file app/code/core/Mage/Customer/Model/Session.php
checking file app/code/core/Mage/Dataflow/Model/Convert/Adapter/Zend/Cache.php
checking file app/code/core/Mage/Dataflow/Model/Convert/Container/Abstract.php
checking file app/code/core/Mage/Dataflow/Model/Convert/Parser/Csv.php
checking file app/code/core/Mage/Dataflow/Model/Convert/Parser/Xml/Excel.php
checking file app/code/core/Mage/ImportExport/Model/Import/Uploader.php
checking file app/code/core/Mage/Sales/Model/Quote/Item.php
checking file app/code/core/Mage/Widget/Model/Widget/Instance.php
checking file app/code/core/Mage/XmlConnect/Helper/Image.php
checking file app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php
checking file app/design/adminhtml/default/default/layout/main.xml
checking file app/design/adminhtml/default/default/template/notification/formkey.phtml
checking file app/design/adminhtml/default/default/template/notification/symlink.phtml
checking file app/design/adminhtml/default/default/template/page/head.phtml
checking file app/design/frontend/base/default/template/checkout/cart/shipping.phtml
checking file app/design/frontend/base/default/template/checkout/multishipping/billing.phtml
checking file app/design/frontend/base/default/template/checkout/multishipping/shipping.phtml
checking file app/design/frontend/base/default/template/checkout/onepage/billing.phtml
checking file app/design/frontend/base/default/template/checkout/onepage/payment.phtml
Hunk #1 succeeded at 35 (offset -1 lines).
checking file app/design/frontend/base/default/template/checkout/onepage/shipping.phtml
checking file app/design/frontend/base/default/template/checkout/onepage/shipping_method.phtml
checking file app/design/frontend/base/default/template/persistent/checkout/onepage/billing.phtml
checking file app/design/frontend/rwd/default/layout/page.xml
checking file app/design/frontend/rwd/default/template/checkout/cart/shipping.phtml
checking file app/design/frontend/rwd/default/template/checkout/multishipping/addresses.phtml
checking file app/design/frontend/rwd/default/template/checkout/multishipping/billing.phtml
checking file app/design/frontend/rwd/default/template/checkout/onepage/payment.phtml
Hunk #1 succeeded at 36 (offset -1 lines).
checking file app/design/frontend/rwd/default/template/checkout/onepage/shipping.phtml
checking file app/design/frontend/rwd/default/template/persistent/checkout/onepage/billing.phtml
checking file app/etc/config.xml
checking file app/locale/en_US/Mage_Adminhtml.csv
Hunk #1 succeeded at 1281 (offset -4 lines).
checking file app/locale/en_US/Mage_Core.csv
Hunk #1 succeeded at 406 (offset -1 lines).
checking file app/locale/en_US/Mage_Dataflow.csv
checking file app/locale/en_US/Mage_XmlConnect.csv
checking file downloader/Maged/Connect.php
Reversed (or previously applied) patch detected! Assume -R? [n]
Apply anyway? [n]
Skipping patch.
3 out of 3 hunks ignored
checking file downloader/Maged/Controller.php
Reversed (or previously applied) patch detected! Assume -R? [n]
Apply anyway? [n]
Skipping patch.
2 out of 2 hunks ignored
checking file downloader/Maged/Model/Session.php
Hunk #1 succeeded at 96 with fuzz 2 (offset 14 lines).
Hunk #2 succeeded at 302 with fuzz 2 (offset 29 lines).
checking file js/lib/jquery/jquery-1.12.0.js
checking file js/lib/jquery/jquery-1.12.0.min.js
checking file js/lib/jquery/jquery-1.12.0.min.map
checking file js/varien/payment.js
checking file skin/frontend/base/default/js/opcheckout.js
Hunk #1 succeeded at 711 (offset 27 lines).
A: The hunk error normally came because it will not match the file lines. In this case you can do 2 things.
*
*Replace those mention error files with new same version Magento setup and then try to install the patch using SSH.
*Install the patch manually.
In this patch in front end only form key is added in checkout and cart files so you can do it manually.
Thanks.
A: I had a similar issue.
The solution for me was next:
*
*Check if you have 'downloader' folder in your project, if not (usually it is not under git) - download it (better from the current project, versions can be different);
*Revert the previous version of this patch (description of the patch - "Note that you must revert SUPEE-9767 version 1 before deploying version 2.")
($ bash ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh -R)
and after that try to patch 2nd version.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44478570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Tools to determine video orientation I receive videos from different devices and want to encode them using the correct orientation.
I've seen some of examples of how to determine the orientation of a video from a iPhone.
With exiftool and mediainfo I can indeed tell if an iPhone video has to be rotated.
However, for android videos, both portrait and landscape videos have the same rotation and matrix structure as each other.
Maybe this is just with my phone, I'm trying to find videos taken from newer droid phones.
My question however is whether there's other tools or a different way to determine the orientation that'll work with all devices.
EDIT:
I just checked a video from a Samsung Galaxy S II, and I can get the orientation from exiftool. So it's not a problem with all android phones.
My android phone is a HTC Desire running on android 2.2.
And actually (I didn't even notice before) a portrait video will not be correctly oriented even when playing on the phone. So I guess it's not about the tools, the orientation data just doesn't seem to be correct at all.
A: Some phones include the rotation information, some phone don't, but the best way to know on videos that include this information is with mediainfo:
mediainfo --Inform="Video;%Rotation%"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9807857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: assign process id to an asynchronous request tornado I would like to create consistent logs so that I can compute statistics on each tornado request, I have a request as below:
@tornado.web.asynchronous
def post(self):
try:
process_id = uuid.uuid4()
logging.info("Incoming request (process_id: %s) to %s" % (str(process_id), self.__class__.__name__))
which would print some info when a request comes in, but the request gets completed in tornado code, which would only print this:
[I 150331 10:55:09 web:1728] 200 POST /transform (127.0.0.1) 3017.19ms
Is there a way to pass my process id to tornado (or make it create one), so that I can connect the first and the last log events of a request?
thanks,
A: In general, the best way to record something like this is to attach it to the RequestHandler instance. For logging, you can override Application.log_request, which has access to the handler. You may need to pass either the request ID or the RequestHandler instance around to other parts of your code if you need to use this in multiple places.
It is possible but tricky to use StackContext as something like a threading.Local if you really need this to be pervasive, but explicitly passing it around is probably best.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29365861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: executing samtools in terminal: "command not found", but it is installed I have samtools installed, and I have used it before on my computer. I am trying to get it to work now, but when I type in samtools in terminal (mac os), it returns "command not found". I have navigated into my samtools folder too and it is still not working. Am i missing something? Thank you for your help
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63889019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Strange behaviour in Material datepicker I'm trying to use materialize date picker (http://materializecss.com/forms.html). With that, I want to popup the date picker when I click on an icon. I have implemented two implementations where the only difference between the two is putting an alert('clicked') with the code.
without the alert('clicked'): http://jsfiddle.net/1bnnkhbw/
with the alert('clicked'): http://jsfiddle.net/1bnnkhbw/1/
The second one works while the first one doesn't.. (in chrome)!!!
Anybody knows the reason for this behavior?
And a way to make the 1st one work?
A: I think I found a solution for you man check this out:
<i id="icon">click</i>
<input class="datepicker" style="display:none;" value="click"></input>
$('.datepicker').pickadate({
selectMonths: true,
selectYears: 15
});
$('#icon').click(function(event){
event.stopPropagation();
$(".datepicker").first().pickadate("picker").open();
console.log("test1");
});
Fiddle: http://jsfiddle.net/k2qtzp7p/1/
Code taken from here and here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29832007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: VBA define property in a variable I am new to the forum, and also new to VBA (only started learning it a week ago).
Is it possible to define a property in a variable? I have a line that looks kind of like this:
Cells(i, j).Formula = "=" & .Cells(i, j).Address(External:=True, RowAbsolute:=False, ColumnAbsolute:=False)
I have to write several cells, so I end up having many of these lines; if possible, I would like to do something like:
dim prop as string
prop = "Address(External:=True, RowAbsolute:=False, ColumnAbsolute:=False)"
Cells(i, j).Formula = "=" & .Cells(i, j).prop
Can something like this be done?
A: You mean like this?
Function MyProp(ByVal r as Range) as String
MyProp = r.Address(External:=True, RowAbsolute:=False, ColumnAbsolute:=False)
End Function
...
Cells(i,j).Formula = "="& MyProp( Cells(i,j) )
This of course makes a cell reference itself, which is generally a bad idea and may lead to circular references. Best if you describe more on what you are trying to do in order to get better answers.
A: As mentioned in the comments this cannot be done in the way you describe. There are two alternatives:
*
*Write a Private Function that you call with your input and expected output (more complicated)
*Write a loop with the code only appearing once. (less code)
To write a loop for all cells from A1 to Last used row, last used column:
Dim LastRow As Long, LastCol As Long
LastRow = Range("A" & Rows.Count).End(xlUp).Row
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column
For i = 1 To LastRow
For j = 1 to LastCol
`Do your stuff here
Next j
Next i
Edit:
I'm going to assume you need to invest in the Range.Offset() method found here because right now, you are setting the cell's formula as equal to itself...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27605146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to build lighter version of opencv_java3 for android? I'm following these lines to build OpenCV's libraries for Android.
Usage Linux:
$ export ANDROID_NDK=/absolute/path/to/the/android-ndk
$ mkdir build && cd build
$ cmake -DCMAKE_TOOLCHAIN_FILE=path/to/the/android.toolchain.cmake ..
$ make -j8
The built libopencv_java3.so file for one architecture (armeabi-v7a) is 8.3MB large.
Is there a way to omit some unused modules on build to get lighter libraries ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41983647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Outlook + Perl + Win32::Ole: How do you select calendar entries sorted by date? Current code opens up an Outlook Calendar database as follow:
my $outlook = Win32::OLE->GetActiveObject('Outlook.Application') || Win32::OLE->new('Outlook.Application', 'Quit');
my $namespace = $outlook->GetNamespace("MAPI");
## only fetch entries from Jan 1, 2007 onwards
my $restrictDates = "[Start] >= '01/01/2007'";
A: Since you don't show the code that gets the date of your object, this question is impossible to answer without some knowledge of the Outlook object you are trying to access.
If you have an array of objects you can sort them by date and filter ones prior to a certain one.
my $sub = sub {
my $ad = $a->date_string_accessor;
my $bd = $b->date_string_accessor;
$ad =~ s:(\d+)/(\d+)/(\d+):$3 . sprintf('%0d', $1) . sprintf('%0d', $2):e;
$bd =~ s:(\d+)/(\d+)/(\d+):$3 . sprintf('%0d', $1) . sprintf('%0d', $2):e;
return $ad cmp $bd;
};
my @sorted = sort $sub @unsorted;
print join("\n", @sorted);
But it would seem to me that you should use the application itself to do this -- presumably Outlook has some sort of query/sort functionality.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/78916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to compress a size of 1024*1024*1024*4 sparse array I have a sparse array which is size of 1024 * 1024 * 1024 * 4. This array's item is byte. So the memory for the array is 4G. It is a sparse array, that is, non-zero item only about 600M. Hopefully, a storage structure can be proposed to compress the sparse array (compressed to 2 ~ 3G), and have good access speed.
A: The suitable representation depends on what operations is desired on the sparse array. The general approach is to store the locations of non-zero items and their values in a data structure.
One option is to use a hash table.
enum {NumDimensons = 4};
struct ArrayLocation {
int16_t location[NumDimensions];
};
typedef uint8_t ArrayValue;
// Hash Table with key as ArrayLocation and value as ArrayValue
With hash table operations like get() and put() are straightforward, but iteration is not. If iteration is important, one option is to use a binary search tree.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40449996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: GCDWebServer always aborts on options check I started using GCDWebServer version 3.1 in an app last year, and this line in the addHandlerWithMatchBlock method of GCDWebServer.m always caused the system to abort immediately:
GWS_DCHECK(_options == nil);
I ended up just changing it to this to avoid the problem:
GWS_DCHECK(_options != nil);
Now I'm updating to the latest version 3.3.2 and see the same problem. My hack still works here, but I would like to know what a real solution would be. Can someone explain?
A: See docs in header:
Addling handlers while the server is running is not allowed.
Attempting to do this will result in undefined behavior.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37195995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sql Group by datetime I have a MySql table :
+--------------------+----------------+
| datetime | energy |
+--------------------+----------------+
| 2010-06-15 10:00:00| 1|
| 2010-06-15 10:15:00| 3|
| 2010-06-15 10:30:00| 6|
| 2010-06-15 10:45:00| 7|
| 2010-06-15 11:00:00| 9|
| 2010-06-15 11:15:00| 12|
| 2010-06-15 11:30:00| 15|
| 2010-06-15 11:45:00| 28|
| 2010-06-15 12:00:00| 52|
| 2010-06-15 12:15:00| 75|
| 2010-06-15 12:30:00| 88|
| 2010-06-15 12:45:00| 102|
| 2010-06-15 13:00:00| 150|
| 2010-06-15 13:15:00| 189|
| 2010-06-15 13:30:00| 200|
| 2010-06-15 13:45:00| 205|
| 2010-06-15 14:00:00| 209|
| 2010-06-15 14:15:00| 400|
| 2010-06-15 14:30:00| 450|
| 2010-06-15 14:45:00| 480|
| 2010-06-15 15:00:00| 500|
+--------------------+----------------+
I would obtain the production of every hour as difference between max and min of every hour:
example:
production of hour 10 is given by prod. of hour 11 (value = 9) less production of hour 10 (value = 1) -> result = 8
Expected result
+--------------+----------------+
| datetime | energy |
+--------------+----------------+
| 2010-06-15 10| 8|
| 2010-06-15 11| 43|
| 2010-06-15 12| 98|
| 2010-06-15 13| 69|
| 2010-06-15 14| 291|
+--------------+----------------+
select max(energy) - min(energy)
FROM tableA
group by hour(datetime)
this query doesn't work because make the difference between 10:45 and 10:00 ( not 11:00 and 10:00)
Any advice ?
A: To get the difference between each hour, use a self-join that relates times that are an hour apart.
SELECT a.datetime, b.energy - a.energy AS energy
FROM tableA AS a
JOIN TableA AS b ON a.datetime = DATE_SUB(b.datetime, INTERVAL 1 HOUR)
WHERE MINUTE(a.datetime) = 0
DEMO
A: EXAMPLE WITH MISSING DATA
+--------------------+----------------+
| datetime | energy |
+--------------------+----------------+
| 2010-06-15 10:00:00| 1|
| 2010-06-15 10:45:00| 7|
| 2010-06-15 11:00:00| 9|
| 2010-06-15 11:15:00| 12|
| 2010-06-15 11:30:00| 15|
| 2010-06-15 11:45:00| 28|
| 2010-06-15 12:15:00| 75|
| 2010-06-15 12:30:00| 88|
| 2010-06-15 12:45:00| 102|
| 2010-06-15 13:00:00| 150|
| 2010-06-15 13:15:00| 189|
| 2010-06-15 13:30:00| 200|
| 2010-06-15 13:45:00| 205|
| 2010-06-15 14:00:00| 209|
| 2010-06-15 14:15:00| 400|
| 2010-06-15 14:30:00| 450|
| 2010-06-15 14:45:00| 480|
| 2010-06-15 15:00:00| 500|
+--------------------+----------------+
In this example some samples are missing.
Expected result:
+--------------+----------------+
| datetime | energy |
+--------------+----------------+
| 2010-06-15 10| 8| 11:00 to 10:00
| 2010-06-15 11| 17| 11:45 to 11:00
| 2010-06-15 12| 150| 13:00 to 12:15
| 2010-06-15 13| 69| 13:00 to 14:00
| 2010-06-15 14| 291| 14:00 to 15:00
+--------------+----------------+
I always want to group by a complete hour:
From 10:00 to 11:00 included
From 11:00 to 12:00 included
From 12:00 to 13:00 included
ecc....
immagine
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44302509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Dyamically Assign JSON Property by Depth I would like to assign a variable on a json object by layers of depth.
For Example:
veryDeepTree[branch][branch][branch][branch] = value
would be achieved by executing the function:
assignByDepth(4, value, branch)
A: One way you can do this is by using a recursive function. Where each iteration of the function goes 1 level deeper until it reaches the desired level to set the value. This is a basic version assuming objects exists with correct depth before calling the function. As it is now, there can be multiple errors if used incorrectly, should be amended to add more error checks.
var veryDeepTree = {
branch : {
branch : {
branch : {
}
}
}
};
function assignByDepth(subTree, currentTreeDepth, objProperty, value){
if(currentTreeDepth == 1){
subTree[objProperty] = value;
}else{
assignByDepth(subTree[objProperty], --currentTreeDepth, objProperty, value);
}
}
assignByDepth(veryDeepTree, 3, "branch", {branch:10});
console.log(veryDeepTree);
assignByDepth(veryDeepTree, 4, "branch", 5555);
console.log(veryDeepTree);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43947109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Error Eclipse Project library see my screen :
http://it.tinypic.com/r/xpa240/8
I can not fix these errors. It seems that it does not generate the class R.
I've tried everything!
Clean the project,
Install all tools
help me thanks
A: The R class is generated automatically by the Android Eclipse plugin when it can. Here, I can see a red cross on your "res" folder so I think you should have some errors on your resources naming or type or something else : just look what your IDE is telling you !
Fix all errors that are not "R class missing" related and this class will be generated.
A: try this :
1 - File->Import (android-sdk\extras\android\support\v7). Choose "appcompat"
2 - Project-> properties->Android. In the section library "Add" and choose "appCompat"
3 - That is all!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26282161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Integer array of resource ids returns 0 I have a set of resource ids stored in an array. This is accessed inside the recycler view to populate an image view. The problem is when I access the array, all values returned is 0.
// arrays.xml
<array name="array_category_icons">
<item>@drawable/autumn</item>
<item>@drawable/backpack</item>
</array>
// inside recycler view adapter
int[] myIcons = getActivity().getResources().getIntArray(R.array.array_category_icons);
myIcons[i] always returns 0.
The drawables are in the hdpi folder only.
A: Do this:
TypedArray ta = getResources().obtainTypedArray(R.array.array_category_icons);
Drawable[] icons = new Drawable[ta.length()];
for (int i = 0; i < ta.length(); i++) {
int id = ta.getResourceId(i, 0);
if (id != 0) {
icons[i] = ContextCompat.getDrawable(this, id);
}
}
ta.recycle();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43307243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Saving the current data before updating the form in Django I would like to create a history of changes in one of my models. That every time I will update it, the current data will be saved to a different table and at the same time, the new data enters to another table. How will I be able to do that? I saw examples and they are based from the admin. But I still don't get the idea of it. This maybe a noob question but I'm still learning Django.
models.py
class tblTicket(models.Model): #new data will be entered here
remarks = models.TextField("Action Taken", max_length=500,default='')
class LogChanges(models.Model): #table to save the changes
prevRemarks = models.CharField(max_length=500,default='')
forms.py
class troubleTicket(ModelForm):
class Meta:
model = tblTicket
fields = '__all__'
class history(ModelForm):
class Meta:
model = LogChanges
fields = '__all__'
views.py
def updateTicket(request, ticket_id):
ticketDetails=tblTicket.objects.get(id=ticket_id)
updateTicketForm = troubleTicket(request.POST or None,instance=ticketDetails)
if updateTicketForm.is_valid():
updateTicketForm.save()
return HttpResponseRedirect('/ticket/')
return render(request,'updateTicket.html', {'updateTicketForm':updateTicketForm,'ticketDetails':ticketDetails,'ticket_id':ticket_id})
I am using django 1.8.3
UPDATE:
I found a link related to my question. But it gives me an error NameError: name 'tblTicket' is not defined
def make_copy(sender, **kwargs):
obj = kwargs['instance']
try:
orig_obj = tblTicket.objects.get(pk=obj.pk)
except: #If it is a new object
orig_obj = None
pre_save.connect(make_copy, sender=tblTicket) <- this is where the error leads me
To my understanding, in this link, the Country there is the model. So I switched it to my model which is tblTicket. I don't understand why it isn't defined.
A: cIt sounds like you want to override the save method of your tblTicket model so that it creates a new LogChanges object. Like this..
class tblTicket(models.Model):
...
def save(self):
super(tblTicket, self).save()
LogChanges.objects.create(prevRemarks=self.remarks)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31850849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to update ProgressBar with respect to downloaded data while downloading text data from web using Asynctask in android I want to show progressbar wrt to downloaded data from the web. Whether I have to create dynamically or have to reference by Id by creating it in xml.I am a little bit confused. Here is my code. Could you please tell me how?
package com.example.telugumovies;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends ListActivity {
String category ="";
String[] cat = {"Upcoming","Telugu"};
private List<String> categories ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
categories = new ArrayList<String>();
int i=0;
for(i=0;i<2;i++)
{
categories.add(cat[i]+" Movies");
}
ArrayAdapter<String> myAdapter = new ArrayAdapter <String>(this,
R.layout.listview_rowlayout, R.id.tv, categories);
// assign the list adapter
setListAdapter(myAdapter);
}
// when an item of the list is clicked
@Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
Bundle giveCategory = new Bundle();
if(position == 0)
{
try {
new GetData().execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
else if(position == 1)
{
giveCategory.putString("cate", cat[position]);
Intent a = new Intent(MainActivity.this,Show_Years.class);
a.putExtras(giveCategory);
startActivity(a);
}
else
{
Toast.makeText(getApplicationContext(), "Sorry This option is not Available for Now ",
Toast.LENGTH_SHORT).show();
}
//String selectedItem = (String) getListView().getItemAtPosition(position);
}
class GetData extends AsyncTask<String,Integer,String>
{
ProgressBar pb ;
protected void onPreExecute()
{
pb = new ProgressBar(MainActivity.this);
pb.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String alldata = "";
int flag=1;
String data = "";
URL url = null;
int i=0,j=0,count=0,c=0;
URLConnection con = null;
InputStream is = null;
String line = null;
try
{
url = new URL("http://www.filmibeat.com/telugu/upcoming-movies.html");
con = url.openConnection();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
//System.out.println(line);
alldata = "";
flag=0;
if(line.contains("<h3"))
{j=0;
flag=1;
for(i=0;i<line.length();i++)
{
if(line.charAt(i)=='<')
{
j=1;
}
else if(j==1 && line.charAt(i)=='>')
{
j=0;
}
else if(j==0)
{
alldata = alldata + (line.charAt(i));
}
}
}
data=data+alldata;
if(flag==1)
{
data=data+"$";
}
}
System.out.println(data);
return data;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
return data;
}
}
protected void onPostExecute(String someting)
{
Bundle givedata = new Bundle();
givedata.putString("moviedata",someting);
Intent a = new Intent(MainActivity.this,Show_upcomingmovies.class);
a.putExtras(givedata);
pb.setVisibility(View.INVISIBLE);
startActivity(a);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
A: Using dynamically created progress bar or referencing it from an id, are both fine.
Using a reference from XML allows you to have more control on the progress bars appearance, as you would have designed it sepcifically for your need (like appearance, where it has to appear, etc..). But if that is not the case, you can use a dynamically created one as in your current code as well.
A: There is a lot of ways. One is to define ProgressDiaolog as a field in your AsyncTask, then add it to your onPreExecuted():
pDialog = new ProgressDialog(this);
pDialog.setMessage("some downloading massage");
pDialog.setIndeterminate(false);
pDialog.setMax(100); //you can adjust this
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
Then you can update the progress by override updateProgress() in your AsyncTask and call pDialog.setProgress();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28791405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: App crashes with storage exception,while dealing with images in firebase storage Following is my piece of code.
this code runs in a loop for many images and images are shown( the whole code runs as expected).
and suddenly app crashes with this error.
Error:: StorageException: StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
And no line of my code is directed for the cause of the error.
StorageReference storageRef = FirebaseStorage.getInstance().getReferenceFromUrl("storage_location");
StorageReference pathReference = storageRef.child("imgPath");
pathReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
holder.ivIcon2.setImageUrl(uri.toString(), MySingleton.getInstance(activity).getImageLoader());
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d("tag", e.toString());
}
});
Don't have any idea of the origin of the issue.
Deleting and reuploading all the images in Storage solve the problem for the time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41198011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cannot access a disposed Object C# I am having a hard time. I am new to this. Can someone help me with this. Every time I call the _clientSocket.Close(); I got an error message.
Cannot access a disposed object. Object name:
System.net.Sockets.Socket
There's no error in my code. It can run smooth but every time I open and close a form it comes up. I want to get rid of it. The program can run with it but its to irritating. Because when I try to open a client it will pop up. And when the time of the client is done, the form will close and the login will come out with another pop up of
Cannot access a disposed object. Object name:
System.net.Sockets.Socket
I use _clientSocket.Close() because if I'm not closing the sockets it will be doubled in Server side. I close it so it will not be double IP in Checklistbox of the Server.
I'm doing this for my project and I'm just studying myself so some of the comments I really don't understand but I'm trying my best to learn from it thank you!
Your suggestions will much appreciated. Correct me if I'm wrong thank you!
This code is the Loginform when Server sends -O it will _clientSocket.Close(); and open the Form2. If Form2 use all the time it will back to Loginform and form2 _clientSocket.Close(); I call the _clientSocket.Close(); because the Server Checklistbox that catches all the connected sockets will be doubled if I don't close the Sockets.
Edited
Server
namespace RealVersion2
{
public partial class Server : Form
{
public class SocketT2h
{
public Socket _Socket { get; set; }
public string _Name { get; set; }
public SocketT2h(Socket socket)
{
this._Socket = socket;
}
}
private byte[] _buffer = new byte[1024];
public List<SocketT2h> __ClientSockets { get; set; }
List<string> _names = new List<string>();
private Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public Server()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
__ClientSockets = new List<SocketT2h>();
this.list_Client.SelectionMode = System.Windows.Forms.SelectionMode.None;
}
private void Send_Click(object sender, EventArgs e)
{
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " );
}
else
{
Sendata(__ClientSockets[j]._Socket, "Server: " + txt_Text.Text);
}
}
}
rich_Text.AppendText("\nServer: " + txt_Text.Text);
txt_Text.Text = "";
}
}
void Sendata(Socket socket, string noidung)
{
byte[] data = Encoding.ASCII.GetBytes(noidung);
socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
_serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
}
private void SendCallback(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
socket.EndSend(AR);
}
private void SetupServer()
{
try
{
lb_stt.Text = "Setting up server . . .";
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8000));
_serverSocket.Listen(1);
_serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AppceptCallback(IAsyncResult ar)
{
Socket socket = _serverSocket.EndAccept(ar);
__ClientSockets.Add(new SocketT2h(socket));
list_Client.Items.Add(socket.RemoteEndPoint.ToString());
lb_soluong.Text = "Number of clients connected: " + __ClientSockets.Count.ToString();
lb_stt.Text = "Client connected. . .";
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
_serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
}
private void ReceiveCallback(IAsyncResult ar)
{
Socket socket = (Socket)ar.AsyncState;
if (socket.Connected)
{
int received;
try
{
received = socket.EndReceive(ar);
}
catch (Exception)
{
// client close connection
for (int i = 0; i < __ClientSockets.Count; i++)
{
if (__ClientSockets[i]._Socket.RemoteEndPoint.ToString().Equals(socket.RemoteEndPoint.ToString()))
{
//taga tapoon ng panget
list_Client.Items.RemoveAt(i);
__ClientSockets.RemoveAt(i);
lb_soluong.Text = "Number of clients connected: "+__ClientSockets.Count.ToString();
}
}
//delete in list
return;
}
if (received!=0)
{
byte[] dataBuf = new byte[received];
Array.Copy(_buffer, dataBuf, received);
string text = Encoding.ASCII.GetString(dataBuf);
//lb_stt.Text = "Text received: " + text;
string reponse = string.Empty;
//reponse = "Server: Hi! You're Connected to the Librarian.";
if (text.Contains("@@"))
{
for (int i = 0; i < list_Client.Items.Count; i++)
{
if (socket.RemoteEndPoint.ToString().Equals(__ClientSockets[i]._Socket.RemoteEndPoint.ToString()))
{
list_Client.Items.RemoveAt(i);
list_Client.Items.Insert(i, text.Substring(1, text.Length - 1));
__ClientSockets[i]._Name = text;
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
return;
}
}
}
for (int i = 0; i < __ClientSockets.Count; i++)
{
if (socket.RemoteEndPoint.ToString().Equals(__ClientSockets[i]._Socket.RemoteEndPoint.ToString()))
{
rich_Text.AppendText("\n" + __ClientSockets[i]._Name + ": " + text);
}
}
}
else
{
for (int i = 0; i < __ClientSockets.Count; )
{
if (__ClientSockets[i]._Socket.RemoteEndPoint.ToString().Equals(socket.RemoteEndPoint.ToString()))
{
__ClientSockets.RemoveAt(i);
lb_soluong.Text ="The number of clients connected: " + __ClientSockets.Count.ToString();
}
}
}
}
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void Server_Load(object sender, EventArgs e)
{
SetupServer();
}
private void Restartbtn_Click(object sender, EventArgs e)
{
string Restart = string.Empty;
Restart = "-r";
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " + Restart);
}
}
}
rich_Text.AppendText("\nServer: " + txt_Text.Text);
}
}
private void Shutdownbtn_Click(object sender, EventArgs e)
{
string Shutdown = string.Empty;
Shutdown = "-s";
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " + Shutdown);
}
}
}
rich_Text.AppendText("\nServer: " + txt_Text.Text);
}
}
private void list_Client_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < list_Client.Items.Count; i++)
{
if (list_Client.GetItemRectangle(i).Contains(list_Client.PointToClient(MousePosition)))
{
switch (list_Client.GetItemCheckState(i))
{
case CheckState.Checked:
list_Client.SetItemCheckState(i, CheckState.Unchecked);
break;
case CheckState.Indeterminate:
case CheckState.Unchecked:
list_Client.SetItemCheckState(i, CheckState.Checked);
break;
}
}
}
}
private void openPCToolStripMenuItem_Click_1(object sender, EventArgs e)
{
string Open = string.Empty;
Open = "-O";
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " + Open);
//use [i] if u dont want name in list
}
}
}
//rich_Text.AppendText("\nServer: " + txt_Text.Text);
}
}
private void Server_FormClosing(object sender, FormClosingEventArgs e)
{
string Ext = string.Empty;
Ext = "exit";
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " + Ext);
}
}
}
//rich_Text.AppendText("\nServer: " + txt_Text.Text);
Application.Exit();
_serverSocket.Close();
}
}
private void End_Click(object sender, EventArgs e)
{
string Ext = string.Empty;
Ext = "close";
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " + Ext);
}
}
}
//rich_Text.AppendText("\nServer: " + txt_Text.Text);
}
}
}
}
Client
public partial class UserLog : Form
{
private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
TimeSpan countdownClock = TimeSpan.Zero;
public UserLog()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string Username = "User";
string Pass = "123";
if (Username == textBox1.Text && Pass == textBox2.Text)
{
MessageBox.Show("Login Successfully");
Usertimer User = new Usertimer(textBox1.Text);
User.Show();
this.Hide();
_clientSocket.Dispose();
_clientSocket.Close();
}
else
{
MessageBox.Show("Please Enter valid Username or Password");
}
}
byte[] receivedBuf = new byte[1024];
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (_clientSocket != null && _clientSocket.Connected)
{
_clientSocket.Close();
}
}
private void ReceiveData(IAsyncResult ar)
{
try
{
int received = _clientSocket.EndReceive(ar);
if (received == 0)
{
return;
}
Array.Resize(ref receivedBuf, received);
string text = Encoding.Default.GetString(receivedBuf);
Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
AppendtoTextBox(text);
if (text == "Server: -O")
{
Thread NT = new Thread(() =>
{
this.BeginInvoke((Action)delegate ()
{
textBox1.Text = "Guest";
this.Hide();
_clientSocket.Close();
Usertimer us = new Usertimer(textBox1.Text);
us.Show();
});
});
NT.Start();
}
if (text == "Server: exit")
{
_clientSocket.Close();
Application.Exit();
}
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
}
catch (ObjectDisposedException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AppendtoTextBox(string text)
{
MethodInvoker invoker = new MethodInvoker(delegate
{
textBox4.Text += text + "\r\n";
});
this.Invoke(invoker);
}
private void LoopConnect()
{
int attempts = 0;
while (!_clientSocket.Connected)
{
try
{
attempts++;
_clientSocket.Connect(IPAddress.Parse(textBox5.Text), 8000);
//_clientSocket.Connect(IPAddress.Parse(textBox4.Text), 100);
}
catch (SocketException)
{
//Console.Clear();
lb_stt.Text = ("Connection attempts: " + attempts.ToString());
}
}
AppendtoTextBox(reponse);
}
private void button2_Click(object sender, EventArgs e)
{
LoopConnect();
// SendLoop();
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
byte[] buffer = Encoding.ASCII.GetBytes("@@"+txName.Text);
_clientSocket.Send(buffer);
}
private void UserLog_Load(object sender, EventArgs e)
{
LoopConnect();
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
byte[] buffer = Encoding.ASCII.GetBytes("@@"+txName.Text);
_clientSocket.Send(buffer);
}
private void UserLog_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
}
Form2 of the client
public partial class Usertimer : Form
{
private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public Usertimer(string pass)
{
InitializeComponent();
label3.Text = pass;
}
byte[] receivedBuf = new byte[1024];
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
this.btnConnect_Click(null, null);
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (_clientSocket != null && _clientSocket.Connected)
{
_clientSocket.Close();
}
}
private void ReceiveData(IAsyncResult ar)
{
try
{
int received = _clientSocket.EndReceive(ar);
if (received == 0)
{
return;
}
Array.Resize(ref receivedBuf, received);
string text = Encoding.Default.GetString(receivedBuf);
if (text == "Server: close")
{
Thread NT = new Thread(() =>
{
this.BeginInvoke((Action)delegate ()
{
UserLog Log = new UserLog();
Log.Show();
this.Close();
_clientSocket.Close();
});
});
NT.Start();
}
Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
AppendtoTextBox(text);
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AppendtoTextBox(string text)
{
MethodInvoker invoker = new MethodInvoker(delegate
{
richTextBox1.Text += text + "\r\n";
});
this.Invoke(invoker);
}
private void LoopConnect()
{
int attempts = 0;
while (!_clientSocket.Connected)
{
try
{
attempts++;
_clientSocket.Connect(IPAddress.Parse(textBox4.Text), 8000);
}
catch (SocketException)
{
//Console.Clear();
lb_stt.Text = ("Connection attempts: " + attempts.ToString());
}
}
AppendtoTextBox(reponse);
}
private void btnConnect_Click(object sender, EventArgs e)
{
LoopConnect();
// SendLoop();
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
byte[] buffer = Encoding.ASCII.GetBytes("@@" + txName.Text);
_clientSocket.Send(buffer);
}
private void btnSend_Click(object sender, EventArgs e)
{
if (_clientSocket.Connected)
{
byte[] buffer = Encoding.ASCII.GetBytes(txt_text.Text);
_clientSocket.Send(buffer);
AppendtoTextBox(txName.Text + ": " + txt_text.Text);
}
txt_text.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
UserLog log = new UserLog();
log.Show();
this.Close();
_clientSocket.Close();
}
}
}
A: Like I answered in your previous question, you should spend the time to read these two pages. They will help you get your answer much faster.
There's no error in my code.
If you're getting an error message, then there's an error in your code.
every time I open and close a form
What form? There is no form in your example.
it will be doubled in Server side. I close it so it will not be double IP in Checklistbox of the Server.
What server? What checklistbox? We don't know what you are referring to here.
Without a minimal, complete and verifiable example, we can't help you very well. That being said, it looks like you are closing your _clientSocket. Once you've closed a socket you must re-open it or create a new one before you can use it again. You cannot call BeginReceive after you've closed your socket.
I was able to reproduce your error by creating a complete, minimal and verifiable example. Here is the code:
public partial class Form1 : Form
{
Socket _clientSocket;
public Form1()
{
InitializeComponent();
}
const int buffSize = 1024;
byte[] receivedBuf = new byte[buffSize];
Socket listenerSock;
Socket handlerSock;
private void Form1_Load(object sender, EventArgs e)
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
listenerSock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listenerSock.Bind(localEndPoint);
listenerSock.Listen(10);
listenerSock.BeginAccept(ServerAcceptAsync, null);
_clientSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_clientSocket.Connect(localEndPoint);
_clientSocket.BeginReceive(receivedBuf, 0, buffSize, SocketFlags.None, ReceiveData, null);
}
private void ServerAcceptAsync(IAsyncResult ar)
{
handlerSock = listenerSock.EndAccept(ar);
}
private void ReceiveData(IAsyncResult ar)
{
//try
//{
Debug.WriteLine("received data");
int received = _clientSocket.EndReceive(ar);
if (received == 0)
{
return;
}
Array.Resize(ref receivedBuf, received);
string text = Encoding.Default.GetString(receivedBuf);
Debug.WriteLine(text);
if (text == "Server: -O")
{
Thread NT = new Thread(() =>
{
this.BeginInvoke((Action)delegate ()
{
textBox1.Text = "Guest";
this.Hide();
_clientSocket.Close();
//Usertimer us = new Usertimer(textBox1.Text);
//us.Show();
});
});
NT.Start();
}
Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
//AppendtoTextBox(text);
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
//}
}
private void button1_Click(object sender, EventArgs e)
{
var message = Encoding.UTF8.GetBytes("Server: -O");
handlerSock.Send(message);
}
}
I commented the code that was not necessary to reproduce. As expected, the problem is that you call ReceiveAsync after you call _clientSock.Close(). You can't do that. If you close the socket, you should not execute anymore code. Here is an example of how to fix this:
if (text == "Server: -O")
{
Thread NT = new Thread(() =>
{
this.BeginInvoke((Action)delegate ()
{
textBox1.Text = "Guest";
this.Hide();
_clientSocket.Close();
//Usertimer us = new Usertimer(textBox1.Text);
//us.Show();
});
});
NT.Start();
}
else
{
Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
//AppendtoTextBox(text);
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52043648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Change default value for Job Activity Monitor Is there a way for me to programmatically (some config table, I'm hoping) change the default value in the Auto Refresh setting to 5 seconds instead of 60, and to set the Auto Refresh to ON?
I need a way to make this a permanent setting - hopefully so that it applies to all users of the server.
A: According to this thread,you can do like below
Open Job activity monitor
In the left pane you can see "View refresh settings"
Click on it and you have a check box for "Auto refresh"
Enable the check box and provide the refresh interval.
Then click ok.
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/d040105c-9d09-46d3-bb37-c69e771190ab/refresh-settings-job-activity-monitor?forum=sqlkjmanageability
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34929065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Running an axios.get inside a map function is returning a promise I have a React application where I get a list of books' ids from my DB and I display them using these IDs to get the information from the GoogleBooks API. So I'm mapping through my props and for each book, I'll go for the API using the axios.get().
My problem is that it's returning an object Promise that I couldn't find where to handle.
this is the error it games me
Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
thanks!
class HomeGroup extends Component {
componentDidMount() {
this.props.fetchBooks();
}
renderBooks() {
return this.props.books.map(async (book, index) => {
const res = await axios.get(`https://www.googleapis.com/books/v1/volumes?q=isbn:${book.ISBN}`);
return <div key={index}>{res.data.items[0].id}</div>;
});
}
render() {
return <div className="row">{this.renderBooks()}</div>;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57893376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: git subtree push failed for behind its remote counterpart I have a github repository and wanted to make a mockup live with my domain.
Since the index.html is located inside a folder named "development" (but not directly in the root), what I did was
a. Create another github repo called "USERNAME.github.io"
b. Add the remote-url by
git remote add demo-origin git@github.com:USERNAME/USERNAME.github.io.git
c. push the repo subtree "development" by
git subtree push --prefix development demo-origin master
d. create "CNAME" file in my "USERNAME.github.io"
e. update the DNS to match the CNAME
Now everything works fine. However when I want to push updates again, I got the error message:
git push using: demo-origin master
To git@github.com:SMARTEDU/SMARTEDU.github.io.git
! [rejected] a5f0176dc6e0b10fa77a88cffe89a67d087d1f96 -> master (non-fast-forward)
error: failed to push some refs to 'git@github.com:SMARTEDU/SMARTEDU.github.io.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
This was due to the CNAME file added in "USERNAME.github.io" repo, but even if I pull it to local, it is still failed when I want to do git subtree push --prefix development demo-origin master again.
Any idea on how to fix it? Very appreciate!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37269796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Logic behind HTML5 Placeholder I am working with a form. Each input field name is identified by its Placeholder. My form working fine in Chrome and Mozilla but fail in IE7 and IE8 because these browser does not support Placeholder attributes of HTML5.
My form is divided into 4 parts. When user fills the first part and click on save and proceed a trigger is fired on database and it shows second part of form and so on
To achieve placeholder in IE , I have tried various plugins and i also create one of my own but everything fails because the placeholder values save in database if i leave the field blank.
HTML5 placeholder worked fine for me in chrome. So if anyone can provide me the logic of HTML5 placeholder i will write it down in jquery to get a same functionality in IE.
A: You can make a jquery function, that initializes the value of the input to some text when the document is loaded (this should be your placeholder) and then put this value to "" (nothing) when there is an onclick event in the input. Hope it helps
A: Try this JSFiddle.
_selector is a custom variable that I've made. Just change the line to the ID of whatever field you want to put this placeholder on. You can chance the _placeholder to contain whatever placeholder text you want inside the field :).
I just change the css and html properties of the input field on when the user clicks inside it (or outside).
One problem with this technique is that when you post the form, it will think the value's are set (since the value is _placeholder (or "Address" in this example). Your best bet would be to check if the value is equal to your placeholder in the PHP script. If it is you can just tell your script to use "" instead of the var.
A: Going with @Hamdi, you can try jQuery. This is a very good article for that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17990024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sending emails from outlook with Python not working I have been running some code for a while which automates some emails using win32com.client. All has been working for months but today I am getting an error.
import win32com.client
olMailItem = 0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
Today I get the error AttributeError: module 'win32com.gen_py.00062FFF-0000-0000-C000-000000000046x0x9x6' has no attribute 'CLSIDToPackageMap'
If I try "Excel.Application" or "Word.Application" then I don't get an error and Outlook is installed and working on my system. Last week I came across the issue where mail.Bcc and mail.HTMLbody changed to mail.BCC and mail.HTMLBody respectively but I've not found that a change in the string has helped.
Can anyone shed any light on what might be happening?
Thanks in advance.
A: You might have to remove some old files:
# If errors are found, do this
# clear contents of C:\Users\<username>\AppData\Local\Temp\gen_py
# that should fix it, to test it type
import win32com.client
app = win32com.client.gencache.EnsureDispatch("Outlook.Application")
app.Visible = True
This gist also has other solutions that remove the files automatically. Application needs to be adjusted.
1.)
from pathlib import Path
try:
xl = win32.gencache.EnsureDispatch('Excel.Application')
except AttributeError:
f_loc = r'C:\Users\<username>\AppData\Local\Temp\gen_py'
for f in Path(f_loc):
Path.unlink(f)
Path.rmdir(f_loc)
xl = win32.gencache.EnsureDispatch('Excel.Application')
2.)
try:
xl = client.gencache.EnsureDispatch('Excel.Application')
except AttributeError:
# Corner case dependencies.
import os
import re
import sys
import shutil
# Remove cache and try again.
MODULE_LIST = [m.__name__ for m in sys.modules.values()]
for module in MODULE_LIST:
if re.match(r'win32com\.gen_py\..+', module):
del sys.modules[module]
shutil.rmtree(os.path.join(os.environ.get('LOCALAPPDATA'), 'Temp', 'gen_py'))
from win32com import client
xl = client.gencache.EnsureDispatch('Excel.Application')
A: I was having the same issue and managed to resolve it by doing the following
from win32com.client import gencache.py
gencache._Dump()
The _Dump() command will print the location of the cache directory. Deleting the directory resolved the issue for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58267574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can't find resource for bundle java.util I have tow properties files :
config-app.properties
config-dev.properties
and i try to read from the fist witch read also from the second like that :
the java code:
String smtpHostName = ResourceBundle.getBundle("config-app").getString("smtp.host.name");
config-app.properties
smtp.host.name =${smtp.host.name.env}
config-dev.properties
smtp.host.name.env =smtp.gmail.com
but i have that message :
Can't find resource for bundle java.util.PropertyResourceBundle
Edit: Code formatting.
A: This should work, assuming config-app.properties exists in the class path (in the root). You should not get the error "Can't find resource for bundle java.util.PropertyResourceBundle".
However, what you're trying to do, by substituting ${smtp.host.name.env}, will NOT work with ResourceBundle. You would need another library to do something more complicated like that.
UPDATED
It's not clear what you're trying to do, but assuming you want to have profile for developement and another one for production, you could try to do something like this:
Properties defaultProperties = new Properties();
defaultProperties.load(new FileInputStream("config-app.properties"));
Properties properties = new Properties(defaultProperties);
if (isDev()) {
properties.load(new FileInputStream("config-dev.properties"));
} else {
properties.load(new FileInputStream("whatever.properties"));
}
properties.getProperty("smtp.host.name");
This will have default settings in config-app.properties, which can be overwritten in config-dev.properties or whatever.properties as needed. In this case the keep must be the same.
config-app.properties:
smtp.host.name =localhost
config-dev.properties:
smtp.host.name =smtp.gmail.com
One last note, the previous code is loading the files from the filesystem, if you have them in the classpath, use something like :
defaultProperties.load(Classname.class.getClassLoader().getResourceAsStream("config-app.properties"));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25853512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: guild.icon & guild.iconURL() not working in embed thumbnail I want to set guild icon as the thumbnail of embed but neither guild.icon nor guild.iconURL() work
bot.on('message', message => {
if(message.author.bot) return;
if(message.channel.name === 'verify') {
if(message.content === '!verify') {
message.delete()
let dm = message.author;
let server = message.guild.name;
let servericon = message.guild.iconURL();
console.log(servericon)
let attachment = new Discord.MessageAttachment(this.choose , 'chosen.png')
let embed = new Discord.MessageEmbed()
.setTitle(`**Welcome to ${server}**\n\nCaptcha`)
.setDescription("Please complete the captcha given below to gain access to the server.\n**Note:** This is case sensitive")
.setAuthor('Mr.Verifier', "https://i.ibb.co/nckjDjG/hmm.png")
.setThumbnail(servericon)
.addField(
{ name: '**Why all this?**', value: 'This is to protect the servers from\nmalicious raids of automated bots'}
)
.setImage(`attachment://chosen.png`)
dm.send(embed)
}else{
message.delete();
}
};
})
A: You need to use guild.iconURL().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61479351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: semantic versioning Gradle plugin I am looking for a good gradle plugin that might help me manage my versioning better, since I have been relying on custom tasks and manually updating. What are the go-to gradle plugins? I tried looking around on plugins.gradle.com, but there are frankly a ton of different plugins that all seem to do the same thing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70268346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Mobile ci-cd pipeline on jenkins for flutter apps On Windows Machine
while building flutter build apk on jenkins fails archieving the build apk
*/.*apk
some one could me help me on this please?
Need and guidance on that to rectify the problems on
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74401501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RESTful web services on JBoss WildFly 13 works from browser & curl but not from Unit tests - 404 error I have an Application deployed on JBoss WildFly 13.0.0.Final as an EAR running on EE8 on macOS High Sierra 10.13.6. All the methods work fine when called from the Applications web pages.
I can ping successfully 'My IP address', 127.0.0.1 & locahost:
ping 192.999.9.255 PING 192.999.1.255
(192.999.9.255): 56 data bytes 64 bytes from 192.999.1.23: icmp_seq=0
ttl=64 time=0.067 ms 64 bytes from 192.999.1.23: icmp_seq=1 ttl=64
time=0.147 ms 64 bytes from 192.99.1.23: icmp_seq=2 ttl=64 time=0.098
ms
PING 127.0.0.1 (127.0.0.1): 56 data bytes 64 bytes from 127.0.0.1:
icmp_seq=0 ttl=64 time=0.046 ms 64 bytes from 127.0.0.1: icmp_seq=1
ttl=64 time=0.085 ms 64 bytes from 127.0.0.1: icmp_seq=2 ttl=64
time=0.076 ms
PING localhost (127.0.0.1): 56 data bytes 64 bytes from 127.0.0.1:
icmp_seq=0 ttl=64 time=0.041 ms 64 bytes from 127.0.0.1: icmp_seq=1
ttl=64 time=0.084 ms 64 bytes from 127.0.0.1: icmp_seq=2 ttl=64
time=0.090 ms
My usr/hosts is standard:
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
fe80::1%lo0 localhost
I can access one of the web services and display the JSON from curl:
MacBook-Pro:bin NOTiFY$ curl "http://localhost:8080/NOTiFYwell/notifywell/get-all-enumbers/"
[
{
"id": "5b6c5dbefac4f7105b3cca2e",
"code": "E100",
"name": "Curcumin (from turmeric)",
"colour": "Yellow-orange",
"status": "Approved in the EU.Approved in the US."
},
and from the browser:
However when I run my JUnit 5 test:
@Test
public final void test01GetListEnumbers() throws IOException {
System.out.println(">>>>> test01GetListEnumbers .....");
String url = "http://localhost:8080/NOTiFYwell/notifywell/get-all-enumbers/";
System.out.println(">>>>> test01GetListEnumbers url = " + url);
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader(CONTENT_TYPE, APPLICATION_JSON);
//Execute and get the response.
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(httpGet);
System.out.println(">>>>> test01GetListEnumbers response getStatus = " + response.getStatusLine().getStatusCode());
System.out.println(">>>>> test01GetListEnumbers response getEntity = " + EntityUtils.toString(response.getEntity()));
}
I get:
test01GetListEnumbers ..... test01GetListEnumbers url = http://localhost:8080/NOTiFYwell/notifywell/get-all-enumbers/ test01GetListEnumbers response getStatus = 404 test01GetListEnumbers
response getEntity =
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 404 Not Found</title>
</head>
<body><h2>HTTP ERROR 404</h2>
<p>Problem accessing /NOTiFYwell/notifywell/get-all-enumbers/. Reason:
<pre> Not Found</pre></p><hr><a
href="http://eclipse.org/jetty">Powered by Jetty:// 9.4.z-SNAPSHOT</a>
<hr/>
</body>
</html>
In WireShark I see:
3027 26.303256 127.0.0.1 127.0.0.1 HTTP 275 GET
/NOTiFYwell/notifywell/get-all-enumbers/ HTTP/1.1
3028 26.303279 127.0.0.1 127.0.0.1 TCP 56 8080 → 50922 [ACK] Seq=1
Ack=220 Win=408064 Len=0 TSval=635600988 TSecr=635600988
3029 26.304989 127.0.0.1 127.0.0.1 HTTP 652 HTTP/1.1 404 Not Found
(text/html)
All my JUnit test were working on my previous MacBook Pro (July 2018) with WildFly 12.0.0.Final on EE8 & macOS High Sierra 10.13.6. I have recently upgraded to WildFly 13.0.0.Final running on EE8. In both cases my series of Unit Tests accessing my web services used the Apache HTTP Core 4.4.10, Client 4.5.6 JARs.
Tried many of the SO suggestions to no avail.
A: @James R. Perkins
Thanks for pointing me in the right direction. I stopped Wildfly 13 and sure enough, I still had something listening on Port 8080
MacBook-Pro:bin NOTiFY$ sudo lsof -i :8080 Password: COMMAND PID
USER FD TYPE DEVICE SIZE/OFF NODE NAME java 437
NOTiFY 163u IPv6 0x299d8c12df3e5311 0t0 TCP localhost:http-alt
(LISTEN)
Killed the PID and ran my JUnit test again and (as hoped) got:
org.apache.http.conn.HttpHostConnectException: Connect to
localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1,
localhost/fe80:0:0:0:0:0:0:1%1] failed: Connection refused
Restarted WildFly 13 and successfully re-ran my JUnit test:
test01GetListEnumbers url = http://localhost:8080/NOTiFYwell/notifywell/get-all-enumbers/
test01GetListEnumbers response getStatus = 200
test01GetListEnumbers response getEntity = [ {
"id": "5b6c5dbefac4f7105b3cca2e",
"code": "E100",
"name": "Curcumin (from turmeric)",
"colour": "Yellow-orange",
"status": "Approved in the EU.Approved in the US." },
Still not sure where Jetty 9.x has come from.
This corresponds with having to reboot my Mac after I used 'Migration Assistant' to copy everything from my old MacBook to the new. Jetty appears to start on reboot. Will investigate.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52006939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Filter Products by Distribution Center Quantity Channel advisor REST API I am working on a django project in which I am fetching products from Channel Advisor platform using the file export feature. I am using the filter '$filter=ProfileID eq and TotalQuantity gt 0'.
https://developer.channeladvisor.com/working-with-products/product-exports
I would like to query the product based on the value present in 'Qty Avail Warehouse' field present in catalogs listing page instead of 'TotalQuantity'. Or filter by distribution center quantity eg: those products having stock greater than 0 in 'Phoenix' distribution center.
Thank you.
A: The easiest way in my opinion is to override the get_queryset method of your ModelViewSet:
views.py
def BaseAPIView(...):
''' base view for other views to inherit '''
def get_queryset(self):
queryset = self.queryset
# get filter request from client:
filter_string = self.request.query_params.get('filter')
# apply filters if they are passed in:
if filters:
filter_dictionary = json.loads(filter_string)
queryset = queryset.filter(**filter_dictionary)
return queryset
The request url will now look like, for example: my_website.com/api/products?filter={"name":"book"}
Or more precisely: my_website.com/api/products?filter=%7B%22name%22:%22book%22%7D
Which can be built like:
script.js
// using ajax as an example:
var filter = JSON.stringify({
"name" : "book"
});
$.ajax({
"url" : "my_website.com/api/products?filter=" + filter,
"type" : "GET",
...
});
Some advantages:
*
*no need to specify which fields can be filtered on each view class
*write it once, use it everywhere
*front end filtering looks exactly like django filtering
*can do the same with exclude
Some disadvantages:
*
*potential security risks if you want some fields to be non-filterable
*less intuitive front-end code to query a table
Overall, this approach has been far more useful for me than any packages out there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67807386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pass text value to another text I want to build a category list scrollview in android studio using java.
I having truble to understand how to pass value from TextView to anthor TextView with same value in other activity.
activity_first.xml
<TextView
android:id="@+id/PersonName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:textColorHint="@color/black"
android:background="@android:color/transparent"
android:text="Name" />
FirstActivity.java
public class FirstActivity extends AppCompatActivity {
TextView PersonName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
PersonName = (TextView)findViewById(R.id.PersonName);
PersonName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent p = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(p);
}
});
}
}
In second activity i have a scrollview.
activity_second.xml
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Father" />
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Mother" />
</LinearLayout>
</ScrollView>
in activity_second.xml when I press on TextView it will return me with the value Father (id:textView) to the FirstActivity and change the TextView (id:PersonName) to father and if I'll do it with value mother (id:textView2) it will do same action and return me to FirstActivity.
A: You can do it using getExtra method
Google Android getExtra
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
TextView mother,father;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second.xml);
mother = (TextView)findViewById(R.id.textView);
father = (TextView)findViewById(R.id.textView2);
mother.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putString("id", seciliodaid);
bundle.putInt("type", 0);
Intent newIntent;
newIntent = new Intent(SecondActivity.this, FirstActivity.class);
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
}
});
father.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putString("id", seciliodaid);
bundle.putInt("type", 1);
Intent newIntent;
newIntent = new Intent(SecondActivity.this, FirstActivity.class);
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
}
});
}
}
FirstActivity.java
public class FirstActivity extends AppCompatActivity {
TextView PersonName;
Bundle data;
int type=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
PersonName = (TextView)findViewById(R.id.PersonName);
try {
data = getIntent().getExtras();
type = data.getInt("type");
if(type==0){
PersonName.setText("Mother");
}else if(type==1){
PersonName.setText("Father");
}
}catch (Exception e){
}
PersonName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent p = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(p);
}
});
}
}
A: Although you can use Bundle to do so (as another answer suggests), if you just need strings, then you can do the following (which I believe is simpler but it would depend on your implementation):
In button onClickListener of FirstActivity.java:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("Mother", mother.getText().toString());
intent.putExtra("Father", father.getText().toString());
In text view onClickListener of SecondActivity.java:
String mother = getIntent().getStringExtra("Mother");
String father = getIntent().getStringExtra("Father");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68248909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to print local variables of an OpenMP parallel region in gdb? I'm stuck with debugging local variables inside an OpenMP parallel region.
Taking this code in consideration:
#include<omp.h>
#include<stdio.h>
int main(){
int a = 0;
#pragma omp parallel shared(a)
{
int m_a = a + omp_get_thread_num();
printf("%d\n",m_a); //breakpoint set here
}
}
The code runs well, but if I set a breakpoint at the line with the comment and type info locals on gdb, it just shows the a variable. Typing print m_a results on No symbol "m_a" in current context.
A: This answers nothing, just report that I cannot repeat it, the code is compiled with
gcc x.c -W -Wall -fopenmp -ggdb
and gdb session as the following, everything seems fine, I guess it may be related with compile flag, try add -O0 in addition to -g or -ggdb
Reading symbols from ./a.out...done.
(gdb) break 9
Breakpoint 1 at 0x40064d: file x.c, line 9.
(gdb) run
Starting program: /some/path/to/a.out
[Thread debugging using libthread_db enabled]
Thread 3 "a.out" hit Breakpoint 1, main._omp_fn.0 () at x.c:9
9 printf("%d\n",m_a); //breakpoint set here
(gdb) info locals
m_a = 2
a = 0
(gdb) info threads
Id Target Id Frame
1 Thread 0x2aaaaaaebb40 (LWP 31287) "a.out" main._omp_fn.0 () at x.c:9
2 Thread 0x2aaaabab0700 (LWP 31516) "a.out" main._omp_fn.0 () at x.c:9
* 3 Thread 0x2aaaabcb1700 (LWP 31517) "a.out" main._omp_fn.0 () at x.c:9
4 Thread 0x2aaaabeb2700 (LWP 31518) "a.out" main._omp_fn.0 () at x.c:9
(gdb) thread 1
[Switching to thread 1 (Thread 0x2aaaaaaebb40 (LWP 31287))]
#0 main._omp_fn.0 () at x.c:9
9 printf("%d\n",m_a); //breakpoint set here
(gdb) info locals
m_a = 0
a = 0
(gdb) thread 2
[Switching to thread 2 (Thread 0x2aaaabab0700 (LWP 31516))]
#0 main._omp_fn.0 () at x.c:9
9 printf("%d\n",m_a); //breakpoint set here
(gdb) info locals
m_a = 1
a = 0
(gdb)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55128846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Scrolling down to div, while hiding first div, makes the page jump down I've got this JSFiddle
The problem is, when I fade out the first div, the page jumps down - so the scrolling is conflicting with the fade out.
Can anyone help me? Thank you.
$(function(){
setTimeout(function(){
$('html, body')
.css({
'overflow': 'auto'
})
.animate({
scrollTop: $('.second').offset().top
}, 1500);
}, 2000);
return false;
});
setTimeout(function() {
$('.first').fadeOut(0);
}, 3400);
JSFiddle:
http://jsfiddle.net/em9yycj5/10/
A: The timing wasn't really working. The second timeout would have to start after the initial one has finished - or you could interrupt the animation (or both to be sure) :
setTimeout(function(){
$('html, body')
.css({overflow: 'auto'})
.animate({scrollTop: $('.second').offset().top}, 1500);
}, 2000);
setTimeout(function() {
$('.first').hide();
$('html, body').stop().scrollTop($('.second').offset().top);
}, 3400);
http://jsfiddle.net/em9yycj5/16/
Not sure what is meant with 'a click function' in the comment above...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29330669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't login with new LDAP user on Alfresco via CMIS I have an Alfresco Enterprise edition version 5.1.2 running on Java version 1.8.0-65 that uses external LDAP server (OpenLDAP) as a directory server.
Alfresco synchronizes with the LDAP server on startup, and is configured with synchronization settings Auto Create People On Login and Sync Changes Onlyon.
When a new user is created on the LDAP server, and I try to log in with that user trough CMIS, I get an error with the following stacktrace:
The server encountered an internal error that prevented it from fulfilling this request.</u></p><p><b>exception</b> <pre>java.lang.IllegalArgumentException: currentUser is a mandatory parameter
org.alfresco.util.ParameterCheck.mandatoryString(ParameterCheck.java:58)
org.alfresco.module.org_alfresco_module_rm.securitymarks.SecurityClearanceServiceImpl.isClearedFor(SecurityClearanceServiceImpl.java:120)
org.alfresco.module.org_alfresco_module_rm.securitymarks.permission.SecurityMarksPermissionPreProcessor.process(SecurityMarksPermissionPreProcessor.java:115)
org.alfresco.repo.security.permissions.impl.ExtendedPermissionServiceImpl.hasPermission(ExtendedPermissionServiceImpl.java:194)
org.alfresco.repo.security.person.PersonServiceImpl.personExists(PersonServiceImpl.java:530)
org.alfresco.repo.security.sync.ChainingUserRegistrySynchronizer.createMissingPerson(ChainingUserRegistrySynchronizer.java:862)
org.alfresco.repo.management.subsystems.SubsystemProxyFactory$1.invoke(SubsystemProxyFactory.java:79)
org.alfresco.repo.security.authentication.AbstractAuthenticationComponent$FixCurrentUserCallback$1.doWork(AbstractAuthenticationComponent.java:550)
org.alfresco.repo.security.authentication.AbstractAuthenticationComponent$FixCurrentUserCallback$1.doWork(AbstractAuthenticationComponent.java:1)
org.alfresco.repo.tenant.TenantUtil.runAsWork(TenantUtil.java:126)
org.alfresco.repo.tenant.TenantUtil.runAsTenant(TenantUtil.java:95)
org.alfresco.repo.tenant.TenantUtil$1.doWork(TenantUtil.java:69)
org.alfresco.repo.security.authentication.AuthenticationUtil.runAs(AuthenticationUtil.java:555)
org.alfresco.repo.tenant.TenantUtil.runAsUserTenant(TenantUtil.java:65)
org.alfresco.repo.tenant.TenantUtil.runAsSystemTenant(TenantUtil.java:119)
org.alfresco.repo.security.authentication.AbstractAuthenticationComponent$FixCurrentUserCallback.execute(AbstractAuthenticationComponent.java:539)
org.alfresco.repo.security.authentication.AbstractAuthenticationComponent$FixCurrentUserCallback.execute(AbstractAuthenticationComponent.java:1)
org.alfresco.repo.transaction.RetryingTransactionHelper.doInTransaction(RetryingTransactionHelper.java:464)
org.alfresco.repo.security.authentication.AbstractAuthenticationComponent.setCurrentUser(AbstractAuthenticationComponent.java:234)
org.alfresco.repo.security.authentication.AbstractAuthenticationComponent.setCurrentUser(AbstractAuthenticationComponent.java:203)
org.alfresco.enterprise.repo.authorization.AuthorizationInterceptor.checkAuthorization(AuthorizationInterceptor.java:115)
org.alfresco.enterprise.repo.authorization.AuthorizationInterceptor.invoke(AuthorizationInterceptor.java:63)
org.alfresco.repo.security.authentication.AbstractChainingAuthenticationComponent.setCurrentUser(AbstractChainingAuthenticationComponent.java:188)
org.alfresco.repo.webdav.auth.BaseAuthenticationFilter.getSessionUser(BaseAuthenticationFilter.java:260)
org.alfresco.repo.webdav.auth.AuthenticationFilter.doFilter(AuthenticationFilter.java:121)
org.alfresco.repo.management.subsystems.ChainingSubsystemProxyFactory$1.invoke(ChainingSubsystemProxyFactory.java:132)
org.alfresco.repo.web.filter.beans.BeanProxyFilter.doFilter(BeanProxyFilter.java:89)
org.alfresco.web.app.servlet.CmisSecurityContextCleanerFilter.doFilter(CmisSecurityContextCleanerFilter.java:56)
org.alfresco.web.app.servlet.GlobalLocalizationFilter.doFilter(GlobalLocalizationFilter.java:68)
I omitted the lines from the proxy classes and interceptors from the stacktrace for better readability.
The same user is able to login to Alfresco via the web interface, and on subsequent attempts to access Alfresco via CMIS with the same user, Alfresco returns properly.
I have analyzed the stacktrace and the Alfresco sources that are available, and ultimately it fails at org.alfresco.repo.security.authentication.AuthenticationUtil.getRunAsUser() which returns null and the validation fails with the currentUser is a mandatory parameter message.
My expectation is that it should be possible to log in on Alfresco via CMIS since the user already exists, and it is possible to log in with that user on Alfresco via the web interface.
My question is if there are some Alfresco settings that should be updated in order to make this work, if there are additional parameters that should be set to the CMIS request, or it is not possible at all?
A: I cannot reproduce this on Alfresco Community Edition 5.1.f on Linux authenticating against OpenLDAP.
The test steps are:
*
*Validate that authentication works for LDAP users.
*Validate that Apache Chemistry CMIS Workbench can authenticate using LDAP users.
*Add a new user to LDAP (tuser4).
*Validate that I can log in to Share via the new user (tuser4).
*Add another new user to LDAP (tuser5).
*Validate that I can log in via CMIS Workbench using the new user (tuser5).
All of these steps pass.
The CMIS service URL I am using in Workbench is: http://alfresco.local:8080/alfresco/api/-default-/public/cmis/versions/1.1/atom
Make sure yours matches that. It could be the issue.
If your service URL matches, please provide the code you are using to get a session.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47792218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: sapply() on multiple columns of looped-over named variabled I used the assign() function to create 20 data frames and assign them with content using read.csv() and a for loop like follows
data_names=paste0("data_",countries$country)
for (i in 1:dim(data_names)[1])
{
assign(data_names[i], read.csv(file=files[i],
header = TRUE,
sep = ',',
colClasses=rep("character",16),
na.strings='NULL'
))
}
Where countries$country is a vector of 20 different names of countries.
Now, for each of these data frames, I want to convert columns 5 to 14 to integer. Manually, I would do like this:
data_russia [,5:14]<- sapply(data_russia [,5:14],as.integer)
data_belarus [,5:14]<- sapply(data_belarus [,5:14],as.integer)
data_philippines [,5:14]<- sapply(data_philippines[,5:14],as.integer)
data_srilanka [,5:14]<- sapply(data_srilanka [,5:14],as.integer)
data_germany [,5:14]<- sapply(data_germany [,5:14],as.integer)
data_serbia [,5:14]<- sapply(data_serbia [,5:14],as.integer)
data_croatia [,5:14]<- sapply(data_croatia [,5:14],as.integer)
data_libya [,5:14]<- sapply(data_libya [,5:14],as.integer)
data_burma [,5:14]<- sapply(data_burma [,5:14],as.integer)
data_algeria [,5:14]<- sapply(data_algeria [,5:14],as.integer)
data_bosnia [,5:14]<- sapply(data_bosnia [,5:14],as.integer)
data_bulgaria [,5:14]<- sapply(data_bulgaria [,5:14],as.integer)
data_iraq [,5:14]<- sapply(data_iraq [,5:14],as.integer)
data_hungary [,5:14]<- sapply(data_hungary [,5:14],as.integer)
data_greece [,5:14]<- sapply(data_greece [,5:14],as.integer)
data_usa [,5:14]<- sapply(data_usa [,5:14],as.integer)
data_vietnam [,5:14]<- sapply(data_vietnam [,5:14],as.integer)
data_ukraine [,5:14]<- sapply(data_ukraine [,5:14],as.integer)
data_france [,5:14]<- sapply(data_france [,5:14],as.integer)
data_egypt [,5:14]<- sapply(data_egypt [,5:14],as.integer)
How would you perform the same action sequentially over the names of countries?
Thanks in Advance for your pieces of advice!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59181219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to write multidimensional vector data to a file in C++ I have a vector of objects obj (of class Holder) with N elements with members like x and y which are also vectors of double type with M elements. I would like to write a text file creating an MxN matrix from this. I have tried lots of different things to no avail up to now.
vector<Holder> obj(N);
void savedata(string filename, vector<Holder> obj, int M, int N) {
ofstream out(filename);
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
out << obj[i][j] << "\t" << endl;
}
}
}
But this just takes the last set of values. How can I create such an MxN matrix where rows are from the object member vector x and columns are from the object vector itself?
Thank you in advance.
--
The bigger version of the code is as follows:
//
//
#include <iostream>
#include <cmath>
#include <fstream>
#include <string>
#include <vector>
#include <random>
using namespace std;
typedef vector< vector<double> > Matrix;
// Particles making up the cell
class Particle{
public:
double x; // x position
double y; // y position
double vx; // velocity in the x direction
double vy; // velocity in the y direction
double Fx; // force in the x direction
double Fy; // force in the y direction
// Default constructor
Particle()
: x(0.0),y(0.0),vx(0.0),vy(0.0),Fx(0.0),Fy(0.0){
}
};
// Holder for storing data
class HoldPar{
public:
vector<double> x;
vector<double> y;
vector<double> vx;
vector<double> vy;
// Default constructor
HoldPar()
: x(0.0),y(0.0),vx(0.0),vy(0.0){
}
// Add elements to vectors
void add_Xelement(double a) {
x.push_back(a);
}
void add_Yelement(double a) {
y.push_back(a);
}
void add_VXelement(double a) {
vx.push_back(a);
}
void add_VYelement(double a) {
vy.push_back(a);
}
};
int main() {
// Initialization of x, v and F
const float pi = 3.14;
int N = 30; // Number of 'particles' that make up the cell
float theta = 2*pi/N; // Angle between two particles in radians
float x0 = 0; // Center of the cell [x]
float y0 = 0; // Center of the cell [y]
float R = 5e-6; // Radius of the cell
vector<Particle> particles(N); // particles
// Assigning the initial points onto the circle
for(int i = 0; i < N; i++) {
particles[i].x = x0 + R*cos(theta*i);
particles[i].y = y0 + R*sin(theta*i);
}
float k = 4.3e-7; // Spring constant connecting the particles
float m = 2e-8; // Mass of the particles
// Calculating the initial spring force between the particles on the cell
particles[0].Fx = -k*(particles[1].x - particles[N].x);
particles[0].Fy = -k*(particles[1].y - particles[N].y);
for(int i = 1; i < N-1; i++) {
particles[i].Fx = -k*(particles[i+1].x - particles[i-1].x);
particles[i].Fy = -k*(particles[i+1].y - particles[i-1].y);
}
particles[N].Fx = -k*(particles[0].x - particles[N-1].x);
particles[N].Fy = -k*(particles[0].y - particles[N-1].y);
// Initial velocities are given to each particle randomly from a Gaussian distribution
random_device rdx; // Seed
default_random_engine generatorx(rdx()); // Default random number generator
random_device rdy; // Seed
default_random_engine generatory(rdy()); // Default random number generator
normal_distribution<float> distributionx(0,1); // Gaussian distribution with 0 mean and 1 variance
normal_distribution<float> distributiony(0,1); // Gaussian distribution with 0 mean and 1 variance
for(int i = 0; i < N; i++) {
float xnumber = distributionx(generatorx);
float ynumber = distributiony(generatory);
particles[i].vx = xnumber;
particles[i].vy = ynumber;
}
// Molecular dynamics simulation with velocity Verlet algorithm
// 'Old' variables
vector<Particle> particles_old(N);
for(int i = 0; i < N; i++) {
particles_old[i].x = particles[i].x;
particles_old[i].y = particles[i].y;
particles_old[i].vx = particles[i].vx;
particles_old[i].vy = particles[i].vy;
particles_old[i].Fx = particles[i].Fx;
particles_old[i].Fy = particles[i].Fy;
}
// Sampling variables
int sampleFreq = 2;
int sampleCounter = 0;
// MD variables
float dt = 1e-4;
float dt2 = dt*dt;
float m2 = 2*m;
int MdS = 1e+5; // Molecular dynamics step number
// Holder variables
vector<HoldPar> particles_hold(N);
// MD
for(int j = 0; j < MdS; j++) {
// Update x
for(int i = 0; i < N; i++) {
particles[i].x = particles_old[i].x + dt*particles_old[i].vx + dt2*particles_old[i].Fx/m2;
particles[i].y = particles_old[i].y + dt*particles_old[i].vy + dt2*particles_old[i].Fy/m2;
}
// Update F
particles[0].Fx = -k*(particles[1].x - particles[N].x);
particles[0].Fy = -k*(particles[1].y - particles[N].y);
for(int i = 1; i < N-1; i++) {
particles[i].Fx = -k*(particles[i+1].x - particles[i-1].x);
particles[i].Fy = -k*(particles[i+1].y - particles[i-1].y);
}
particles[N].Fx = -k*(particles[0].x - particles[N-1].x);
particles[N].Fy = -k*(particles[0].y - particles[N-1].y);
// Update v
for(int i = 0; i < N; i++) {
particles[i].vx = particles_old[i].vx + dt*(particles_old[i].Fx + particles[i].Fx)/m2;
particles[i].vy = particles_old[i].vy + dt*(particles_old[i].Fy + particles[i].Fy)/m2;
}
// Copy new variables to old variables
for(int i = 0; i < N; i++) {
particles_old[i].x = particles[i].x;
particles_old[i].y = particles[i].y;
particles_old[i].vx = particles[i].vx;
particles_old[i].vy = particles[i].vy;
particles_old[i].Fx = particles[i].Fx;
particles_old[i].Fy = particles[i].Fy;
}
// Store variables
if(j % sampleFreq == 0) {
for(int i = 0; i < N; i++) {
particles_hold[i].add_Xelement( particles[i].x );
particles_hold[i].add_Yelement( particles[i].y );
particles_hold[i].add_VXelement( particles[i].vx );
particles_hold[i].add_VYelement( particles[i].vy );
}
sampleCounter += 1;
}
}
//* End of molecular dynamics simulation
}
//
//*
//
Essentially I'm trying to write a txt file where particles_hold elements (from 1 to N) are columns and members of particles_hold elements like x (from 1 to some value M) are rows.
A: If you mean visually then the way is put endl or "\n" to the outer loop and remove endl from inner loop.But i do not know anythig about your Holder object and if you have [] operator defined there that is the answer.
vector<Holder> obj(N);
void savedata(string filename, vector<Holder> obj, int M, int N) {
ofstream out(filename);
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
out << obj[i][j] << "\t";
}
out<< "\n";
}
}
A: Your method is ok, however, made some minor change so that you have M lines, each lines represent obj[i], i = 0.. M-1. So, each column (jth index) is printed as tab separated in each line
vector<Holder> obj(N);
void savedata(string filename, vector<Holder> obj, int M, int N) {
ofstream out(filename);
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
out << obj[i][j] << "\t";
}
out << endl;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25974034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Accessing AdvertisingIdClient in Play Services 9.2.1 I added play-services-ads-lite to my project, but apparently it doesn't contain
com.google.android.gms.ads.identifier.AdvertisingIdClient.
which of the following libraries do I have to include?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38662987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Creating your own TTS function with custom voice? So there are some programs out there that allow you to clone your own voice and use it for TTS, but I want to use this custom TTS within my own code. How would I go about it?
I did research some but it's hard to know where to start.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74353678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mule HTTP parameter I created a service where you call the mule service via http:
<http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8086" path="idnum" doc:name="HTTP"/>
so if you want to call this service you type:
http://localhost:8086/idnum
but what i want is for the http to accept an id number as a parameter and then store the id number into a variable so that i can use the id number. So the http would look like:
http://localhost:8086/idnum/4583948364094 for example.
So my question is how do you get the parameter from the url
A: From Mule-3.6 on wards, we have HTTP Listener Connector, using which you can pass URI parameters.
You can access the URI parameters using the below MEL
#[message.inboundProperties.'http.uri.params'.id] provided your URI should be like this: http://localhost:8086/idnum/{id}
A: You need to put the id as a message inbound parameter as following .. In Mule flow you need to do the following :-
<flow name="test">
<http:inbound-endpoint exchange-pattern="request-response"
host="localhost" port="8086"
path="idnum" doc:name="HTTP"/>
<!-- storing id in variable myId -->
<set-variable variableName="myId"
value="#[message.inboundProperties['id']]"
doc:name="Variable"/>
<!-- Print the variable in console -->
<logger level="INFO" message="My id :- #[flowVars['myId']]"/>
</flow>
Now in browser access
http://localhost:8086/idnum/?id=4583948364094
Now you can store it in a variable in Mule and you can see it in a logger like:
My id :- 4583948364094
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25929687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to do multi-language regex for a SPA routing in laravel? im using vue and laravel to do SPA application.
in my app im using vue-router in history mode, and its works like magic.
to make my SPA work properly even when you refresh a page im using:
Route::get('/{vue?}', function() {
return view('main');
})->where('vue', '[\/\w\.-]*');
and it works, but, only in english.
when im trying to use Hebrew in my URL, its not working.
i thing the problem is the regex im using
please help me, thanks !
A: You can use
'[\x{0590}-\x{05FF}\/\w.-]*'
It matches zero or more chars defined inside [...], a character class:
*
*\x{0590}-\x{05FF} - a range of Unicode code points that constitute a Hebrew character range
*\/ - a literal forward slash
*\w- word chars, i.e. ASCII letters, digits and an underscore
*. - a dot
*- - a hyphen.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45880312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Mapping Super Keys to Control in xorg.conf? I've been attempting to switch my super and control keys in X on a macbook and have been half successful. I'd like to avoid creating a custom .Xmodmap if possible, as there is a temporary 100% cpu bug that pops up every time the custom map is loaded.
After some diging, I ended up putting Option "XkbOptions" "altwin:ctrl_win" in my 01-keyboard-layout.conf file which has gotten me halfway there: for eg, left command now maps to 133 Control_L.
However, the control keys remain the same. Left control, for eg still maps to 37 Control_L.
Looking through evdev.lst (and a bunch of googling) turned up no relevant XkbOption for turning control keys into supers, and now i'm pretty stuck.
Any ideas?
A: Ok, I did finally get this to work.
First, these two resources are amazing for anyone wanting to delve into this mess:
http://madduck.net/docs/extending-xkb/
&
http://www.charvolant.org/~doug/xkb/html/index.html
For anyone specifically trying to do this switchover, this is what I did:
1) create a file in /usr/share/X11/xkb/symbols for your new mapping
2) put this in it:
// Control is SWAPPED with Win-keys
partial modifier_keys
xkb_symbols "cmd_n_ctrl" {
key <LWIN> { [ Control_L ] };
key <RWIN> { [ Control_R ] };
key <LCTL> { [ Super_L ] };
modifier_map Control { <LWIN>, <RWIN> };
modifier_map Mod4 { <LCTL> };
};
3: edit evdev in /usr/share/X11/xkb/rules to include:
altwin2:cmd_n_ctrl = +altwin2(cmd_n_ctrl)
(under the option = symbols section)
4: add your new option to evdev.lst (same dir):
altwin2:cmd_n_ctrl
(under the option section)
5: now edit your 01-Keyboard conf file to include the new option that you've created. Mine looks like this:
Section "InputClass"
Identifier "keyboard-layout"
Driver "evdev"
MatchIsKeyboard "yes"
Option "XkbLayout" "us, ru, ca, fr"
Option "XkbOptions" "altwin2:cmd_n_ctrl"
EndSection
6: reboot and you should be good to go.
The above resources are way better at explaining all of this, or any snags you might run into. There is probably a much better way to do this (probably not altering the contents of /usr/share), but so far, this is what got me up and running.
Hope that helps someone else stuck in this spot!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14094456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: PHPUnit "no test executed" when I make a coverage report, in Laravel I triying to make a report of a coverage of my tests and I cant because when I execute the follow command:
phpunit --coverage-html C:\Users\user\report.html
I get the follow error:
PHPUnit 3.7.21 by Sebastian Bergmann.
Configuration read from C:\xampp\htdocs\dynamic_form\phpunit.xml
Time: 0 seconds, Memory: 6.00Mb
No tests executed!
Generating code coverage report in HTML format ... done
I using the phpunit.xml that comes by default in Laravel.
What can be the problem?
Thanks
EDIT:
I add the forceCoversAnnotation="false" attribute and the problem persits.
A: In Laravel unit tests are located inside tests folder and they have some rules in naming in order to run them.
I had the same issue in the past and this is how i solved it:
1) Namespace must be Test\Unit (or if you have a middle folder include that but always inside Tests)
2) the name of the function you build must start with the word test like
public function testMyFunction()
{
// Put your code here
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60528708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Way around getting "ON" value overwritten when writing LEFT JOINs with same column name Whenever I have two tables I want to join where some of the rows will have matches and some won't, I can't figure out how to get around the issue of the column I'm using for the ON condition getting overwritten with '' when it doesn't have a match.
Here is an example query:
SELECT * FROM kickstarter
LEFT JOIN user_kick_ratings
ON kickstarter.project_id=user_kick_ratings.project_id
WHERE rating>=1
Now wherever there is a row from 'kickstarter' where there isn't a matching row from user_kick_ratings, the project_id gets overwritten to ''. The only ways around this I know right now are a) make the id column names different or b) name aliases in the column select area which would force me to name every column I need, which is a lot.
I don't like either of those options, optimally. Is there a way I can use a different type of join or rearrange my query so that the project_id from the main table (kickstarter) is always there?
edit: I'll add that I DO need every row from 'kickstarter' that matches the query, but that there won't always be a corresponding row for the second table, if that wasn't already clear.
A: The cause of this has to do with the order of query execution. The query will first join all rows (regardless of a match, since it's a left join) and then it will filter out rows that don't meet the condition rating >= 1, effectively dropping any rows that didn't have a match in the first place.
To correct this, you need to change your join to only join when rating >= 1. This way, you can still get all rows from the first table, and only get matches from the second table that you need. Try this:
SELECT *
FROM kickstarter k
LEFT JOIN user_kick_ratings ukr
ON k.project_id = ukr.project_id AND ukr.rating >= 1;
As far as the overwritten id, you should instead rewrite your query to only select relevant columns. There's no need to select project_id from both tables, since they are always the same. You should select it from the table that is guaranteed to have a value; In this case, kickstarter:
SELECT k.project_id, k.stuff, ukr.rating
FROM ...
A: Figured it out, and it's so simple! Just use RIGHT JOIN and flip the table order. Even though it's simple, I hope this helps someone one day.
SELECT * FROM user_kick_ratings
RIGHT JOIN kickstarter
ON kickstarter.project_id=user_kick_ratings.project_id
WHERE rating>=1
A: For simple cases:
Instead of doing a SELECT *, you can use
SELECT table2.*, table1.* -- notice the reverse order!
FROM table1
LEFT JOIN table2 .....
They overwrite each other in the order of reference.
So now you got the id from table1.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33529034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Shortcut for "my_var.condition ? statement : my_var" I have this statement :
username.blank? ? firstname : username
There is a shortcut or a way to avoid repeating 'username' ?
A: As it seems you're using ActiveSupport, there is simple way to do this:
username.presence || firstname
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22683338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Detecting CDROM media removal/insertion in Linux Is there a clean way to detect or receive events when a user inserts or removes a CD on a Linux platform?
A: Udev monitors hardware and forwards events to dbus. You just need some dbus listener. A quick check using the dbus-monitor tool shows this in my system:
dbus-monitor --system
signal sender=:1.15 -> dest=(null destination) serial=144 path=/org/freedesktop/UDisks; interface=org.freedesktop.UDisks; member=DeviceChanged
object path "/org/freedesktop/UDisks/devices/sr0"
This is the DeviceChanged event from Udisks, and the device path is included.
So, in whatever programming language you want that supports dbus bindings you can listen for those (system bus) events.
A: Traditionally there has been HAL (Hardware Abstraction Layer) for this, but the web page says
HAL is in maintenance mode - no new
features are added. All future
development focuses on udisks, UPower
and other parts of the stack. See
Software/DeviceKit for more
information.
and the DeviceKit page lists
udisks, a D-Bus interface for dealing with storage devices
So udisks should probably be what you are asking for.
A: The best way I was able to find was Halevt. Halevt is apparently a higher level abstraction than using HAL directly. It uses an XML based configuration file that may or may not be to your liking. The configuration file properties documentation is somewhat lacking. A list of all the supported properties are listed here:
http://www.marcuscom.com/hal-spec/hal-spec.html
Also, the link to Halevt: http://www.nongnu.org/halevt/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5112298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Only arrow functions in eslint? I prefer this:
const foo = x => x + 1;
to this:
function foo(x) {
return x + 1;
}
Is there an eslint rule to enforce this?
A: You can use ESLint's built-in no-restricted-syntax rule to disallow the FunctionExpression and FunctionDeclaration AST nodes:
{
"rules": {
"no-restricted-syntax": [
"error",
"FunctionExpression",
"FunctionDeclaration"
]
}
}
This doesn't explicitly "prefer" arrow functions, but if you disallow all ArrowFunctionExpression alternatives, then you effectively enforce arrow functions only.
With the above rule, these fail:
// VariableDeclaration containing a FunctionExpression
const f1 = function () {}
// FunctionDeclaration
function f2() {}
class C {
// MethodDefinition containing a FunctionExpression
m() {}
}
These pass:
// VariableDeclaration containing an ArrowFunctionExpression
const f = () => {}
class C {
// PropertyDefinition containing an ArrowFunctionExpression
m = () => {}
}
If you want to allow FunctionExpression and FunctionDeclaration nodes when they reference this or when they are generator functions (there's no such thing as an arrow generator function currently), then you can use esquery syntax to specifically disallow those nodes when they don't have a ThisExpression node as a descendant and they aren't generator functions:
{
"rules": {
"no-restricted-syntax": [
"error",
"FunctionExpression[generator=false]:not(:has(ThisExpression))",
"FunctionDeclaration[generator=false]:not(:has(ThisExpression))"
]
}
}
With the above rule, these fail:
// VariableDeclaration containing a FunctionExpression
const f1 = function () {}
// FunctionDeclaration
function f2() {}
class C {
// MethodDefinition containing a FunctionExpression
m() {}
}
These pass:
// VariableDeclaration containing a FunctionExpression containing a ThisExpression
const f1 = function () {
this.x = 42
}
// VariableDeclaration containing a FunctionExpression[generator=true]
const f2 = function* () {}
// FunctionDeclaration containing a ThisExpression
function f3() {
this.x = 42
}
// FunctionDeclaration[generator=true]
function* f4() {}
// VariableDeclaration containing an ArrowFunctionExpression
const f5 = () => {}
class C {
// MethodDefinition containing a FunctionExpression containing a ThisExpression
m1() {
this.x = 42
}
// MethodDefinition containing a FunctionExpression[generator=true]
*m2() {}
// PropertyDefinition containing an ArrowFunctionExpression
m3 = () => {}
}
Unfortunately, the function f in the following example is also allowed even though it could be rewritten as an arrow function:
function f() {
function g() {
this.x = 42
}
return g
}
I wasn't able to come up with an esquery selector that includes functions like f while excluding functions like g.
A: You can use this ESLint prefer-arrow-callback rule which would flag with error/warning anywhere you could use an arrow function instead of a function expression
A: Anser based on @JohannesEwald comment and @KevinAmiranoff answer.
I'm using the following rules:
https://www.npmjs.com/package/eslint-plugin-prefer-arrow
https://eslint.org/docs/rules/prefer-arrow-callback
https://eslint.org/docs/rules/func-style
npm install -D eslint-plugin-prefer-arrow
.eslintrc or package.json with eslintConfig:
"plugins": [
"prefer-arrow"
],
"rules": {
"prefer-arrow/prefer-arrow-functions": [
"error",
{
"disallowPrototype": true,
"singleReturnOnly": false,
"classPropertiesAllowed": false
}
],
"prefer-arrow-callback": [
"error",
{ "allowNamedFunctions": true }
],
"func-style": [
"error",
"expression",
{ "allowArrowFunctions": true }
]
}
I think this works really well. If you need to disable the rules for a specific line I do it like this:
// eslint-disable-next-line func-style, prefer-arrow/prefer-arrow-functions
A: allow only arrow function guide
you can refer this.
in the .eslintrc.json file enter these in the rules section:
"react/function-component-definition": [2, { "namedComponents":
"arrow-function" }]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52669325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: Google Maps: KML Icon elements not showing up today, worked last week A simple KML file that maps.google.com displayed properly last week not longer displays the Icon elements. Segments are showing up as before, but no Icons. The Icons are showing up in the detail panel but not on the map. Could Google have updated their JS and broken me?
A: @ManoMarks: Things are getting worse.
Browse his file again or e.g., my http://maps.google.com/maps?q=http:%2F%2Fjidanni.org%2Flocation%2Fzaokeng.kmz
Unclicking boxes in the LEFT panel no longer turns off that layer!
They used to turn on and off what they referred to, that is why they are clickable checkboxes.
Now they don't work on any KML map anywhere! (Broken now in Google Maps, but still works OK in Google Earth though.)
Furthermore, e.g., turning on the (panoramio) photo layer in the RIGHT pull down menus loses the LEFT panel's menus for
the rest of the session no matter what.
In conclusion viewing KML files in Google Maps is now at an all time bug threatened low!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10807767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: populating object data from flaskSQLAlchemy into wtfforms fields I'm trying to populate data from User model like username and email into the form so the the admin can update them using the user_id passed in the route to query the user. But i'm doing a custom validation in the form to check if the field didn't change so it won't raise an error that username is taken.
Currently i'm using g global variable offered by Flask to match the user obj data queried in the route to be passed in the form validation function. Any way i can do this better ??
Below is the code for the Form:
class UpdateUserForm(FlaskForm):
username = StringField("Username", validators=[DataRequired()])
email = StringField("Email", validators=[DataRequired(), Email()])
status = SelectField("Account Status", choices=[(True, "Verified"), (False, "Not Verified")], coerce=bool, validators=[InputRequired()])
submit = SubmitField("Update")
def validate_username(self, username):
if username.data != g.username:
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError("That username is taken, please choose a different one.")
def validate_email(self, email):
if email.data != g.email:
user = User.query.filter_by(email=email.data).first()
if user:
raise ValidationError("That email is taken, please choose a different one.")
This is the code for the route:
admin.route("/admin_panel/update_user/<int:user_id>", methods=['GET', 'POST'])
@admin_login_required
def update_user(user_id):
user = User.query.filter_by(id=user_id).first()
g.username = user.username
g.email = user.email
updateUserForm = UpdateUserForm()
updateUserForm.username.data = user.username
updateUserForm.email.data = user.email
print("this is first one" + str(updateUserForm.status.data))
if updateUserForm.validate_on_submit():
user.username = updateUserForm.username.data
user.email = updateUserForm.email.data
user.verified = updateUserForm.status.data
print("this is second one" + str(updateUserForm.status.data))
db.session.commit()
flash("Account updated!", 'success')
return redirect(url_for('admin.admin_panel'))
return render_template("admin/update_user.html", title="Update User", updateUserForm=updateUserForm)
Not that i can't use current user as that the admin logged in
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58711133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Set up and connect to local SQLEXPRESS database using SQL Server Management Studio 2008 r2 and adodbapi For testing purposes, I am attempting to setup a SQL Server database on my local machine and connect to it using adodbapi in Python. I used SQL Server Management Studio 2008 r2 to create a database and table. I enabled the SQL Server Browser service, but I am still unable to connect using adodbapi. Using this connections string:
adodbapi.connect(r'Provider=SQLOLEDB;Data Source=COMPUTERNAME.\SQLEXPRESS;Initial Catalog=Test;User ID=userName; Password=password;')
I get the following error:
Traceback (most recent call last): File "", line
1, in File
"C:\Python26\ArcGIS10.0\lib\site-packages\adodbapi\adodbapi.py", line
307, in connect
raise OperationalError(e, "Error opening connection: " + connection_string) OperationalError: (com_error(-2147352567,
'Exception occurred.', (0, u'Microsoft OLE DB Provider for SQL
Server', u'[DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not
exist or access denied.', None, 0, -2147467259), None), 'Error opening
connection: Provider=SQLOLEDB;Data Source=COMPUTERNAME.\SQLEXPRESS;Initial
Catalog=Test;User ID=userName; Password=password;')
Any insight into what I'm missing?
A: I did a little more digging around and I ended up haphazardly stumbling on the answer. I was missing "Integrated Security=SSPI" in my connection string and it turns out I didn't need the dot before "\SQLEXPRESS" in my data source. Here's the connection string that worked for me:
adodbapi.connect(r'Provider=SQLOLEDB;Data Source=COMPUTERNAME\SQLEXPRESS;Initial Catalog=Test;User ID=COMPUTERNAME\USERNAME; Password=PASSWORD;Integrated Security=SSPI')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13535822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Kotlin callbackFlow awaitClose trigger problem when delay I couldn't understand something about callbackFlow. I have two implementation. There is only difference both of them is using delay or any other suspend function which includes delay. When I run 1. implementation, awaitClose block doesn't run but there is no problem when run the 2. implementation. Coroutine was canceled when I call the first function and in my code implementation needs first call.
I believe there is a logical explanation about that but I couldn't solve it.
1. Implementation
val callbackFlow = callbackFlow {
send("Value")
delay(100)
awaitClose { println("Channel was closed") }
}
val firstValue = callbackFlow.first()
println(firstValue)
2. Implementation
val callbackFlow = callbackFlow {
send("Value")
awaitClose { println("Channel was closed") }
}
val firstValue = callbackFlow.first()
println(firstValue)
A: Flow.first() cancels the flow once the first value has been collected.
In your case, it means that the awaitClose function is never reached.
*
*The call to callbackFlow.first() triggers flow collection
*The send("value") transmit value to the collector
*The collector cancels the flow
*Then, depending on your implementation
*
*The delay might have start, and is cancelled along the flow. The "awaitClose" function is never reached.
*Without delay, there's a chance that 'awaitClose' might register the lambda (and therefore execute it) faster than the collector cancels the flow.
Note however, I'm not sure that the awaitClose is always reachable, even without delay. More research would be needed to give a definitive answer for that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73501193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Vertical Alignment - Foundation 5 - Simple Javascript I've used the technique explained here (js.fiddle link) to achieve vertical alignment for a section on my page.
The problem I have is that I would like to re-use this same technique on a different part of my page.
At the moment this works, but obviously the height of the first instance is then applied to a completely unrelated section somewhere else, and the vertical alignment is not achieved. Could someone help me with modifying the js (maybe using 'this'?) to allow the use of the same code to apply the height to different elements in different parts of my page?
Or do I have to duplicate this code with different var/class names each time I want to use it?
Code snippets below
HTML
<div class="row row_v_align">
<div class="small-3 columns column_v_align">
<div class="v_align"><img src="spade.png"></div>
</div>
<div class="small-9 columns">
<h3>Title</h3><p>Content</p>
</div>
</div>
<div class="row row_v_align">
<div class="small-3 columns column_v_align">
<div class="v_align"><img src="bullsEye.png"></div>
</div>
<div class="small-9 columns">
<h3>Title</h3><p>Content.</p>
</div>
</div>
CSS
.row_v_align {
display: table;
}
.v_align {
display: table-cell;
vertical-align: middle;
}
JS
$(window).on("resize", function () {
var rowHeight = $(".row_v_align").height();
console.log(rowHeight);
$(".column_v_align").height(rowHeight);
$(".v_align").height(rowHeight);
}).resize();
A: I tested code below with fiddle you linked.
$(document).ready(function(){
$(".row").each(function(){
var rowHeight = $(this).height();
console.log(rowHeight);
$(".column", this).height(rowHeight);
$(".v_align", this).height(rowHeight);
});
});
So for you this should work:
$(window).on("resize", function () {
$(".row_v_align").each(function(){
var rowHeight = $(this).height();
console.log(rowHeight);
$(".column_v_align", this).height(rowHeight);
$(".v_align", this).height(rowHeight);
});
}).resize();
*
*each() run function for every matched element
*$("...", this) makes sure that changes are made inside current row
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20938696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JS Accordion open first tab by default I want to open first tab by default on my accordion. I have been trying different solutions, but nothing worked for me.
Here is my JS and HTML:
$('.accordion').each(function () {
var $accordian = $(this);
$accordian.find('.accordion-head').on('click', function () {
$(this).parent().find(".accordion-head").removeClass('open close');
$(this).removeClass('open').addClass('close');
$accordian.find('.accordion-body').slideUp();
if (!$(this).next().is(':visible')) {
$(this).removeClass('close').addClass('open');
$(this).next().slideDown();
}
});
});
<div class="accordion">
<div class="accordion-head">
Title here <div class="arrow down"></div>
</div>
<div class="accordion-body">
copy goes here
</div>
<div class="accordion-head">
Title here <div class="arrow down"></div>
</div>
<div class="accordion-body">
copy goes here
</div>
<div class="accordion-head">
Title here <div class="arrow down"></div>
</div>
<div class="accordion-body">
copy goes here
</div>
</div>
Please help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30230134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: MVC partialview not showing session variable When I load the edit.cshtml view a Session["Order_Number"] is being set in the controller and passed to the View. For some reason this session variable is not be passed to partialview.
Getting error: The name 'ordernumber' does not exist in the current context
Edit.cshtml
@{
var ordernumber = (int)Session["Order_Number"];
}
<div id="tabs">
<ul class="nav nav-tabs">
<li class="active"><a href="#tabs-1">General</a></li>
<li><a href="#tabs-2">Item</a></li>
<li><a href="#tabs-3">Total</a></li>
</ul>
<div id="tabs-1">
@{Html.RenderPartial("_Partial_General_Tab");}
</div>
<div id="tabs-2">
@{Html.RenderPartial("_Partial_Item_Tab");}
</div>
<div id="tabs-3">
Content for Tab 3 goes here.<br />
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#tabs").tabs();
});
</script>
_Partial_General_Tab.cshtml
@model Mvc5.Models.ORDERMetadata
@using (Html.BeginForm("Edit", "Order"))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
// Set New Order Number
@Html.HiddenFor(model => model.Order_Number, new { @Value = ordernumber }) <====== Error Here!!!!!!
<div class="panel panel-default">
<div class="panel-body">
<div class="row">
<div class="col-lg-3">
@Html.LabelFor(model => model.Order_Type)
</div>
<div class="col-lg-9">
<div id="combo_OrderTypes"></div>
@Html.HiddenFor(model => model.Order_Type, new { id = "ordertype" })
</div>
</div>
<button id="editorder" type="submit" class="btn btn-default">Save</button>
</div>
</div>
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27819684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Indeed API search for particular company I am developing a job portal and using the Indeed API.
In my request to the Indeed API I am using following parameters to search:
$params = array(
"q" => $query,
"co" => $country,
"jt" => $jt,
"salary" => $salary,
"start" => $start,
"limit" => $limit,
"userip" => $ipaddress,
"useragent" => $user_agent
);
$results = $client->search($params);
Now I want to make a more specific search. For example,
I want to search for particular company like Facebook, Microsoft etc
and want to add an advanced search feature "With these words in the title".
How can I add these two parameters to the search? These filters are not listed in the search parameters of the Indeed API specification.
A: FYI: indeed has discontinued their API.
I am posting this here because their website still lists it as active but when one tries to get a publisher id one gets redirected to an unrelated page without any explanation. After some time I called indeed and they told me it was discontinued.
Hopefully this saves other people time from trying to figure out what they are doing wrong in trying to get a publisher id.
A: when we try to do advance serch in indeed, like for company "facebook" than on result page we get in search box some thing like "company:Facebook".
So using this format in q parameter we can search that and to add other parameter also simple add space and that parameter in advance search.
like for company and title it will be like this
q="company:facebook title:Executive Assistant"
This will work for advance search, don't use url parameter like as_cmp and all it is not working.
A: I can't comment yet, so posting here. In case it is of use, here is the helpful reply I received from Indeed support. Thank you Indeed!
Hello,
Thank you for your interest in Indeed.
You can utilize our Advanced Search to create a targeted q value for your API calls. You can do this here: http://www.indeed.com/advanced_search? Add your criteria, press search then add the q value located in the 'What" box to your API calls. Please note, the more targeted search the less results.
For example: Here, I entered the "with these words in the title" junior developer and "company" IBM and received 3 results:
http://api.indeed.com/ads/apisearch?publisher=yourpublishernumber&q=title:(Junior%20Developer)%20company:IBM&l=&sort=&radius=&st=&jt=&start=&limit=&fromage=&filter=&latlong=1&co=us&chnl=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2
In this example, I used the selection "With all of these words" with junior developer and company "IBM" and received 28 results:
http://api.indeed.com/ads/apisearch?publisher=yourpublishernumber&q=Junior%20Developer%20company:IBM&l=&sort=&radius=&st=&jt=&start=&limit=&fromage=&filter=&latlong=1&co=us&chnl=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2
Please give this a try and let me know if it doesn't meet your needs.
Thank you,
Indeed Support Team
Indeed - How the World Works.™
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37592883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Django - inclusion tag In my html, there is a div containing all the comments. I need to restrict the amount of comments to be shown. So, I created an inclusion tag:
<div class="past_comments">
{% limit_amount_in_a_page page_nr=page_nr topic_id=topic.id amount=4 %}
</div>
@register.inclusion_tag('post/comment_block.html')
def limit_amount_in_a_page(page_nr, topic_id=1, amount=5):
topic = get_object_or_404(Topic, id=topic_id)
comments = Comment.objects.filter(topic=topic)
selected_comments = []
starting_index = page_nr*amount
for index in range(starting_index, starting_index + amount):
if index >= len(comments):
break;
selected_comments.append(comments[index])
return {
'topic': topic,
'page_nr': int(page_nr),
'selected_comments': selected_comments,
'amount_comments': comments.all().count(),
'limit_amount_comment': amount,
}
so, this tag shows the code from comment_block.html
{% load static %}
{% load post_tags %}
{% load post_filters %}
{% for comment in selected_comments %}
<div class="comment_body">
<div class="user_info_block">
<div class="content">
<div class="photo_profile"></div>
<div class="user_info"></div>
</div>
</div>
<div class="content_block">
<p>{{comment.content}}</p>
</div>
</div>
{% endfor %}
topic id is {{topic.id}}
page nr is {{page_nr}}<br>
comment amount is {{amount_comments}}<br>
limit amount is {{limit_amount_comment}}<br>
{% if page_nr != 0 %}
<a href="{% url 'post:detail' topic.id page_nr|increase:-1 %}">Previous Page</a>
{% endif %}
{%page_not_over_amount page_nr amount_comments limit_amount_comment%}
{% if comment_not_over_amount %}
<a href="{% url 'post:detail' topic.id page_nr|increase:1 %}">Next Page</a>
{% endif %}
As you can see, I created another tag page_not_over_amount after all comments are shown to hide the link directing to the next page if all comment already been shown
@register.inclusion_tag('post/comment_block.html')
def page_not_over_amount(page_nr, comment_amount, comment_limit):
result = page_nr * comment_limit < comment_amount - comment_limit
return {'comment_not_over_amount': result}
However, I found my tag page_not_over_amount didn't ready any variable from the comment_block.html (After I get the exception, I checked the local variables. All their values are "").
I guess the possible cause of this is both tags are redirecting to the same html file. After the second tag redirects, it refreshs all the variables in the page.
Should I call a context variable?
A: Okay, so it seems like you're going for a basic pagination scheme. First things first, you should look at the built-in solution in Django. You should definitely take an hour and try and make that work.
Django's a heavyweight framework that has a built-in way of doing most things, and libraries for everything else. As a general rule, if you find yourself doing a common task in a convoluted way, there's probably a stock solution out there.
If you decide you want to do it the quick and dirty way, how about calculating has_next_page and has_prev_page in limit_amount_in_a_page?
@register.inclusion_tag('post/comment_block.html')
def limit_amount_in_a_page(page_nr, topic_id=1, amount=5):
topic = get_object_or_404(Topic, id=topic_id)
comments = Comment.objects.filter(topic=topic)
num_comments = comments.count()
selected_comments = comments[page_nr*amount, (page_nr + 1)*amount]
has_prev = (page_nr != 0)
has_next = ((page_nr + 1) * amount) < num_comments
return {
'topic': topic,
'page_nr': int(page_nr),
'selected_comments': selected_comments,
'has_next' : has_next,
'has_prev' : has_prev,
'amount_comments' : num_comments,
}
Also, note the use of slices to select comments.
But again, I highly recommend checking out the Paginator class in Django. Reading through the docs and doing the tutorial is a great thing to do as well, if you have not yet. Skimming through all the docs gives you an idea of what is built-in, which saves a lot of time in the long run.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47166251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript contentEditable of certain classes only I have the following script that makes an HTML page editable
document.body.contentEditable = 'true'; document.designMode='on';
I am wanting to only allow my users to edit sections with a class of "edit". Is this possible?
A: Yes that's possbile.
let el_array = document.getElementsByClassName('edit');
Then loop on el_array and apply this to each element el.contentEditable = true;
A: Yes this is possible, just run a simple loop over all elements with the edit class and give them contentEditable true
[...document.getElementsByClassName("edit")].forEach(
el => el.contentEditable = "true"
);
Thats all!
Edit: as harry mentioned in the comments: forEach doesnt work on htmlCollection objects, so you must cast it to an array using [...theHTMLCollection]
A:
function edit_content(){
document.querySelectorAll('.myP').forEach(function(ele){
ele.contentEditable = 'true';
})
}
<p class="myP">
abcdefghijklmnop
</p>
<button onclick="edit_content()">
Click to edit
</button>
you can do this. first, select all classes in the DOM by querySelectorAll then iterate that from forEach loop.
A: YOu can try to find all the elements with the class name 'edit' and change all off them like below.
document.querySelectorAll('.edit').forEach(function(element){
element.contentEditable = 'true';
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64389650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: 2 forms on same page - jquery context I have 2 identical forms on a page both have an id
I get the id
var parentForm = $(this).closest("form").attr("id");
alert(parentForm);
then try and get the vale of the fields based on the context.
first_name = $('input[name=first_name]', parentForm).val();
alert(first_name);
This works for #form1 but not #form2
A: You can use selectors, that's correct:
var first_name = $('#'+parentForm+' input[name=first_name]').val();
alert (first_name);
Another way:
var first_name = $('input[name=first_name]', '#'+parentForm).val();
alert (first_name);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32090509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Making postgresql query more readable I have the following sql query:
SELECT
distinct(date(survey_results.created_at)),
ROUND(
COUNT(*) FILTER (WHERE (
scores#>>'{medic,social,total}' in('high', 'medium'))) OVER(order by date(survey_results.created_at)
) * 1.0 /
(CASE (COUNT(*) FILTER (WHERE (scores#>>'{medic,social,total}' in('high','medium','low') or coalesce(raw#>>'{survey, denied}', 'f') = 'true')) OVER(order by date(survey_results.created_at)))
WHEN 0.0 THEN 1.0
ELSE (COUNT(*) FILTER (WHERE (scores#>>'{medic,social,total}' in('high','medium','low') or coalesce(raw#>>'{survey, denied}', 'f') = 'true')) OVER(order by date(survey_results.created_at)))
END)* 100, 2
) AS positive,
ROUND(
COUNT(*) FILTER (WHERE (
scores#>>'{medic,social,total}' in('low'))) OVER(order by date(survey_results.created_at)
) * 1.0 /
(CASE (COUNT(*) FILTER (WHERE (scores#>>'{medic,social,total}' in('high','medium','low') or coalesce(raw#>>'{survey, denied}', 'f') = 'true')) OVER(order by date(survey_results.created_at)))
WHEN 0.0 THEN 1.0
ELSE (COUNT(*) FILTER (WHERE (scores#>>'{medic,social,total}' in('high','medium','low') or coalesce(raw#>>'{survey, denied}', 'f') = 'true')) OVER(order by date(survey_results.created_at)))
END)* 100, 2
) AS negative
FROM survey_results
GROUP BY date, scores, raw
ORDER BY date ASC;
I'm trying to make it more DRY and readable. Any advices?
A: For positive, you can try this logic:
AVG(CASE WHEN scores#>>'{medic,social,total}' in ('high', 'medium')
THEN 100.0
WHEN scores#>>'{medic,social,total}' in ('low')
THEN 0.0
END) OVER (ORDER BY date(survey_results.created_at) as positive
(And similar logic for negative.)
I think this encapsulates your logic, except it returns NULL rather than 0 when there are no matches. If that is a problem, you can use COALESCE().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48404837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Foreign Keys are evil? Sorry for posting under an assumed name but I have to keep it anonymous due to corporate restrictions and generally to protect the innocent.
I've been a professional developer for about 18 years and though I'm not a DBA I've worked closely with them over the years and have formed what I feel is a pretty decent sense of what are and are not good database practices. I just joined a company where two developers are in charge of the database schema and I found they are very much opposed to the use of foreign key constraints.
Their reasoning as best as I can tell is that
(1) it makes unit testing stored procedures more difficult due to the extra data setup involved and
(2) foreign keys can raise errors as order is important. They would actually prefer orphaned data rather than stoppage of the application.
This seems like bad practice to me but they are unwavering in their position. We've brought up advantages foreign keys provide in terms of data integrity, query performance, generating database diagrams, etc, to no avail.
Am I not seeing something here? Any advice?
A: I think they are misguided or naive if what you have described is truly the developers' general approach to foreign keys. Of course it is quite possible that there are good reasons why a foreign key constraint can't or shouldn't apply to some particular attributes in any given system. Maybe that is the real reasoning behind the apparent rhetoric.
My advice. If you are stakeholder in the system in question then don't talk to the developers, talk to the development manager or whoever owns the system. Back up your case with specific examples of where lack of referential integrity is having an adverse impact or poses future risks.
If you don't have a current RI-related issue then presumably your main concern is to improve the policy or development approach for future work. Talk to the database managers, DBAs or those responsible for standards and information risks. Consider investing in some training, mentoring or consultancy for the benefit of the development team.
A: I've been designing database systems for over 30 years now. Here's my take - you're probably not going to like it. When designing closed systems, your referential integrity is probably going to be built into the application's user interface. You can only add a Product entity record where Color is required - enforced by the user interface. So why have a foreign key? I don't do Open databases where anyone can do anything - so your typical back end is going have thousands of lines of front end code protecting the integrity of the data. The bolted on foreign keys just get in the way and don't provide you with any real service. It's not like the foreign key is going to throw an exception and then you're going to go trap that exception and post a message to the user. Nobody and I mean NOBODY codes that way. All us programmers love to rush in and put all that cool stuff directly in the user interface. But like I said, I work with closed systems where the developer rules. Indexes, on the other hand - EXTREMELY IMPORTANT. Deal with that first. Foreign keys - just syntactical fluff.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22020218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: What are the advantages, disadvantages and example use cases of the different PowerShell module / script types? At the time of this post there are a number different PowerShell module / script types as listed on the offical MSDN page.
The page lists Script Modules, Binary Modules, Manifest Modules and Dynamic Modules.
Although, each of the pages listed above go into detail about how to create said module, none of the pages list any details about when to consider using a certain module type or the advantages and disadvantages of each.
For example (just an example), if one builds a script module that relies heavily on PowerShell 4 cmdlets and attempts to run it in a PowerShell 2 environment, the module that was created would not run. However, if one were to create a PowerShell module using C#, they would be able to run their cmdlet on any version of Windows as long as the underlying .NET framework matched the required framework of the module that was written at a cost of system memory used at script load time.
These script details are not listed on the MSDN pages, and I have not been able to find any useful information about these differences on the internet or the books I have read.
What are the advantages and use cases of the different module types above?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30423056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Jquery Scrolltop to bottom in bootstrap modal dialog I would like to create a button, when click , the modal will appear and then scroll to the bottom :
my button code :
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo scrolltop to bottom
my modal code :
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
b la bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
bla bla
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
How? I read about scrolltop but i did not understand how the scrolltop would works in modal dialog box .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35028560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: gmaps4rails not rendering in specified div id I am using Gmaps4Rails (Google Maps for Rails) in Active Admin. Everything well so far except for when I had to add multiple maps on the same show page.
gem 'gmaps4rails', '~> 2.1', '>= 2.1.2'
I extracted the importing of scripts to an html that I call only one time in the show view so I don't get an error:
/views/admin/_map_include_scripts.html.erb
<script src="//maps.google.com/maps/api/js?key=<%= ENV['GOOGLE_KEY'] %>"></script>
<script src="//cdn.rawgit.com/mahnunchik/markerclustererplus/master/dist/markerclusterer.min.js"></script>
<script src='//cdn.rawgit.com/printercu/google-maps-utility-library-v3-read-only/master/infobox/src/infobox_packed.js' type='text/javascript'></script>
Then in the show I do:
div id: 'map' do
render '/admin/map_include_scripts'
markers = DeliveryMarkersService.new(delivery).orders_markers
render '/admin/map_scripts', markers: markers, map_div_id: 'map'
end
And in views/admin/_map_scripts.html.erb I have:
<script>
handler = Gmaps.build('Google');
handler.buildMap({ provider: {}, internal: { id: '<%= map_div_id %>' }}, function(){
markers = handler.addMarkers(<%=raw markers.to_json %>);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
handler.getMap().setZoom(15);
});
</script>
So far it works GREAT! I see the maps, the markers, everything.
Now I want to add a second div with a second map so first I tried changing the first div to the following to verify that I could tell Gmaps in what div to display it:
div id: 'map2' do
render '/admin/map_include_scripts'
markers = DeliveryMarkersService.new(delivery).orders_markers
render '/admin/map_scripts', markers: markers, map_div_id: 'map2'
end
But then the map does not render! No errors on console.
If I do send an invalid id (div id that does not exist) I do get an error.
Does anyone know what's happening?
A: Your problem may be related to doing render '/admin/map_include_scripts' twice in the same page, which triggers another load of the maps and overlay APIs. When you do that after the first one has loaded your render '/admin/map_scripts', markers: markers, map_div_id: 'map2' may be executing the map rendering JS before the libs are completely loaded. Try moving render '/admin/map_include_scripts' to a common snippet, outside each div map loop.
This way the libs are loaded only once you don't need to wait a second load of the API.
render '/admin/map_include_scripts'
div id: 'map' do
markers1 = DeliveryMarkersService.new(delivery1).orders_markers
render '/admin/map_scripts', markers: markers1, map_div_id: 'map'
end
div id: 'map2' do
markers2 = DeliveryMarkersService.new(delivery2).orders_markers
render '/admin/map_scripts', markers: markers2, map_div_id: 'map2'
end
A: Could you specify what do you mean by 'the map does not render'? It's not visible on the page or the DOM? Have you checked the source code/DOM in developer tools? If you don't get the error maybe it renders but just isn't displayed correctly, e.g. it has width/height set to 0?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53696296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: ServiceStack Custom Registration Validator Issue I want to override the default Registration validator that is enabled when the Registration feature is added.
I have added my own CustomRegistrationValidator as per the ServiceStack documentation (basic rules for now, to be expanded later):
public class CustomRegistrationValidator : RegistrationValidator
{
public CustomRegistrationValidator()
{
RuleSet(ApplyTo.Post, () =>
{
RuleFor(x => x.FirstName).NotEmpty();
RuleFor(x => x.LastName).NotEmpty();
RuleFor(x => x.Email).NotEmpty();
RuleFor(x => x.Password).NotEmpty();
});
}
}
I have overridden the default registration validator in my Configure method as per the following snippet:
Plugins.Add(new AuthFeature(
() => new AuthUserSession(),
new IAuthProvider[] { new BasicAuthProvider(),
new CredentialsAuthProvider()
}));
Plugins.Add(new ValidationFeature());
Plugins.Add(new RegistrationFeature());
RegisterAs<CustomRegistrationValidator, IValidator<Register>>();
container.RegisterValidators(typeof(AppHost).Assembly);
However, the validator never appears to execute, thus I can register new users with invalid details.
I am using the latest version of ServiceStack V4.0.22
Is this a major ServiceStack bug or is this feature no longer available with the latest version of ServiceStack?
Thank you in advance for any help with this.
Regards
John
A: I can confirm that this is still a bug in v4.0.35. This is how I got around it...
*
*Create a custom registration validation class which implements AbstractValidator<Register> and add your own fluent validation rules (I copied the rules from the SS source)
public class CustomRegistrationValidator : AbstractValidator<Register>
{
public IAuthRepository UserAuthRepo { get; set; }
public CustomRegistrationValidator()
{
RuleSet(ApplyTo.Post, () =>
{
RuleFor(x => x.UserName).NotEmpty().When(x => x.Email.IsNullOrEmpty());
RuleFor(x => x.UserName)
.Must(x => UserAuthRepo.GetUserAuthByUserName(x) == null)
.WithErrorCode("AlreadyExists")
.WithMessage("UserName already exists")
.When(x => !x.UserName.IsNullOrEmpty());
RuleFor(x => x.Email)
.Must(x => x.IsNullOrEmpty() || UserAuthRepo.GetUserAuthByUserName(x) == null)
.WithErrorCode("AlreadyExists")
.WithMessage("Email already exists")
.When(x => !x.Email.IsNullOrEmpty());
RuleFor(x => x.FirstName).NotEmpty();
RuleFor(x => x.LastName).NotEmpty();
RuleFor(x => x.Email).NotEmpty();
RuleFor(x => x.Password).NotEmpty();
// add your own rules here...
});
RuleSet(
ApplyTo.Put,
() =>
{
RuleFor(x => x.UserName).NotEmpty();
RuleFor(x => x.Email).NotEmpty();
// add your own rules here...
});
}
}
*Create a CustomRegistrationFeature class which implements IPlugin (again I just copied the SS source and changed the IoC registration to the CustomRegistrationValidator class)
public class CustomRegistrationFeature : IPlugin {
public string AtRestPath { get; set; }
public CustomRegistrationFeature()
{
this.AtRestPath = "/register";
}
public void Register(IAppHost appHost)
{
appHost.RegisterService<RegisterService>(AtRestPath);
appHost.RegisterAs<CustomRegistrationValidator, IValidator<Register>>();
}
}
*Replace the RegistrationFeature registration in the App.Host with the new CustomRegistrationFeature we just created.
Plugins.Add(new CustomRegistrationFeature());
I don't know why this works as I am just doing the same or similar thing to what's already there, but it does. It also allows me to add in more validation rules (which is why I needed to do this).
A: I'm not quite sure that this is a bug, but it might be. Anyway, the reason that the custom validator isn't used, is that the Register() method of RegistrationFeature isn't called until after the Configure() method has been run, thus overriding the registration of CustomRegistrationValidator.
The simplest solution is registering the custom validator after the Register() method has been run:
public override void OnAfterInit()
{
base.OnAfterInit();
RegisterAs<CustomRegistrationValidator, IValidator<Register>>();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24451926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Type 'FormGroup | null' is not assignable to type 'AbstractControlLike' with Angular material stepControl <mat-step [editable]="true" [stepControl]="productDetailsFormGroup$ | async">
<ng-template matStepLabel>Product details</ng-template>
<ng-template matStepContent>
<fetebird-ui-product-details></fetebird-ui-product-details>
</ng-template>
</mat-step>
In the component
readonly productDetailsFormGroup$: Observable<FormGroup>;
constructor(private productStore: ProductStore) {
this.productDetailsFormGroup$ = this.productStore.selectProductDetailsForm$;
}
Error
error TS2322: Type 'FormGroup<any> | null' is not assignable to type 'AbstractControlLike'.
Type 'null' is not assignable to type 'AbstractControlLike'.
A: The result of async pipe is always T | null or null, and the stepControl doesn't accept null.
You can add *ngIf to make sure it's not null before using it, like the following:
<mat-step
*ngIf="productDetailsFormGroup$ | async as stepControl"
[editable]="true"
[stepControl]="stepControl"
>
<ng-template matStepLabel>Product details</ng-template>
<ng-template matStepContent>
<fetebird-ui-product-details></fetebird-ui-product-details>
</ng-template>
</mat-step>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73836098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Some CSS, worked well in dev, does not work in build version In vue.js, Most of css I used works well but
some css for example,
In Home.vue
<template>
...
</template>
<script>
...
</script>
<style>
h1 {font-size:2.6em;font-weight:bold;color: #848381;}
</style>
in dev mod, at my notebook, h1 css works well.
But when I run npm run build and upload files to aws webserver, the color of h1 is other color.
--- addition ---
In Chrome Dev tool, I found some part of css is auto added.
For all h1 ~ h6 tag color:inherit is added.
If I turn off that css, the color change to same as dev mode.
How can I fix it?
What area should I check?
A: Open Dev Tools and see where the style applied to the h1 tag is declared.
Check if the style has been overwritten.
Try as follows:
h1 {
font-size:2.6em !important;
font-weight:bold !important;
color: #848381 !important;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52350346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: titanium maps user location near annotation Im building an app with titanium and i am creating multiple annotations on a google map.
My question is if somehow i can check if user location is inside an annotation and lets say fire an alert. Is this possible?
In a similar project with javascript i was creating circles around annotations and then checking if user was inside this circle.
Something like this:
Circles[k] = new google.maps.Circle({
map: map,
clickable: false,
radius: 35,
fillColor: '#fff',
fillOpacity: .6,
strokeColor: '#313131',
strokeOpacity: .4,
strokeWeight: .8,
center: new google.maps.LatLng(json.markers[k].lat, json.markers[k].lon)
});
BoundsArray[k] = Circles[k].getBounds();
Thank you
A: Geofencing (http://mobile.tutsplus.com/tutorials/iphone/geofencing-with-core-location/)
Geofencing is the process in which one or more geofences are monitored and action is taken when a particular geofence is entered or exited. Geofencing is a technology very well suited for mobile devices. A good example is Apple’s Reminders application. You can attach a geofence to a reminder so that the application notifies you when you are in the vicinity of a particular location (figure 1). This is incredibly powerful and much more intuitive that using traditional reminders that remind you at a certain date or time.
IOS Module Implementation for Titanium:
http://www.clearlyinnovative.com/blog/post/34758523489/appcelerator-titanium-quickie-ios-geofencing-module#.UZVL3CtARYg
I believe there is a tutorial on converting Skyhook's SDK to a module in Titanium. This looks like the result.
https://github.com/aaronksaunders/ClearlyInnovativeSkyhookModule
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16569907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I Need to fetch GPO policy attached with the specific GPO and what delegation permissions are linked to the GPO I Need to fetch GPO policy attached with the specific GPO and what delegation permissions are linked to the GPO, for eg we have a delegation tab where we add Machin/ User level permission instead of Authenticated User using Powershell
here I'm importing all the client devices and fetching where this client device are attached to which GPO as delegation permission. But not getting any error or data blank report is fetched and it took 15 mins to ran this
$Computers = Import-Csv C:\Users\User\Desktop\Computers.csv
Get-GPO -All -Domain "test.com" | foreach-object { if($_ | Get-GPPermission -TargetName "$($Computers.Name)" -TargetType Computer -ErrorAction SilentlyContinue) {$_.DisplayName}} | export-csv -path c:\users\delegation.csv -append
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73670362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.