source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0014638254.txt" ]
Q: Gherkin to (not for) Javascript I am new to BDD and Gherkin. Trying to use Cucumber, which parses Gherkin to Ruby - a language I don't know. Is there any library which converts Gherkin to Javascript ? If I get the Javascript output for Gherkin, I plan to modify the code and call some Javascript functions of my own. Please note, I am not planning to test these javascript functions - these functions are from some other testing tool I am trying to chain to. I Hope I am not planning to do something weird. All the problem is that our team does not want to learn Ruby. Please suggest some options. I guess, what I need is a tool which allows me to write step definitions in javascript - as opposed to Ruby. Thanks ! A: I think you're looking for Cucumber.js: http://git.io/cukejs
[ "stackoverflow", "0006984729.txt" ]
Q: How can I replace UINavigationController as left hand view in UISplitViewController in Interface Builder? My main view controller in my iPhone app is a UITabBarController. I want to use it as the left-hand view controller in a UISplitViewController, but Interface Builder doesn't want to play nice and let me do it. Is it possible to replace the left view controller in a UISplitViewController? If so, how do I do it? I realize I can do this in code, but I'd prefer to do it in Interface Builder. A: Turns out you can't replace the UINavigationController with a stock UITabBarController because the UITabBarController only supports portrait by default. So I'd have to inherit from UITabBarController and override that method etc etc which I don't want to do. After playing around with UISplitViewController, though, I find it to be mostly useless, so I've abandoned it as my root view controller.
[ "stackoverflow", "0002865302.txt" ]
Q: Why C# doen't support multiple inheritance Possible Duplicate: Should C# include multiple inheritance? One of my friend asked me the question i.e.Why C# doen't support multiple inheritance A: Using interfaces is more flexible and eliminates the ambiguity of multiple inheritance. Further details, HERE.
[ "stackoverflow", "0009660670.txt" ]
Q: Android: Setting variables from other classes I have been trying to find a way to set variables for one class while in another class withous changing intents. Maybe I'm searching the wrong things, maybe I'm over complicating this, I don't know. Basically, what I am doing at the moment is getting the listView item that is selected, checking its index value, and chaning a variable or two(from a different class) based on the choice. public void onItemClick(AdapterView<?> parent, View v, int position, long id){ theGame settings = null; switch(position){ case 0: settings.baseWave = 10; settings.baseRate = 5; break; case 1: settings.baseWave = 20; settings.baseRate = 10; break; case 2: settings.baseWave = 30; settings.baseRate = 15; break; } } "theGame" is my outside class and "baseWave" and "baseRate" are the corrisponding varriables. Obviously, what I am doing here is not working for me. Im fairly new at all of this so be gentle. Thank you for any help you can offer, it is much appreciated :) ~TG A: It's nice that it struck you that you may have a bad design, but it should also have struck you that you don't know Java, that you're having this problem because you don't know Java, and that a good Java book would help you. Well, this is the shortest path to getting this attempt of yours working: have theGame store a reference to itself in a static member; use the static member in your code. That is, class TheGame { public static TheGame theGame = null; TheGame() { theGame = this; } } And elsewhere: TheGame.theGame.baseWave = 10 * (position + 1); Or you may need it put this way: public class TheGame extends Activity { public static TheGame theGame = null; @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); theGame = this; } } A good Java book would describe this sort of thing to you, give you a name for it, and warn you away from it.
[ "math.stackexchange", "0003051604.txt" ]
Q: PRIMES in P paper - Lemma 4.7 - why are the polynomials $X^m$ distinct in $F$? I'm working through the original AKS paper, available here: https://www.cse.iitk.ac.in/users/manindra/algebra/primality_v6.pdf. There's a single transition which I don't know how to justify, I will describe the setting and hopefully capture everything that's relevant. In doubt, feel free to see Lemma 4.7 in the paper. We have the following setting: $p$ is prime, $p > r$. $h(X)$ is an irreducible polynomial over $F_p$ that divides $X^r-1$ and has degree greater than $1$. $F := F_p[X]/(h(X))$. There's $(n, r) = (p, r) = 1$. $m_1$ and $m_2$ are distinct elements of $G$, the multiplicative group generated by $n$ and $p$ modulo $r$ (so $G$ is a subgroup of $\mathbb{Z}_r^*$). Now, from that information they somehow infer that $X^{m_1}$ and $X^{m_2}$ are distinct in $F$. I don't know how. If you want to refer to the paper, the sentence this is paraphrasing is 'Hence there will be $|G| = t$ distinct roots of $Q(Y)$ in $F$.' The preceding sentence is 'Since $(m, r) = 1$ ($G$ is a subgroup of $\mathbb{Z}_r^*$), each such $X^m$ is a primitive $r^\text{th}$ root of unity.' With a little work I think I'll be able to show that $X^m$ is a primitive $r^\text{th}$ root of unity in $F$, however I don't see how that connects to the statement that the $X^m$ are distinct in $F$ for distinct $m \in G$. Perhaps I'm missing some elementary background that makes this transition obvious. Below is some work that I've done trying to solve this, but it might be wrong because I have never learned any of this theory properly :( Below I'm often quietly using the fact that $h(X)$ can't divide any $X^d$ for $d \in \mathbb{Z}$. If I haven't made a mistake along the way, I think this problem can be reduced to showing that: \begin{equation} h(X) \not | \ X^{m_1-m_2} - 1 \end{equation} If I understand primitive roots of unity correctly, we have that $m_1 = m_2k$ for some integer $k$ (because $X^{m_1}$ generates, among other roots also the root $X^{m_2}$), and so $X^{m_1-m_2} - 1 = X^{(k-1)m_2} - 1$. We also already know $h(X) | X^{r} - 1$ and I think if we assume (looking for a contradiction from here) that $h(X) | \ X^{m_1-m_2} - 1$ then we can get $h(X) | X^{\text{gcd}(r, (k-1)m_2)} - 1 = X^{\text{gcd}(r, k-1)} - 1$ from that. That would be great if we can show that $(r, k-1) = 1$ cause we'd get a contradiction because $\deg h > 1$. However I don't know how to show that $(r, k-1) = 1$, if that's even true... I'd think that $(k, r) = 1$ because $(m_1, r) = 1$ and $m_1 = m_2k$. That seems to suggest $(k-1, r) = 1$ is quite unlikely to hold? (That's not a rigorous argument of course.) A: The proof of Lemma $4.7$ begins with noting that $X$ is a primitive $r$-th root of unity in $F$. This means that if $X^m=1$ in $F$, then $r\mid m$. Thus if $X^{m_1}=X^{m_2}$ in $F$, then $m_1\equiv m_2\pmod r$. For $m_1,m_2\in G$ this translates into $m_1=m_2$.
[ "stackoverflow", "0014124047.txt" ]
Q: append multiple files and remove duplicates using dictionaries So I have a few files that look like: snpID Gene rs1 ABC1 rs2 ABC1 rs3 ABC25 rs4 PT4 rs5 MTND24 In different files there will be other snpIDs and Gene pairs but there may be duplicates for a given snpID but the corresponding "Gene" associated could be different . For eg: snpID Gene rs100 URX1 rs95 KL4 rs1 ABC1 rs2 ABC1-MHT5 rs3 ABC25 rs4 PT4-FIL42 What I want to do is to append all the contents of the files and remove the duplicates if they have the same snpID and Gene pair. Whereas if the corresponding Gene for a snpID is different it has to go into the same row For the above example it should look like: snpID Gene rs1 ABC1 rs2 ABC1, ABC1-MHT5 rs3 ABC25 rs4 PT4, PT4-FIL42 rs5 MTND2 rs100 URX1 rs95 KL4 I thought I could achieve this through creating dictionaries. import glob file_list = glob.glob('annotations.*') dict_snps_genes = {} for filename in file_list: with open(filename) as fileA: for line in fileA: col0 = line.split()[0] col1 = line.split()[1] dict_snps_genes[col0] = col1 unique_dict_snps = {} for key,value in dict_snps_genes: if key not in unique_dict_snps.keys(): unique_dict_snps_genes[key] = value I tested this before moving any further and this gives me an error like: ValueError: too many values to unpack PS: each file has around 8000 snpId-Gene pair and there are more than 5 files Ideas on how to get past this!! A: You are looping over keys, but trying to assign those to both a key and value variable: for key,value in dict_snps_genes: change that to loop over .items(): for key,value in dict_snps_genes.items(): or better still, if on Python 2.x, use `.iteritems(): for key,value in dict_snps_genes.iteritems(): Note that the way you read the files, you only ever store the last-read gene for any given snpID; you overwrite the previous one if you find another entry for that id. Personally, I'd use collections.defaultdict() with a set default: import glob import collections file_list = glob.glob('annotations.*') snps_genes = collections.defaultdict(set) for filename in file_list: with open(filename) as fileA: for line in fileA: snpid, gene = line.strip().split(None, 1) snps_genes[snpid].add(gene) Now the values in snps_genes are sets of genes, each unique. Note that I split your line into 2 pieces on whitespace (.split(None, 1)) so that if there is any whitespace in the gene value, it'll be stored as such: >>> 'id gene with whitespace'.split(None, 1) ['id', 'gene with whitespace'] By using `snpid, gene' as left-hand assignment expression Python takes the result of the split and assigns each piece to a separate variable; a handy trick here to save a line of code. To output this to a new file, simply loop over the resulting snps_genes structure. Here is one that sorts everything: for id in sorted(snps_genes): print id, ', '.join(sorted(snps_genes[id]))
[ "stackoverflow", "0048001211.txt" ]
Q: TypeError: Expected String, got 0 of type int instead i've been using the code from tf.estimate.quickstart to run my own image classification task and i keep getting the error stated in the title, this is the full code: import numpy as np import tensorflow as tf import pandas as pd train_x = pd.read_csv('train_set_x.csv') train_y = pd.read_csv('train_set_y.csv') test_x = pd.read_csv('test_set_x.csv') test_y = pd.read_csv('test_set_y.csv') feature_columns = [tf.feature_column.numeric_column("x", shape=[784])] uni = set() for i in range(0,26): str(i) uni.add(i) uni = list(uni) train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": np.array(train_x)}, y=np.array(train_y), num_epochs=None, shuffle=True) classifier = tf.estimator.DNNClassifier(feature_columns=feature_columns, hidden_units=[10, 20, 10], n_classes=26, model_dir="/tmp/test_run", label_vocabulary=uni) classifier.train(input_fn=train_input_fn, steps=1) test_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": np.array(test_x)}, y=np.array(test_y), num_epochs=1, shuffle=False) accuracy_score = classifier.evaluate(input_fn = test_input_fn)["Accuracy"] print("\nTest Accuracy: {0:f}\n".format(accuracy_score)) the dataset i've used is the EMNIST dataset which contains handwritten letter images in the dimension of 28 x 28 which i've converted into a .csv file, is this the right way to go about image recognition training? the error is occurs in the line classifier.train(input_fn=train_input_fn, steps=1) here is the full stack trace: Traceback (most recent call last): File "C:/Users/Slither/Documents/Scripts/lol.py", line 33, in <module> classifier.train(input_fn=train_input_fn, steps=1) File "C:\Users\Slither\Anaconda3\lib\site-packages\tensorflow\python\estimator\estimator.py", line 302, in train loss = self._train_model(input_fn, hooks, saving_listeners) File "C:\Users\Slither\Anaconda3\lib\site-packages\tensorflow\python\estimator\estimator.py", line 711, in _train_model features, labels, model_fn_lib.ModeKeys.TRAIN, self.config) File "C:\Users\Slither\Anaconda3\lib\site-packages\tensorflow\python\estimator\estimator.py", line 694, in _call_model_fn model_fn_results = self._model_fn(features=features, **kwargs) File "C:\Users\Slither\Anaconda3\lib\site-packages\tensorflow\python\estimator\canned\dnn.py", line 334, in _model_fn config=config) File "C:\Users\Slither\Anaconda3\lib\site-packages\tensorflow\python\estimator\canned\dnn.py", line 203, in _dnn_model_fn logits=logits) File "C:\Users\Slither\Anaconda3\lib\site-packages\tensorflow\python\estimator\canned\head.py", line 456, in create_estimator_spec name='class_string_lookup') File "C:\Users\Slither\Anaconda3\lib\site-packages\tensorflow\python\ops\lookup_ops.py", line 1197, in index_to_string_table_from_tensor vocabulary_list = ops.convert_to_tensor(vocabulary_list, dtypes.string) File "C:\Users\Slither\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 836, in convert_to_tensor as_ref=False) File "C:\Users\Slither\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 926, in internal_convert_to_tensor ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) File "C:\Users\Slither\Anaconda3\lib\site-packages\tensorflow\python\framework\constant_op.py", line 229, in _constant_tensor_conversion_function return constant(v, dtype=dtype, name=name) File "C:\Users\Slither\Anaconda3\lib\site-packages\tensorflow\python\framework\constant_op.py", line 208, in constant value, dtype=dtype, shape=shape, verify_shape=verify_shape)) File "C:\Users\Slither\Anaconda3\lib\site-packages\tensorflow\python\framework\tensor_util.py", line 383, in make_tensor_proto _AssertCompatible(values, dtype) File "C:\Users\Slither\Anaconda3\lib\site-packages\tensorflow\python\framework\tensor_util.py", line 303, in _AssertCompatible (dtype.name, repr(mismatch), type(mismatch).__name__)) TypeError: Expected string, got 0 of type 'int' instead. Process finished with exit code 1 A: The vocabulary is supposed to be strings but you are adding integers (you are calling str(i) and ignoring the result when you probably mean i = str(i)).
[ "stackoverflow", "0032536966.txt" ]
Q: waiting for thread with timeout: freeze I don't understand anything now. Consider I have next piece of code (simplified version): #include <iostream> #include <thread> #include <condition_variable> #include <mutex> #include <chrono> const auto k_sleep = std::chrono::seconds{3}; const auto k_wait = std::chrono::seconds{1}; const auto k_repeats = 20u; void test() { std::mutex m; std::condition_variable c; bool processed = false; std::thread worker{[&]() { std::this_thread::sleep_for(k_sleep); std::unique_lock<std::mutex> lock(m); processed = true; lock.unlock(); c.notify_one(); }}; std::unique_lock<std::mutex> lock(m); if(c.wait_for(lock, k_wait, [&processed]() { return processed; })) { worker.join(); std::cout << "done" << std::endl; } else { worker.detach(); std::cout << "timeout" << std::endl; } } int main() { for(auto i = 0u; i < k_repeats; ++i) test(); } Few questions: are there any deadlocks ? am I using condition_variable (and all other stuff relative to thread) correctly ? is there UB ? if everything OK, how many times timeout will be printed ? As you can see, I'm running thread and waiting for it (using condition_variable) some time. Wait time is less then thread's executing time. With both VC++ (Visual Studio 2015, v 19.00.23026) and g++ (v 4.8.2) I have timeout 2 times printed and then I'm stuck on worker.join() under debugger. If I will increase k_sleep to something big (relatively to k_wait with small loops count), for example, 30 seconds - everything will be fine. So, why this happens ? If I do something incorrectly please explain me the correct way. Thanks A: You have problems with memory management there: Capturing variables by reference in lambda that passed to a new thread. All variables (m, c and processed) are allocated on the stack, and they will go out of scope when you detach a worker thread. So, when the thread wake up, it will access garbage. So, you need to allocate you data on the heap and make sure you do not capture variables by reference. I always prefer to pass data explicitly into std::thread. #include <iostream> #include <thread> #include <condition_variable> #include <mutex> #include <chrono> #include <memory> const auto k_sleep = std::chrono::seconds{ 3 }; const auto k_wait = std::chrono::seconds{ 1 }; const auto k_repeats = 20u; struct Data { std::mutex m; std::condition_variable c; bool processed = false; }; void test() { auto data = std::make_shared<Data>(); auto run = [](std::shared_ptr<Data> i_data) { std::this_thread::sleep_for(k_sleep); std::unique_lock<std::mutex> lock(i_data->m); i_data->processed = true; lock.unlock(); i_data->c.notify_one(); }; std::thread worker{ run, data }; std::unique_lock<std::mutex> lock(data->m); if (data->c.wait_for(lock, k_wait, [&data]() { return data->processed; })) { worker.join(); std::cout << "done" << std::endl; } else { worker.detach(); std::cout << "timeout" << std::endl; } } int main() { for (auto i = 0u; i < k_repeats; ++i) test(); }
[ "math.stackexchange", "0003151049.txt" ]
Q: Trouble reading this proof of characterization of continuous mappings by open sets. Here's the first part of the proof—the part I have a question about. Simply put, I don't see anything here precluding $x_0$ from being on the boundary of $S_0$. And if that's the case then $N_0 \not\subset S_0$. Here's a picture of what's in my brain: I'm sure that it's somehow implied $x_0$ can't be on the boundary but I'm not seeing it for some reason. Can someone please expand on the proof? Thank you. Note: this is from Kreyszig's Introductory Functional Analysis with Applications. A: The key part you are missing here is in the line Since $T$ is continuous, $x_0$ has a $\delta$-neighborhood $N_0$ which is mapped into $\pmb N$. Since $N$ is a subset of $S$, any subset of $\pmb X$ that is mapped into $\pmb N$ is a subset of $\pmb {S_0}$, since $S_0 = f^{-1}(S)$ is by definition the collection of points that get mapped into $S$. This is what forces the $\delta$-neighborhood to "not be on the boundary," since it must be wholly contained in $S_0$, by the definition of inverse image.
[ "stackoverflow", "0005158665.txt" ]
Q: Java try catch blocks Here a simple question : What do you think of code which use try catch for every instruction ? void myfunction() { try { instruction1(); } catch (ExceptionType1 e) { // some code } try { instruction2(); } catch (ExceptionType2 e) { // some code } try { instruction3(); } catch (ExceptionType3 e) { // some code } try { instruction4(); } catch (ExceptionType4 e) { // some code } // etc } I know that's horrible, but I want to know if that decreases performance. A: Try something like this: (I know this doesn't answer your question, but it's cleaner) void myfunction() { try { instruction1(); instruction2(); instruction3(); instruction4(); } catch (ExceptionType1 e) { // some code } catch (ExceptionType2 e) { // some code } catch (ExceptionType3 e) { // some code } catch (ExceptionType4 e) { // some code } // etc } A: It doesn't decrease performance (certainly not noticeably) but it does indeed look horrible. Remember the golden rule: readable code is often faster code. Produce readable code first and only change it if it proves to be too slow. Group your try-catch blocks into logical chunks of the original code (e.g. one for opening a stream and reading data from it, one for all the processing done afterwards) and your maintenance developers will thank you for it. You should also consider that if your first catch block catching an exception doesn't end abruptly (that is, execution continues in the normal flow), additional exceptions might be thrown by subsequent instructions that rely on the previous ones completing successfully, which are both spurious and they can slow your code down. A: No, this probably doesn't decrease performance (but, as always, you'd have to test it). When compiled into bytecode, the Java exception handlers are changed into a table of bytecode offset ranges and associated handler addresses. The catch handlers are generally compiled outside the mainline of the code, so do not affect "normal" non-exception execution. More information can be found in The Java Virtual Machine Specification, section 7.12 Throwing and Handling Exceptions. This section also provides examples of how various code constructs might be compiled to bytecode.
[ "stackoverflow", "0038199660.txt" ]
Q: PostgreSql Traverse through an array to fetch results in multiple rows under same column I have JSON data as follows: "group_nw4qu40":[ {"group_nw4qu40/Special_Characteristics":"11"}, {"group_nw4qu40/Special_Characteristics":"0"}, {"group_nw4qu40/Special_Characteristics":"0"}, {"group_nw4qu40/Special_Characteristics":"1"}, {"group_nw4qu40/Special_Characteristics":"1"}] My task is to Traverse though the Array within an array to fetch the "Special_Characteristic" of each individual member and create a table having these values in Multiple Rows under same column. I tried using this query but, it fetches me values in multiple columns which is incorrect for me. select id AS id, (json->'group_nw4qu40'->>0)::json->>'group_nw4qu40/Special_Characteristics' AS value_of_special_characteristic from public.logger_instance where id = 5215 Please help me get these values in multiple Rows under same column. A: Use jsonb_array_elements() or json_array_elements(), e.g.: with the_data (json) as ( values ( '{"group_nw4qu40":[ {"group_nw4qu40/Special_Characteristics":"11"}, {"group_nw4qu40/Special_Characteristics":"0"}, {"group_nw4qu40/Special_Characteristics":"0"}, {"group_nw4qu40/Special_Characteristics":"1"}, {"group_nw4qu40/Special_Characteristics":"1"}]}'::jsonb) ) select e->>'group_nw4qu40/Special_Characteristics' value_of_special_characteristic from the_data, jsonb_array_elements(json->'group_nw4qu40') e value_of_special_characteristic --------------------------------- 11 0 0 1 1 (5 rows) Your actual query should look like this: select id, e->>'group_nw4qu40/Special_Characteristics' value_of_special_characteristic from public.logger_instance, jsonb_array_elements(json->'group_nw4qu40') e where id = 5215;
[ "wordpress.stackexchange", "0000255533.txt" ]
Q: Why an arugment is missing in wp_get_attachment_image_attributes? I have a function: function azu_post_thumbnail_responsive_size($attr, $attachment, $size) { if ($size === 'az_medium') { $attr['sizes'] = '(max-width: 639px) 100vw, (max-width: 1023px) 50vw, 334px'; } else if ($size === 'az_large') { $attr['sizes'] = '(max-width: 1023px) 100vw, 717px'; } return $attr; } add_filter('wp_get_attachment_image_attributes', 'azu_post_thumbnail_responsive_size', 10 , 3); This is working fine on WP4.4+, but before, when responsive image were not introduced, I have the folowing error: Warning: Missing argument 3 for azu_post_thumbnail_responsive_size() Can someone help me with this? A: The third parameter $size was introduced in WordPress 4.1. Before that there was only $attr and $attachment. So for this to work before WP 4.1, you need to provide a default value for $size. Since default for size is thumbnail, you can use that in your filter hook's function definition. So, modify your CODE as follows: function azu_post_thumbnail_responsive_size($attr, $attachment, $size = 'thumbnail') { if ($size === 'az_medium') { $attr['sizes'] = '(max-width: 639px) 100vw, (max-width: 1023px) 50vw, 334px'; } else if ($size === 'az_large') { $attr['sizes'] = '(max-width: 1023px) 100vw, 717px'; } return $attr; } add_filter('wp_get_attachment_image_attributes', 'azu_post_thumbnail_responsive_size', 10 , 3); Now it'll work for all versions of WordPress. Note: obviously, any CODE related to the $size parameter will not function similarly pre & post WP 4.1. However, at least you'll not get the error.
[ "stackoverflow", "0021769918.txt" ]
Q: How do i know if i'm disconnected from a Dart websocket server I created a WebSocket server, and it works just fine, however, i don't know how to detect if a client is disconnected, can anyone help me ? here is my code: import 'dart:io'; const port=8080; List users=new List(); void main() { HttpServer.bind('127.0.0.1', port) .then((HttpServer server)=> server.listen((HttpRequest request) => WebSocketTransformer.upgrade(request).then((WebSocket websocket) { //what can i do here to detect if my websocket is closed users.add(websocket); websocket.add("clients Number is ${users.length}"); }) ) ); } A: Since a WebSocket is a Stream it will close when the socket is disconnected. This is a nice property of many of the dart:io classes implementing Stream - you can interact with them al lthe same way, once you know how to use Streams. You can detect when a Stream closes in several ways: Add an onDone handler to your listen() call: websocket.listen(handler, onDone: doneHandler); Add an on-done handler to the StreamSubscription returned from listen(): var sub = websocket.listen(handler); sub.onDone(doneHandler); Turn the StreamSubscription into a Future via asFuture() and wait for it to complete: var sub = websocket.listen(handler); sub.asFuture().then((_) => doneHandler);
[ "stackoverflow", "0055955520.txt" ]
Q: File with single Line around 4G to load into Spark I am trying to load a file which is a single line, there are no new line charters in the entire File so technical single line size is the size of the file. I tried to use the below code to load the data. val data= spark.sparkContext.textFile("location") data.count It is not able to return any value. Tried to read the file as string with the following Code, Trying to write in java code. import org.apache.hadoop.conf.Configuration import org.apache.hadoop.fs.Path import org.apache.hadoop.fs.FileSystem val inputPath = new Path("File") val conf = spark.sparkContext.hadoopConfiguration val fs = FileSystem.get(conf) val inputStream = fs.open(inputPath) import java.io.{BufferedReader, InputStreamReader} val readLines = new BufferedReader(new InputStreamReader(inputStream)).readLine() The JVM is getting exited with following error. ava HotSpot(TM) 64-Bit Server VM warning: INFO: os::commit_memory(0x00007fcb6ba00000, 2148532224, 0) failed; error='Cannot allocate memory' (errno=12) There is insufficient memory for the Java Runtime Environment to continue. Native memory allocation (mmap) failed to map 2148532224 bytes for committing reserved memory. The Problem is entire data is in single line, spark using \n to identify the new record(new line). As there is \n it is trying to load into single line which creating the memory issues I am ok to split that long string based on length, add new line character for every 200 charcter (0,200) first line. (200,400) is second line. Sample Input This is Achyuth This is ychyath This is Mansoor ... .... this line size is more than 4 gigs. Output This is Achyuth This is ychyath This is Mansoor . . . A: This approach works if the file size is a multiple of the split size and the character encoding is fixed-length (ASCII, UTF-16, UTF-32, no code points above 127 in UTF-8 or similar...). Given file This is AchyuthThis is ychyathThis is Mansoor val rdd = spark .sparkContext .binaryRecords(path, 15) .map(bytes => new String(bytes)) val df = spark.createDataset(rdd) df.show() Output: +---------------+ | value| +---------------+ |This is Achyuth| |This is ychyath| |This is Mansoor| +---------------+
[ "stackoverflow", "0005885710.txt" ]
Q: There's an easy way to load csv rows into an Heroku hosted app? I have some csv exported rows of data that I need to load into a Rails 2.3.8 app. The csv data is already in the perfect format for the app that I'm hosting on Heroku. Is there an easy way to do it? Thanks, Augusto A: I have had success with something like this: require 'csv' CSV.foreach(Rails.root.to_s+"/db/calseed_test1.csv") do |row| Calevent.create( :caldate => row[0], :caltime => row[1], :callocation => row[2], :caldescription => row[3] ) end A: You could use Ruby's built-in CSV library to read your data into an array, which you can then do whatever you need to with: CSV.foreach("path/to/file.csv") do |row| # use row here... # For example, if you had users in a CSV file like "username,email" you could do: User.create(:username => row[0], :email => row[1]) end
[ "pt.stackoverflow", "0000121441.txt" ]
Q: Html não renderiza valor de radio button Preciso pegar o valor da input radio dentro de uma modal bootstrap, mas ele não renderiza o valor fica dessa forma: Utilizei esse exemplo de radios: <div id="itemList"> <input type="radio" value ="1" class="overWrite" name="overWrite" />Yes <input type="radio" value ="2" class="overWrite" name="overWrite" />No </div> No debug, percebi que quando pego o valor logo ao carregar a pagina desta forma: $(document).ready(function(){ var overwrite = $('#itemList input:radio:checked').val(); alert('value = ' + overwrite); }); Ele consegue capturar o value da input, porém quando pego através do change ou click ele retorna vazio: $("input[type='radio']").click(function () { var radioValue = $(this).val(); alert(radioValue); }); Quando a modal é carregada na página a input radio perde seu value, no mesmo formulário existem outras inputs, mas isso acontece apenas com o radio button. Alguém sabe por quê? A: As inputs do tipo radio são melhores utilizada para a submissão de um formulário, pois o name de ambas devem ser iguais. Para pagar o valor de modo dinâmico, o melhor jeito é utilizar a tag select, ela substitui o input radio e resolve os problemas. <!doctype html> <html> <body> <select id="option"> <option value="Yes">Sim</option> <option value="No">Não</option> </select> <input type="button" value="Click" onclick="alert(document.getElementById('option').value);"> </body> </html>
[ "english.stackexchange", "0000223794.txt" ]
Q: Question regarding English in an old maths book I'm currently working through an old British maths book, released around 1910, on the whole the language is quite manageable however I've reached a part of the text where there's talk of circles and this was written: "The circumferences of circles are to one another as their radii" What does this mean? Does it mean that the circumference of circles are dependent on their radii or what? A: It means that the ratio of one circle's circumference to another's, is the same as the ratio of the radii of the same circles. Or c1/c2 = r1/r2, where c1 and c2 are the circumferences of two circles, and r1 and r2 are the radii of the same circles.
[ "dba.stackexchange", "0000019875.txt" ]
Q: How can I trigger this stored procedure on insert? I have a table of error messages to which errors will be inserted. I also have a table defining interactions between errors. For example, when a "Power Restored" error occurs, it clears any previous "Power Lost" errors. ("Error" being used loosely to describe any enumerable diagnostic message.) To do this, I've defined the following stored procedure: BEGIN -- Declare local variables DECLARE done BIT DEFAULT 0; DECLARE target SMALLINT(5) UNSIGNED DEFAULT '0'; DECLARE `action` ENUM('Clear','Raise','SetSeverity'); DECLARE severity TINYINT(3) UNSIGNED DEFAULT NULL; DECLARE timespan INT(11) DEFAULT NULL; DECLARE cutoff TIMESTAMP; -- Declare the cursor DECLARE interactions CURSOR FOR SELECT TargetErrNo, errorinteraction.`Action`, errorinteraction.Severity, errorinteraction.TimeSpan FROM errorinteraction WHERE ActorErrNo=NEW.Number ORDER BY Priority DESC; -- Declare continue handler DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1; CREATE TABLE IF NOT EXISTS interactionrecord (`datediff` INT); TRUNCATE TABLE interactionrecord; -- Open the cursor OPEN interactions; -- Loop through all rows REPEAT -- Get FETCH interactions INTO target, `action`, severity, timespan; IF NOT done THEN -- Process IF timespan IS NULL THEN IF `action`='Clear' THEN UPDATE error SET Cleared=NOW(), UpdatedBy=NEW.Id WHERE Number=target AND Cleared IS NULL; ELSEIF `action`='Raise' THEN UPDATE error SET Cleared=NULL, UpdatedBy=NEW.Id WHERE Number=target AND Cleared IS NOT NULL; ELSEIF `action`='SetSeverity' AND severity IS NOT NULL THEN UPDATE error SET error.Severity=severity, UpdatedBy=NEW.Id WHERE Number=target AND error.Severity!=severity; END IF; ELSE SET cutoff=DATE_SUB(NEW.Reported, INTERVAL timespan SECOND); IF `action`='Clear' THEN UPDATE error SET Cleared=NOW(), UpdatedBy=NEW.Id WHERE Number=target AND Cleared IS NULL AND error.Reported>=cutoff; ELSEIF `action`='Raise' THEN UPDATE error SET Cleared=NULL, UpdatedBy=NEW.Id WHERE Number=target AND Cleared IS NOT NULL AND error.Reported>=cutoff; ELSEIF `action`='SetSeverity' AND severity IS NOT NULL THEN UPDATE error SET error.Severity=severity, UpdatedBy=NEW.Id WHERE Number=target AND error.Severity!=severity AND error.Reported>=cutoff; END IF; END IF; END IF; -- End of loop UNTIL done END REPEAT; -- Close the cursor CLOSE interactions; END This works perfectly when I insert a new error by hand, then call this function passing the new error's Id. But when I try and insert a trigger to call it automatically, MySQL begins throwing Error 1422 at me. I've tried both FOR EACH ROW CALL updateerror(NEW.Id); and copying the stored procedure code into the trigger directly, replacing a few of the variables with their respective NEW columns. Should I simply leave this as a stored procedure and assume users are responsible to call it? Is there a better way to do this? My exact MySQL version is 5.5.25. A: I figured out that the following lines of code weren't allowed to run in a trigger: CREATE TABLE IF NOT EXISTS interactionrecord (`datediff` INT); TRUNCATE TABLE interactionrecord; I had had them in there for debugging purposes and forgot to remove them. Once I removed them, I could run the code as a trigger, until I tried updating the error table, since apparently updating the table the trigger is on isn't allowed either. What I'm doing now is a trigger which simply inserts new error Id into a small table, then having an event run every minute or so, calling my stored procedure on all the newly inserted errors.
[ "stackoverflow", "0059437346.txt" ]
Q: How to send notification mail each time the user logs in with firebase? I am trying to send a notification mail (or any medium) each time the user logs in to the react app. Currently, I am using Firebase.auth().onAuthStateChanged(async(userData) => { if (userData) { const sendMail = await api.sendMail(userData.email); } } But the issue with this each time I refresh the app, it calls sendMail API. So I thought I will do this on login button click, but the issue with that is its a social login. And I am using signInWithRedirect like Firebase.auth().signInWithRedirect(facebookProvider);. In this case, I don't have the past state of my app. Is there any way to do this signInWithRedirect? A: You would not want to trigger this onAuthStateChanged because, as you pointed out, this will send emails anytime the user's signin state changes. Since you are using Facebook to authenticate users, you'll want to look at the auth events and methods available to Firebase's federated identity provider integration. In this case, you should trigger the email during signinWithPopup or getRedirectResult if using signInWithRedirect. Example using signinWithPopup: firebase.auth().signInWithPopup(provider).then(async result => { const user = result.user; const sendMail = await api.sendMail(user.email); }).catch(function(error) { // Handle Errors here. }); Example using signInWithRedirect: firebase.auth().getRedirectResult().then(async result => { if (result.credential) { const user = result.user; const sendMail = await api.sendMail(user.email); } }).catch(function(error) { // Handle Errors here. });
[ "ethereum.stackexchange", "0000052438.txt" ]
Q: Can I set the block size in genesis block by puppeth? Found the block size is set to 30K in genesis block. How can I modify this value to 100K or 1M by puppeth? A: To increase block size you have to increase the gasLimit of a block so that more transaction can be included in block, ultimately block size increase.
[ "chemistry.stackexchange", "0000054115.txt" ]
Q: Quadrupole moment of a molecule What is a quadrupole moment of a molecule and how does it arise? How is it measured for a particular molecule? I've read the Wikipedia article on quadrupoles and understand that it has to do with the distribution of charge, but I'd like a more chemistry-oriented explanation. A: What is a quadrupole moment of a molecule and how does it arise? This explanation is geared at someone with one year of chemistry. It captures the gist but is not rigorous: To test for monopoles, dipoles or quadrupoles in a molecule or ion, assign charges or partial charges to each atoms. For partial charges, δ+ and δ- is fine (if you want estimated values for partial charges of simple molecules, use a tool like MolCalc). To test for monopoles (ions), add up all the charges. If they are non-zero, it's an ion. If the net charge is zero, test for presence of a dipole: If you can draw a line through the molecule such that more negative partial charges are on one side of the line and more positive partial charges are on the other side of the line, it has a dipole moment. An example for water is below. If it does not have a dipole, you can check for a quadrupole moment: If you can draw an "X" through the molecule such that more negative partial charges are in opposite quadrants and more positive partial charges are in the other two quadrants, it has a quadrupole moment. The animated GIF shows the model of carbon dioxide rotated in the presence of such an "X" (or "+" in this orientation if you will). In one orientation (where it is diagonal), the negative partial charges of oxygen are in opposite quadrants, while the positive partial charge is in the center (neither quadrant), showing that it has a quadrupole moment. For a definition of the quadrupole moment (i.e. how to calculate it from a given charge distribution), take a look at this section of the wikipedia article on multipole expansions, which I found when reading the answer to Can nonpolar molecules exhibit dipole-dipole forces?. How is it measured for a particular molecule? The accepted answer for this question cites a paper describing one method.
[ "stackoverflow", "0035480169.txt" ]
Q: How to integrate Actor IM android app with local server I am working with Actor Instance Messaging Platform and for now, I have installed and run it's local server, and also imported and compiled the android app in Android Studio. Now I want to configure the android app to work with the local server I have, but I have no idea where to apply the configurations and settings. Here is the link to the project's repository in GitHub. Has anyone ever worked with it or has any idea about how I can integrate these two? Thanks in advance. A: I found the solution to the problem, by the way the application's development team have introduced the solution to this problem in their newly released documentation, which I post the link to it here. Actor Documentation
[ "stackoverflow", "0037168225.txt" ]
Q: How to iterate through multiple object keys in 1 for() loop x = {a:1,b:2} y = {c:3,d:4} for (k in x+y) { console.log(k) } Desired output: a b c d I'm more used to Python in which case this would be easier but Javascript doesn't seem to let me do this. I want to do this in the simplest way possible because simplicity is bliss. If I can't do it simply, I'm afraid I might need to just combine x and y into 1 Object and add a 'type' key to each of their keys so I can filter by them, but I thought having pre-filtered keys as their own top-level Objects was more readable. A: You can use two loops and move the code to a function in order to avoid repetition. function iteration(key) { // ... } for (var key in x) iteration(key); for (var key in y) iteration(key); Or merge the two objects into a new one for (var key in Object.assign({}, x, y) { // ... }
[ "stackoverflow", "0004299094.txt" ]
Q: How to store persons name in a record table Intro Damn, this is harder then I thought. Some people have camel-case names like McDonald or O'Ferncher, and some do not have double-barrelled name, but hyphenated name like Bowes-Lyon or just given name, like Honovi Hohnihhohkaiyohos ( Strong High Backed Wolf ). In some culture spaces like: Portuguese you have more then 1 family name and more then 1 first name (by default). Russia you have middle name (patronymic), that is obligatory. In some places you have gender inequality and to formally address a person you need to use prefix, like: Sir (where gender can be male, female and in-between). And yes, prefix changes depending on the persons age. Like this is not enough - people can and will get married (this occurs pretty often)(thy might do this multiple times), and it is a default custom for at least one partner to change their family name. In most places people can change their name or at least given name. More details This is not important if you want to answer the question, just giving a hint what I'm trying to do. Tables where I want to store the names are in xml and appengine datastore with twig object store interface (I use twig among other things, for it enables me to compile schema). Data itself can come form various places and probably there exists a case where old name is used (so - storing multiple names). My best guess is: @XmlAttribute @Key protected Long id; @XmlElement(required = true) final protected List<String> lastName; @XmlElement(required = false) protected String middleName; @XmlElement(required = true) final protected List<String> firstName; @XmlElement(required = true) protected Boolean isMale; @XmlElement(required = true) protected Date birthday; //+locale for naming? Writing function or preconditions for compareTo method just makes My day ... I'm seriously considering 0 fault tolerance. Yes, meaning existence or lack of apostrophes, whitespace and other symbols or case difference can yield to different results. (And for cynical bastards - this is not homework.) The question was: How to store persons name in a record table? A: If you are looking for a simple, universal solution, I think you will find that there is none. Read this blog posting, and weep. And when you've finished crying, take a look at this document, which attempts to model names for a US American audience. Obviously it makes a lot of simplifying assumptions, which are probably invalid.
[ "stackoverflow", "0029054618.txt" ]
Q: Android Add Items One By One Into a LinearLayout I'm new to Android and I'm trying to find out how to do that: - I have an activity with a ScrollView and inside it I have a LinearLayout (R.id.my_layout) - I nedd to add TextView programmatically so I'm doing this: I load the main XML layout via seContentView, I refer to my LinearLayout inside the ScrollView as "mLayout" and so on. I load a list of names from a file and with a function called populateList()I do: private void populateList() { try { for (final String team : mTeams) { rCount++; addRow(team); } } The addRow() method just create a new LinearLayout (mRow), a TextView, 2 Button, add the TextView and the 2 Buttons to the LinearLayout, and then I use addView to add the new mRow to the mLayout. Everything is working fine, but the ScrollView is shown only when i finished creating the list (so when the populateList() ends). What I would like to do is to show the rows one by one in sequence to give the activty a better look and a bit of animation. Is there a way to do this? I hope i was able to explain it :-) Thank you A: new Thread(new Runnable() { // i am creating the new thread @Override public void run() { // so call populateList() function here } }).start(); and for your addRow(String string) method the place you call View.addView(); edit it this way and place the following code in your addRow(String string) method View.post(new new Runnable() {// view here is mlayout the scrollView. @Override public void run() { mlayout.addView(yourview); // note yourview should be final, //eclipse might help you with that } }); remember to declare mlayout globally, so you do not have to attach final
[ "stackoverflow", "0010088930.txt" ]
Q: How to change an img width depending on img height I need to change img width depending on img height. I used the jQuery height property but it doesn't work. Please see my function below. $(function imagesSizer(){ var img = document.getElementsByClassName('.offer_img'); if ($('.offer_img').height() < 210) { $('.offer_img').css('width','360px') } }); A: You should try //Wait until the DOM is ready $(function(){ //get all images and iterate over them $('.offer_img').each(function(){; //if the height of this img is < 210 if ($(this).height() < 210) { //set the width to 360 $(this).width(360); } }); });
[ "stackoverflow", "0033096222.txt" ]
Q: Span element in PHP function not reflecting with Styles Can please anyone assist to fix these two issues in PHP Code. Span Inside DIV is not reflecting in Blue Color. Italics text also reflecting inside DIV with Bakground Color: #DCDCDC. It should be outside of DIV. function send_admin_notification($post_id,$post_title) { $blogname = get_option('blogname'); $email = get_option('admin_email'); $headers = "MIME-Version: 1.0\r\n" . "From:".$blogname." "." < ".$email.">\n" . "Content-Type: text/HTML; charset=\"" . get_option('blog_charset') . "\"\r\n"; $message = __('A new post has been submitted in ','accesspress-anonymous-post').$blogname.'site.'.' <br/> <br/>'. ' <div style="background-color:#DCDCDC;"> <span style="font-color:Blue" New Post Submission </span>'.' <br/> <br/>'; 'Post Title: '.$post_title.' <br/> <br/>'; 'Post Module: '.$post_title.' <br/> <br/> </div>'; $post_author_name = get_post_meta($post_id,'ap_author_name',true); $post_author_email = get_post_meta($post_id,'ap_author_email',true); $post_author_url = get_post_meta($post_id,'ap_author_url',true); if($post_author_name!=''){ $message .= 'Post Author Name: '.$post_author_name.' <br/> <br/>'; } if($post_author_email!=''){ $message .= 'Post Author Email: '.$post_author_email.' <br/> <br/>'; } if($post_author_url!=''){ $message .= 'Post Author URL: '.$post_author_url.' <br/> <br/>'; } $message .= ' <br/> <br/>'.__(' <i>This is an auto generated email. For more details regarding this, please login to Wiki website','accesspress-anonymous-post.</i>'); $subject = __('Process Wiki | New Post Submission','.$post_title.'); wp_mail($email,$subject,$message,$headers); } A: span hasn't been closed properly <span style="font-color:Blue" New Post Submission </span>' use the below one <span style="color:Blue"> New Post Submission </span>
[ "buddhism.stackexchange", "0000034070.txt" ]
Q: Sankhara meditation Could someone explain to me how to meditate in order to see how the sankharas can be manipulated and changed so to not feel that the current situation is fixed and a must and helpless. I read somewhere that this was possible and in my personal practice that would be really helpful. From what I have heard there are 3 Sankharas : Kaya,vaci and citta or mano. How do i manipulate them during meditation and in what way do i manipulate them so I can see that there is free will and that I am not helpless could you describe with what particular technique do i manipulate or change a particular sankhara, I really need to understand it so that I can feel that these things are not a must because it seems like a must for me. (especially my feelings seems fixed and like a must) Perhaps my perceptions are messing things up to so I really want to feel that I have power over my situation by direct seeing that these things are not a must and get be manipulated and changed beacuse now it seems like a must. But I would appreciate all possible advice you could give not just about manipulating feelings during meditation but all other Sankharas or aggregates and the technique used and which sankhara or aggregate is manipulated during that particular technique. Also 1 more question. Are sankharas volitions (things we do uknowingly that can be stopped with free will) to me its like they have power over me is that ultimate truth, Because from my first question as you saw there was Monk that said that theese things could be manipulated that seems like they are not a must and can with free will and skillful attention,mindfulness be stopped if yes please tell me how and please describe how and what is happening and I will try it. Thank you all. A: Formations (Sankhara) There are 3 kinds of formations as you identified: Ayya, how many kinds of formation are there? Avuso Visākha, there are these 3 kinds of formation bodily formation, kāya,saṅkhāra verbal formation, vacī,saṅkhāra thought formation. citta,saṅkhāra Cūla Vedalla Sutta What are they? But what, ayya, is bodily formation, what is verbal formation, what is thought formation? Visākha, The in-and-out breaths, are bodily formation. Thinking and pondering are verbal formation. Perception and feeling are thought formation. Cūla Vedalla Sutta Why these? But, ayya, why are the in-and-out-breaths bodily formation; why are thinking and pondering verbal formation; why are perception and feeling thought formation? The in-and-out-breaths, avuso Visākha—these are states bound up with the body. Therefore, they are bodily formation. Avuso Visākha, one, having first thought and pondered, then breaks out into speech. Therefore, thinking and pondering are verbal formation. Perception and feeling—these are mentally-connected states, bound up with the mind. Therefore, perception and feeling are thought formation. Cūla Vedalla Sutta Formations are due to volition and cause the arising of future volition. Also, it is volition which is the forerunner for karmic action. Since karma is backed by volition doing karmic action result in formations. One cannot manipulate the formations as they are not-self. (Dhammapada Verse 279: "All phenomena (dhammas) are without Self"; when one sees this with Insight-wisdom, one becomes weary of dukkha (i.e., the khandhas). This is the Path to Purity) The past store of formations will remain as they are until they give results. Only then will past formations dissolve, will they cease to exist. The timing of karma is not in one's control. This cannot be changed or manipulated, as this is not in one's control. But one can calm them (this is like stilling a muddy pond: the water becomes clear but the mud remains), prevent them from arising or create new ones to dilute past formations. Caliming Formations Calming Bodily Formations To calm bodily formation or the breath one can use breath meditation. The calming does not happen immediately but when one reacher stage 4 of the breath meditation: (4) He trains himself thus: ‘Calming the bodily formation (of breath), I will breathe in’; He trains himself thus: ‘Calming the bodily formation (of breath), I will breathe out’; Ānâpāna,sati Sutta Calming Verbal Formations Verbal formation or thinking and pondering of the mind is calmed by concentration. What is concentration and how is concentration achieved? (11) Now, ayya, what is mental cultivation? What are the objects of mental cultivation? What are the requisites of mental cultivation? What is the cultivation of samadhi? Avuso Visākha, the one-pointedness of mind (cittassa ek’aggatā)—this is samadhi [mental stillness]. The 4 focuses of mindfulness (sati’paṭṭhāna)—these are the mental signs (nimitta) for samadhi. The 4 right efforts (samma-p.padhāna)—these are the requisites of samadhi. These states that are much cultivated, associated with, grown—this is here the cultivation of samadhi. Cūla Vedalla Sutta When initial and sustained through stops then thinking and pondering stops. This happens in the 2nd Jhana and beyond. See: Vitakka,vicāra by Piya Tan. For more on The 4 focuses of mindfulness (sati’paṭṭhāna) see: Mahā Satipatthāna Sutta For more on The 4 right efforts (samma-p.padhāna) see: (Catu) Padhāna Sutta Calming Through Formations Steps 7 and 8 of Anapanasati deals with calming the mind. The 2nd in the 2nd triad which is Mindfulness of Feelings. One uses the blissful feeling arisen from the breath meditation to do the calming. (7) He trains himself thus: ‘Knowing the mental formations [mental functions], I will breathe in’; He trains himself thus: ‘Knowing the mental formations [mental functions], I will breathe out’; (8) He trains himself thus: ‘Calming the mental formations [mental functions], I will breathe in’; He trains himself thus: ‘Calming the mental formations [mental functions], I will breathe out’; Ānâpāna,sati Sutta Stoping and Preventing Formation Cessation of Through Formations (and other formations) Though formations or perception and feeling are stopped by being in Nirodha or Pala Samapatthi. This is the cessation of perception and feeling. Nirodha Samapatthi is achieved after This is achieved in the 8th Jhana. Pala Samapatthi is achieved when one realises Nirvana through the practice of the Noble 8 Fold Path and completing the 3 fold training. See discussion in Cūla Vedalla Sutta. In Nirodha Samapatthi, bodily and verbal formations would also be already suspended. See Cūla Vedalla Sutta. Also, all past formations will be suspended. Once one comes out of it the part formations will become effective again. NB: for an enlightened person past formations are effective but new formations do not arise. Preventing Formation from Arising Feeling result in craving according to dependent origination. Craving leads to formations. In order to prevent formations arising one has to break the arising of craving at feelings. The Blessed One said this: “And what, bhikshus, is dependent arising? With ignorance as condition, there are volitional formations; with volitional formations as condition, there is consciousness; with consciousness as condition, there is name-and-form; with name-and-form as condition, there are the six sense-bases; with the six sense-bases as condition, there is contact; with contact as condition, there is feeling; with feeling as condition, there is craving; with craving as condition, there is clinging; with clinging as condition, there is existence; with existence as condition, there is birth; with birth as condition, there arise decay and death, sorrow, lamentation, physical pain, mental pain and despair. Such is the origin of this whole mass of suffering. (Paṭicca,samuppada) Vibhanga Sutta Past conditioning creates input for the dependent origination. How you react creates conditioning now which gives result in the future. The way not to create new formations at the present moment is: you have to know the feeling know that it is impermanent do not cling onto the feeling To further elaborate: Know the feeling i. On seeing a form with the eye, one investigates the form that is the basis for mental joy, one investigates the form that is the basis of mental pain, one investigates the form that is the basis of equanimity. ii. On hearing a sound with the ear, one investigates the sound that is the basis for mental joy, one investigates the sound that is the basis of mental pain, one investigates the sound that the basis of equanimity. iii. On smelling a smell with the nose, one investigates the smell that is the basis for mental joy, one investigates the smell that is the basis of mental pain, one investigates the smell that is the basis of equanimity. iv. On tasting a taste with the tongue, one investigates the taste that is the basis for mental joy, one investigates the taste that is the basis of mental pain, one investigates the taste that is the basis of equanimity. v. On feeling a touch with the body, one investigates the touch that is the basis for mental joy, one investigates the touch that is the basis of mental pain, one investigates the touch that is the basis of equanimity. vi. On cognizing a mind-object with the mind, one investigates the mind-object that the basis of mental joy, one investigates the mind-object that is the basis of mental pain, one investigates the mind-object that is the basis of equanimity. Dhātu Vibhaṅga Sutta Know that the feels are impermanent so do not cling onto them If he feels a pleasant feeling, he understands that it is impermanent; he understands that it is not to be clung to; he understands that there is no delight in it. If he feels a painful feeling, he understands that it is impermanent; he understands that it is not to be clung to; he understands that there is no delight in it. If he feels a neutral feeling, he understands that it is impermanent; he understands that it is not to be clung to; he understands that there is no delight in it. If he feels a pleasant feeling, he feels it in a detached manner. If he feels a painful feeling, he feels it in a detached manner. If he feels a neutral feeling, he feels it in a detached manner. Dhātu Vibhaṅga Sutta Also, see: Nibbida by Piya Tan Accumulating Formations Accumulating Karmicly Positive Formations You can achieve this by doing positive bodily, verbal and mental action. You can engage in: Giving (Dāna-maya) Virtue (Sīla-maya) Mental development (Bhāvanā-maya) Honoring others (Apacāyana-maya) Offering service (Veyyāvaca-maya) Dedicating (or transferring) merit to others (Pāli:Pattidāna-maya; Sanskrit: puṇyapariṇāmanā) Rejoicing in others' merit (Pattānumodanā-maya) Listening to teachings (Dhammassavana-maya) Instructing others in the teachings (Dhammadesanā-maya) Straightening one's own views in accordance with the Teachings (Diṭṭhujukamma) Merit (Buddhism) Also, the accumulation of more formations with positive karmic potent can dilute past karma. This is like adding more water to an existing amount of salt, i.e., dilutes the taste of salt. See: Loṇa,phala Sutta Not Accumulating Karmicly Negative Formations You can achieve this refraining from negative bodily, verbal and mental action. You can refrain from: In giving up the taking of life, the practitioner will accomplish freedom from vexations; In giving up stealing, the practitioner will find security in life, economically, socially and spiritually; In giving up wrongful (sexual) conduct, the practitioner will find inner peace and peace in the family life; In giving up lying, the practitioner will attain purity of speech and mind; In giving up slander, the practitioner will be protected socially and spiritually; In giving up harsh language, the practitioner's words will be more effective; In giving up frivolous speech, the practitioner will become wise and dignified; In giving up lust, the practitioner finds freedom in life through contentment and simplicity; In giving up hatred, the practitioner will develop kindness and gentleness; In giving up wrong views, the practitioner will not falter in the good and spiritual path. Merit (Buddhism) This is only like stopping the adding of salt into a glass of water. A lesser amount of salt means the salty taste is less. The salt one already put in will remain. See: Loṇa,phala Sutta If this is combined by adding more water like in the example above, while not adding more salt. The salty taste will quickly dilute. Controlling One's Perceptions Due to Feelings Regarding perceptions, they also arise due to feeling. “Bhikshu, as regards the source from which proliferation of conception and perception assails a person: if one were to find nothing there to delight in, nothing there to welcome, nothing to cling to—this is the end of the latent tendency of lust, the latent tendency of aversion, the latent tendency of views, the latent tendency of doubt, the latent tendency of conceit, the latent tendency of desire for existence, and the latent tendency of ignorance. This is the ending of the taking up of the rod and the sword, quarrels, disputes, mayhem [strife], slandering and lying —here these evil unwholesome states cease without remainder.” … Avuso, dependent on the [eye | ear | nose | tongue | body | mind] and [form | sound | smell | taste | touch | mind-object], [eye | ear | nose | tongue | body | mind]-consciousness arises. The meeting of the three is contact. With contact as condition, there is feeling. What one feels, one perceives. What one perceives, one thinks about. What one thinks about, one mentally proliferates. From that as source, proliferation of conception and perception assails a person regarding past, future and present [forms | sounds | smells | tastes | touch | mind-objects] cognizable through the [eye | ear | nose | tongue | body | mind]. Madhu,piṇḍika Sutta For a worldly person perceptions, thoughts, views that arise are subjected to the 4 pervertions (vipallasa), which are: what is impermanent is taken to be permanent; what is painful is taken to be pleasurable; what is not self is taken to be a (or the) self; and what is impure [unattractive or repulsive] is taken to be pure [attractive or beautiful] One should try to break this train also when feelins arise. The method to deal with preception is also as in the previous part, hence I will not repeat it here. If perceptions, thoughts, or views do arise one should straighten them by contemplating: Impermanent as impermanent Painful as painful Not-self as not-self Impure [unattractive or repulsive] as impure See Vipallasa Sutta Dantabhūmi Sutta one should abandon thoughts with regard to the Sathipattanas: (1) dwell observing the body in the body, and do not think (any) thought regarding the body; (2) dwell observing feelings in feelings, and do not think (any) thought regarding feelings; (3) dwell observing the mind in the mind, and do not think (any) thought regarding the mind [thoughts]; (4) dwell observing dharmas in the dharmas, and do not think (any) thought regarding dharmas [realities]. This way Vipallasa will not arise. Also, concept proliferation and throughs can be subdued by the 2nd Jhana and beyond. Summary To calm bodily formation do 1st triad of the Anapanasati Sutta. Bodily formations are fully suspended in the 4th Jhana as breathing stops. To calm verbal formation practice 2nd Jhana of above To calm through the formation do the 2nd triad of the Anapanasati Sutta. Though formations are fully suspended in Nirodha Samapatthi as both feeling and perception are suspended. To stop the accumulation of formations contemplate feeling are impermanent rid the mind of perversions (vipallasa) Jhana To make the accumulation of positive karmic formations be moral in bodily, verbal and mental conduct Not to accumulate of negative karmic formations refrain from negative bodily, verbal and mental conduct A: Could someone explain to me how to meditate in order to see how the sankharas can be manipulated and changed so to not feel that the current situation is fixed and a must and helpless. Buddhist practice primarily uses wisdom but also concentration, particularly when wisdom has developed concentration. "Remembering" to be wise or use wisdom is the meaning of "mindfulness". "Mindfulness" is "remembering". Mindfulness remembers to bring & use wisdom. From what I have heard there are 3 Sankharas : Kaya, vaci and citta or mano. "Mano sankhara" is found in more mundane teachings about "kamma" and is possibly an Abhidhamma teaching added at a later time to the Pali suttas. We can ignore this matter for now and say: Kaya sankhara = in & out breathing Vaci sankhara = thinking Citta sankhara = perception & feeling Note: The word "sankhara" above does not mean "formation", "fabrication" or "condition". It means "fabricator" or "conditioner". For example, thinking is the verbal conditioner (vaci sankhara) because it conditions or fabricates speech. Try to be logical. Try to avoid translations that create confusion. How do i manipulate them during meditation and in what way do i manipulate them so I can see that there is free will and that I am not helpless could you describe with what particular technique do i manipulate or change a particular sankhara. Citta sankhara is too subtle to manipulate or control for a newbie. Therefore, you should focus on controlling kaya sankhara & vaci sankhara. How to control vaci sankhara is described in MN 19 and many other suttas, such as MN 61 & MN 20. How to control kaya sankhara is described in MN 118. Perhaps my perceptions are messing things up to so I really want to feel that I have power over my situation by direct seeing that these things are not a must and get be manipulated and changed beacuse now it seems like a must. The problem is your "views" & "thinking" rather than "perceptions". Generally, for a stable mind, it is moral views (good & bad) that need to be sorted out. Thus, refer to MN 61 & MN 19, as I suggested. Are sankharas volitions (things we do uknowingly that can be stopped with free will) to me its like they have power over me is that ultimate truth. The word "sankhara" does not always mean "volitional formations". In certainly contexts, such as 2nd condition of Dependent Origination, sankhara are not "volitional" but are non-volitional; arising spontaneously from ignorance; without our decision or control: so it is best to give up the translation "volitional formations". If you read MN 19, as I recommended, you will understand how there is unwise thinking arising without free will (called "sankhara" in Dependent Origination) and there is also wise thinking (called "paṭisañcikkhato") that is used to stop the unwise thinking . MN 19 is the most important sutta about controlling vaci sankhara or ignorant thinking. In summary, instead of being concerned with the term "volitional formations", please focus on two terms, namely: (i) unwise thinking; and (ii) wise thinking. Like the Buddha-To-Be, you must use wise thinking to conquer unwise thinking. Because from my first question as you saw there was Monk that said that these things could be manipulated that seems like they are not a must and can with free will and skillful attention,mindfulness be stopped if yes please tell me how and please describe how and what is happening and I will try it. Thank you all. Your questions are answered in MN 19. Read MN 19 carefully and practise the teaching until you can emulate the Buddha-To-Be and walk in his noble footsteps. Also, try to control your breathing (kaya sankhara), to help you calm down. At the very least, for a short time, practise some deliberate long breathing, including counting breaths. While this is not true Anapanasati, it can still help control the mind, body & impulses ("asava"). However, the most important practise is controlling the vaci sankhara using the methods in MN 19, MN 61, MN 20, etc. Use wise thinking to conquer unwise thinking. Once you can control your thoughts so your thoughts are only moral wholesome non-harmful thoughts, then you can practise Anapanasati in the proper more refined way & attain stream-entry. A: A Mahayana answer here, based on the live chain of enlightened teachers starting from the Buddha, rather than on books. This is what I was taught by a teacher who mastered it in practice and then passed it on. Sankhara/Samskaras are tendencies to automatically react a certain way (physically, mentally, verbally, emotionally), based on some previous experience. For example, if you had a painful experience of getting assaulted, beaten up, and humiliated by a group of guys with shaved heads, you may have a fear of shaved heads for the rest of your life. Whenever you see a man with shaved head, you may have an automatic reaction of fear and aversion. Or, for example, when you were a very young boy, your mom had a certain hair style. And now you are attracted to young women with the same hair style. I'm oversimplifying on purpose, but you get the idea. This type of subconscious preconception is a Sankhara. In meditation your goal is to find Sankharas for the issues that bother you. Starting from the most painful ones and then going smaller and smaller. Or, you can do it going from the present time back into the past, one by one. Once you see each, you need to process them and let go. You process them by reviewing. Once you review it and process it, the emotional energy associated with the sankhara will get released, and you will be able to let it go. Here is how to review them properly. For example, today you met a man and you felt very stressed but did not know why. Go over today's situation. Relive it in your imagination. Then focus on the feeling you feel in or around your body, when you think about the situation. Try to go "inside" that feeling in or near your body. Concentrate on that feeling. The mind will give you a hint by showing you a flash of the "sign" it associates with the feeling. In this example, that sign is a picture of shaved head. You realize that you felt stressed because the man had a shaved head so you felt unsafe. Keep concentrating on the feeling and the sign at the same time, and try to remember how they are connected in the past. In this example you will remember the past assault. Go over the experience of assault and allow all your locked up emotions come out. Now think about the man you met today. Connect the past and the present. In both cases the sign was the same - the shaved head - but situations were different. Look at your mind and try to see directly how these past and present memories and feelings connect in your head. Keep processing it until you can let it go.
[ "stackoverflow", "0021226954.txt" ]
Q: Changing text of a h1 with jquery,, hey guys im trying to change the text of a h1 with jquery. i want to change the text every time enter key is pressed in a text area and the values are numeric values like on first enter the text should be 1 and on other it should be 2 and so on.. This is the code which im using... Jquery <script> $('#_co').bind('keypress', function(e) { //_co is the Id of Text area var code = e.keyCode || e.which; var id = 1; if(code == 13) { var text = $('#_line').text(); $('#_line').text(id); id++; } }); </script> Html <h1 id="_line">0</h4> A: Just move your declaration outside of that function, var id = 1; $('#_co').bind('keypress', function(e) { //_co is the Id of Text area var code = e.keyCode || e.which; if(code == 13) { var text = $('#_line').text(); $('#_line').text(id); id++; } }); And as Rohit said in the comment, You are having an invalid markup, Just close the h1 tag properly, <h1 id="_line">0</h1> As per your new requirement you can use .append() in your current context. var id = 1; $('#_co').bind('keypress', function(e) { //_co is the Id of Text area var code = e.keyCode || e.which; if(code == 13) { var text = $('#_line').text(); $('#_line').append('<br>' + id); id++; } }); DEMO
[ "stackoverflow", "0022585353.txt" ]
Q: YouTube-like Ajax Loading Bar not working I am using the YouTube-like Ajax Loading Bar to load a php file. This is my Javascript $(".ajax-call").loadingbar({ target: "#loadingbar-frame", replaceURL: false, direction: "right", async: true, complete: function(xhr, text) {}, cache: true, error: function(xhr, text, e) {}, global: true, headers: {}, statusCode: {}, success: function(data, text, xhr) {}, dataType: "html", done: function(data) {} }); This is my HTML <a href="load.php" class="ajax-call">..</a> <div id="loadingbar-frame"></div> This is load.php, the file that I'm trying to load <?php echo 'some content'; ?> I'm haven't used ajax before and I'm not sure why this isn't working. A: On success: function(data, text, xhr) {}, is where you get the response, in this example, data will be equal to "some content", so there you can work with the response, for example replace the content of your html page; success: function (data) { $('body').html(data); }
[ "stackoverflow", "0007848015.txt" ]
Q: How to query nested information in RavenDB? I have the following document called Reservation: { "CustomerId": 1, "Items": [ { "EmployeeId": "employees/1", "StartTime": "2011-08-15T07:20:00.0000000+03:00", "EndTime": "2011-08-15T07:40:00.0000000+03:00" }, { "EmployeeId": "employees/1", "StartTime": "2011-08-15T07:40:00.0000000+03:00", "EndTime": "2011-08-15T09:10:00.0000000+03:00" }, { "EmployeeId": "employees/3", "StartTime": "2011-08-16T07:20:00.0000000+03:00", "EndTime": "2011-08-16T11:35:00.0000000+03:00" } ] "ReservedAt": "2011-10-20T15:28:21.9941878+03:00" } In addition I have the following projection class: public class ReservationItemProjection { public string ReservationId { get; set; } public string CustomerId { get; set; } public string EmployeeId { get; set; } public DateTime StartTime { get; set; } public DateTime EndTime { get; set; } } What kind of index and query do I write if I want to find matching ReservationItemProjections? E.g.: // invalid example query: var matches = docs.Query<ReservationItemProjection, ReservationItemProjectionsIndex>() .Where(x => x.EmployeeId == "employees/1" && x.StartTime >= minTime && x.EndTime <= maxTime) .ToList(); Please note, that I do not wish to get a list of Reservation documents but a list of ReservationItemProjection objects. The documentation says: But while just getting the documents matching a particular query is useful, we can do better than that. Instead of getting the documents themselves, I want to get the values directly from the index, without getting the full document. I have already tried using an index like this: public class ReservationItemProjectionsIndex : AbstractIndexCreationTask<Reservation, ReservationItemProjection> { public ReservationItemProjectionsIndex() { Map = reservations => from reservation in reservations from item in reservation.Items select new { ReservationId = reservation.Id, CustomerId = reservation.CustomerId, item.EmployeeId, item.StartTime, item.EndTime }; Store(x => x.ReservationId, FieldStorage.Yes); Store(x => x.CustomerId, FieldStorage.Yes); Store(x => x.EmployeeId, FieldStorage.Yes); Store(x => x.StartTime, FieldStorage.Yes); Store(x => x.EndTime, FieldStorage.Yes); } } Somehow I can't get the query and index working: it either throws an exception about not being able to cast from ReservationItemProjection to Reservation or, when I have been able to get the ReservationItemProjection objects, they will have included all Items in all Reservations that have even one matching Item, even though my query has the Where-clause x.EmployeeId == "employees/1". Summary: what is the required index? Does the index need only a Map clause or also Reduce or TransformResults? How do I write the query in C#? A: Kasper, In RavenDB, you are querying for documents. While it is technically possible to do what you want, it is usually meaningless to do so, because the projected information doesn't have the required context to do something with it. What is it that you are trying to do? For reference, the index would be something like: from doc in docs.Items from reservation in doc.Reservations select new { reservation.EmployeeId, reservation.Start, reservation.End } Then, mark EmployeeId, Start and End as Store. Now, in your query, issue: session.Query<...,...>().AsProjection<ReservationProjection>().ToList(); The AsProjection call will let the DB know that you want the values from the index, not the document
[ "stackoverflow", "0020903990.txt" ]
Q: PHP: mcrypt_ecb is not working inside a function I've got a very simple function: $me = 45S237s53dsSerwjw53s23rjf; //Some long encrypted string. function decrypt($user){ $user = pack("H*" , $user); //Converting from hexadecimal to binary $user = mcrypt_ecb(MCRYPT_DES, $key, $user, MCRYPT_DECRYPT); //Decrypting return $user; } The problem is if I do go echo decrypt($me); it doesn't work, I don't end up with a decrypted string. However if I do essentially the same thing without using a function it works: $user = $me; $user = pack("H*" , $user); $user = mcrypt_ecb(MCRYPT_DES, $key, $user, MCRYPT_DECRYPT); echo $user; //Works fine... What's going on here? A: Your missing the $key variable inside the function body. With the correct error level settings you'd have been given a warning, that $key is undefined. Either add $key as a function argument or define $key inside the function body (or, third alternative, import $key from the global scope). 1 function decrypt($user, $key){ //... } 2 function decrypt($user){ $key = '....whatever...'; //... } 3.1 function decrypt($user){ global $key; //... } 3.2 function decrypt($user){ //... $user = mcrypt_ecb(MCRYPT_DES, $GLOBALS['key'], $user, MCRYPT_DECRYPT); //... }
[ "stackoverflow", "0023293980.txt" ]
Q: Show popup menu when action bar item is clicked How to add a menu popup when an action bar item is clicked (see screenshot)? I want the menu item to show an icon. tHings I have tried: Setting actionProvider (support lib v7) for the action bar item. In the actionProvider, return null for onCreateActionView. In onPrepareSubMenu, populate the submenu. This works on Android 2.x but not Android 4.0, and for Android 2.x, there is no icon. In the actionProvider, create a imageview and on clicking, shows a PopupMenu, but popup menu has no icon, when I have specifically used setIcon to show it. I don't understand why PopupMenu does not show any icon. I followed the "official" code as closely as possible but to no avail. http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.1_r1/android/widget/ShareActionProvider.java#195 Please help! Thanks! A: Use popUpMenu ->>> Follow> res/menu/horario.xml <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/menu_MudaDia" android:titleCondensed="Mudar Dia" android:title="Mudar Dia" android:icon="@drawable/ic_menu_popup" android:showAsAction="always"> </item> activity.class @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { menu.clear(); inflater.inflate(R.menu.horario, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_MudaDia: View vItem = getActivity().findViewById(R.id.menu_MudaDia); PopupMenu popMenu = new PopupMenu(getActivity(), vItem); for (int i = 0; i < diaSemana.length; i++) { popMenu.getMenu().add(0, i, i, diaSemana[i]); } popMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { DIA = diaSemana[item.getItemId()]; atualizaGUI(); return true; } }); popMenu.show(); break; default: break; } return super.onOptionsItemSelected(item); }
[ "stackoverflow", "0035840137.txt" ]
Q: Write xml in root I'm currently trying to write a XML file in ASP.Net (see code below). It is not the writing that doesn't work, but when I run the code, it returns an error: Access to the path 'C:\Program Files\IIS Express\devices.xml' is denied. This is not the directory of my project, so I don't know why it's trying to save the XML right there. If this is the problem of the error, how do I make sure the XML is saving to my project root? Else, what is wrong here and what do I have to do? Code ArrayList devices = new ArrayList(); devices.Add(new Device()); XmlTextWriter writer = new XmlTextWriter("devices.xml", Encoding.UTF8); writer.WriteStartDocument(); foreach(Device device in devices) { writer.WriteStartElement("device"); writer.WriteStartElement("name"); writer.WriteString(device.name); writer.WriteEndElement(); writer.WriteEndElement(); } writer.WriteEndDocument(); writer.Close(); A: I think you should use Server.MapPath() to get the proper path to where your application is running, so: new XmlTextWriter(Server.MapPath("~/devices.xml"), Encoding.UTF8); See if that helps you?
[ "stackoverflow", "0053970827.txt" ]
Q: How to fix "Cannot commit when autoCommit is enabled" exception while connecting to PostgreSQL We are in a phase where we need to replace H2 database by Postgresql database for our application. We followed the guidelines given in the below URLs. URL: How can the Corda node be extended to work with databases other than H2? URL: Replacing h2 database with some other relational database in Corda However, the node that is to be connected to Postgresql fails to run and an exception "Cannot commit when autoCommit is enabled" is thrown. We set the autocommit off in Postgresql by running command "\set autocommit off;" in PSQL tool, but still the above exception is thrown by the node. We are using V1 of Corda. Should we migrate to higher version - V2, V3? A: In the related stack question (below link), it is answered that postgresql is supported by corda versions 2 and above. (Using PostgreSQL instead of H2 as the Corda node's database) The auto-commit issue found in corda version 1 may not exist in corda versions 2 and above.
[ "gardening.stackexchange", "0000027333.txt" ]
Q: Excavating a yard I have some landscaping work to do around my house. Am planning to start off with a 1.5' x 4" trench around the house, followed by a ~4' x 12 " plant bed , followed by a 2' x 6" trench for a walkway. Attached is an image describing the scope. Couple of questions : Are the trench depths okay ? How do I go about with trenching out the yard (with different depths for each area) ? Other details : I've checked with utilities and its all good. There is a positive grade around the house. Thanks in advance ! A: If your trench or excavated areas are in widths suitable for a bobcat bucket (48" - 60" depending on the model) then rent one of those for a day. More fun than you can imagine and good for moving any bulk item in quantity. Otherwise it is hand dig time. A good wheelbarrow and dump bin located close to the work area are time and labour savers. When calculating volumes add or subtract a factor of one third to account for fluffing up of removed material and compaction of newly added material. I also highly recommend a laser level and willing accomplice. Nothing says professional more than straight and level where called for. You don't say what you want to do with the trench. I know I would want to install my good friend 4" drain pipe with sleeve. You may have a positive grade to shed water from your roof away from the house but nothing says peace of mind better during that one in a hundred year storm than drain pipe installed around the perimeter. By the way, if you are going to do a walkway in any part of the world where it gets cold you will want to provide a good base and dig deeper to do this. Please provide more details.
[ "math.stackexchange", "0002763875.txt" ]
Q: What is the derivative of this function: $\frac {d}{dx}x^{\lfloor{x}\rfloor}?$ What is the derivative of the following function? $$\frac {d}{dx}x^{\lfloor{x}\rfloor}$$ Here, $\lfloor x \rfloor$ is the floor function. I tried: $$\frac {d}{dx} x^x=\frac {d}{dx} e^{x \ln x}=x^x (\ln x +1)+C$$ But, here $\lfloor{x}\rfloor$ is problematic for me. A: The function has discontinuities at integer values of $x$. Other than that, you can evaluate the derivatives using $\frac{d}{dx}x^a=ax^{a-1}$ because $\lfloor x\rfloor$ is constant for $a < x < a+1$, where $a \in \mathbb{Z}$. To summarize, the derivative of $x^{\lfloor x \rfloor}$ when it exists is $$\lfloor x \rfloor x^{\lfloor x \rfloor-1}.$$ A: Suppose $x\in[n,n+1)$, where $n$ is an integer. Then $$ f(x)=x^n $$ and so $f$ coincides with $x^n$ over the open interval $(n,n+1)$. Hence $f'(x)=nx^{n-1}$ for $x\in(n,n+1)$. Thus, for noninteger $x$, $$ f'(x)=\lfloor x\rfloor x^{\lfloor x\rfloor-1} $$ The problem is now to see whether $f$ is differentiable at integers. But, if $n\ne0$ is an integer $$ \lim_{x\to n^+}x^{\lfloor x\rfloor}=\lim_{x\to n^+}x^n=n^n $$ whereas $$ \lim_{x\to n^-}x^{\lfloor x\rfloor}=\lim_{x\to n^-}x^{n-1}=n^{n-1} $$ The limits are different when $n\ne1$. Also $$ \lim_{x\to0^+}f(x)=1 \qquad \lim_{x\to0^-}f(x)=-\infty $$ This shows the function is not continuous at the integers $\ne1$, so not differentiable either. Now try and see if the derivative exists at $x=1$.
[ "es.stackoverflow", "0000071855.txt" ]
Q: Calendario en android usando Date Picket Estoy tratando de agregar un calendario a mi aplicación, mi código es el siguiente: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calendar); btn_fecha = (Button)findViewById(R.id.btn_fecha); btn_hora = (Button)findViewById(R.id.btn_hora); btn_next_fecha = (Button)findViewById(R.id.btn_next_fecha); eFecha = (EditText)findViewById(R.id.eFecha); eHora = (EditText)findViewById(R.id.eHora); btn_fecha.setOnClickListener(this); btn_hora.setOnClickListener(this); } @Override protected void onResume() { super.onResume(); btn_next_fecha = (Button)findViewById(R.id.btn_next_fecha); btn_next_fecha.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent btn_next_fecha = new Intent(SelectDayActivity.this, DatosAutoActivity.class); startActivity(btn_next_fecha); } }); } @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onClick(View v) { if (v==btn_fecha){ final Calendar c = Calendar.getInstance(); dia = c.get(Calendar.DAY_OF_MONTH); mes = c.get(Calendar.MONTH); ano = c.get(Calendar.YEAR); DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { eFecha.setText(dayOfMonth+"/"+(month+1)+"/"+year); } } ,dia, mes, ano); datePickerDialog.show(); } Mi código funciona, sin embargo, cuando aparece el calendario muestra el año 1900 y me gustaría que apareciera la fecha de hoy (la fecha actual que tiene el celular) Me podrían apoyar para hacer eso? Gracias A: Agrega esta línea : dpd.getDatePicker().setMinDate(System.currentTimeMillis()); debajo de: @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { eFecha.setText(dayOfMonth+"/"+(month+1)+"/"+year); } } ,dia, mes, ano); ----> Agregala aqui <------- datePickerDialog.show();
[ "stackoverflow", "0035917155.txt" ]
Q: how generate user profile from db after login mvc 4 I want to create login page after login success, It should go to user profile generated from database.this is my home controller. namespace webSite.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } public ActionResult Login() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(User u) { // this action is for handle post (login) if (ModelState.IsValid) // this is check validity { using (projectEntities dc = new projectEntities()) { var v = dc.service_provider.Where(a => a.Sp_email.Equals(u.Email) && a.Sp_password.Equals(u.Password)).FirstOrDefault(); if (v != null) { return RedirectToAction("AfterLogin"); } } } return View(u); } public ActionResult AfterLogin() { return View(); } public ActionResult Register() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Register(service_provider U) { if (ModelState.IsValid) { using (projectEntities dc = new projectEntities()) { //you should check duplicate registration here if (U != null) { dc.service_provider.Add(U); dc.SaveChanges(); ModelState.Clear(); U = null; ViewBag.Message = "Successfully Registration Done"; } else { throw new Exception(); } } } return View(U); } } } I want to generate user profile after login. A: public ActionResult Login(User u) { // this action is for handle post (login) if (ModelState.IsValid) // this is check validity { using (projectEntities dc = new projectEntities()) { var v = dc.service_provider.Where(a => a.Sp_email.Equals(u.Email) && a.Sp_password.Equals(u.Password)).FirstOrDefault(); if (v != null) { //return RedirectToAction("AfterLogin"); int id = u.ID; // assign your valid user's id and pass it to AfterLogin Action return RedirectToAction("AfterLogin", new {@id=id}); } } } return View(u); } public ActionResult AfterLogin(int id) { User u = // select your user's data using id and assign to a user object return View(u); // and pass the user object to view } in view - @model Project.DataObject.User // path to User @{ ViewBag.Title = "User Profile"; } <input type="text" id="txtName" value="@Model.Name"> //Get user's name
[ "gis.stackexchange", "0000083205.txt" ]
Q: Configuration for GeoWebCache in Geoserver 2.4.0 I have developed a web map application by using Geoserver 2.4.0 and tomcat 7 in Windows XP. I have tried to configure the GeoWebCache for WMS layers to speed up the service but unfortunately it didn't work for me. I did something wrong in configuration steps. Kindly Help me to achieve this. I have attached some screenshots for reference. I have created New Gridset for EPSG:404000 I have tested with XXX.XXX.X.XX:8080/geoserver/gwc/demo Link: My layer setting is: And My Geoserver Log is: at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) 2014-01-18 10:30:31,901 ERROR [geowebcache.GeoWebCacheDispatcher] - Problem communicating with GeoServer http://xxx.xxx.x.xx:8080/geoserver/gwc/service/wms 2014-01-18 10:30:31,901 INFO [geoserver.wms] - Request: getServiceInfo 2014-01-18 10:30:31,901 ERROR [geoserver.ows] - org.geoserver.platform.ServiceException: No such style: ODC_Raster at org.geoserver.wms.map.GetMapKvpRequestReader.parseStyles(GetMapKvpRequestReader.java:1386) My Default Raster Style: My Custome Raster Style: Thanks in advance A: As you can see in the browser there are no png tiles in the GeoWebCache. You must go to Tile Caching > Tile Layers > Add a new cached layer to add your layer in GWC. Then press seed/truncate and you'll see a dialog where you can choose the zoom levels and the tile format (jpg/png). Don't forget to enable the Disk Quota, if you want to see the current disk space used by the cached layer tiles.
[ "stackoverflow", "0003023503.txt" ]
Q: How can I check if an object is an iterator in Python? I can check for a next() method, but is that enough? Is there an ideomatic way? A: In Python 2.6 or better, the designed-in idiom for such behavioral checks is a "membership check" with the abstract base class in the collections module of the standard library: >>> import collections >>> isinstance('ciao', collections.Iterable) True >>> isinstance(23, collections.Iterable) False >>> isinstance(xrange(23), collections.Iterable) True Indeed, this kind of checks is the prime design reason for the new abstract base classes (a second important one is to provide "mixin functionality" in some cases, which is why they're ABCs rather than just interfaces -- but that doesn't apply to collections.Iterable, it exists strictly to allow such checks with isinstance or issubclass). ABCs allow classes that don't actually inherit from them to be "registered" as subclasses anyway, so that such classes can be "subclasses" of the ABC for such checks; and, they can internally perform all needed checks for special methods (__iter__ in this case), so you don't have to. If you're stuck with older releases of Python, "it's better to ask forgiveness than permission": def isiterable(x): try: iter(x) except TypeError: return False else: return True but that's not as fast and concise as the new approach. Note that for this special case you'll often want to special-case strings (which are iterable but most application contexts want to treat as "scalars" anyway). Whatever approach you're using to check iterableness, if you need such special casing just prepend a check for isinstance(x, basestring) -- for example: def reallyiterable(x): return not isinstance(x, basestring) and isinstance(x, collections.Iterable) Edit: as pointed out in a comment, the question focuses on whether an object is an iter***ator*** rather than whether it's iter***able*** (all iterators are iterable, but not vice versa -- not all iterables are iterators). isinstance(x, collections.Iterator) is the perfectly analogous way to check for that condition specifically. A: An object is iterable if it implements the iterator protocol. You could check the presence of __iter__() method with: hasattr(object,'__iter__') in Python 2.x this approach misses str objects and other built-in sequence types like unicode, xrange, buffer. It works in Python 3. Another way is to test it with iter method : try: iter(object) except TypeError: #not iterable A: To be an iterator an object must pass three tests: obj has an __iter__ method obj has a next method (or __next__ in Python 3) obj.__iter__() returns obj So, a roll-your-own test would look like: def is_iterator(obj): if ( hasattr(obj, '__iter__') and hasattr(obj, 'next') and # or __next__ in Python 3 callable(obj.__iter__) and obj.__iter__() is obj ): return True else: return False
[ "stackoverflow", "0023134819.txt" ]
Q: Python global/local scope in the interpreter? What sorcery is this Here's my simple script, called aScript.py: a = 0 def load(): global a a = 1 def plot(): print a Then in the python interpreter in do the following 4 commands: >>>from aScript import * >>>print a >>>load() >>>print a Why does it print: 0 0 Instead of (which is what I expected btw): 0 1 I'm using python 2.6. Thanks! ...Why does it print 0 0? A: global variables are only global in their own module, therefore load() only modifies the a variable inside aScript, not the imported a. When you do from aScript import *, python iterates over aScript's public variables and creates a copy of each in the current module, that is, it creates __main__.a equal to aScript.a. Now you call load, which is actually aScript.load which modifies its own a (aScript.a), but since it has no idea about __main__.a, the latter is left intact.
[ "stackoverflow", "0026586003.txt" ]
Q: GetField doesn't work for [Events on a] button control I have the following code that creates a button : Dim B As New Button B.Parent = Me B.Location = New Point(50, 50) AddHandler B.Click, Sub() MsgBox("Hi") End Sub 'I try to get the field info for the click event inorder to get the event handler and remove it Dim FieldInfo As FieldInfo = B.GetType.GetField("Click", BindingFlags.[Static] Or BindingFlags.NonPublic Or BindingFlags.Public) Dim obj As Object = FieldInfo.GetValue(Obj_) Dim EI As EventInfo = Obj_.GetType.GetEvent(EventName) EI.RemoveEventHandler(Obj_, obj) but the FieldInfo is constantly null. I tried with many event names ClickEvent, EventClick... but none of them allowed me to get a result. Does anyone know what is missing to my code please ? Thank you in advance. A: I suggest you to go through this - How to: Hook Up a Delegate Using Reflection Get an EventInfo object representing the event, and use the EventHandlerType property to get the type of delegate used to handle the event. In the following code, an EventInfo for the Click event is obtained. Code snippet: Dim evClick As EventInfo = tExForm.GetEvent("Click") Dim tDelegate As Type = evClick.EventHandlerType You can easily get their list (type.GetEvents()), add another handler (EventInfo.AddEventHandler()) or remove a handler (EventInfo.RemoveEventHandler()). To get a list of attached delegates you have to do something more. References: Removing Event Handlers using Reflection How to get event handlers list using reflection Raise an event via reflection in c# Getting event via reflection
[ "stackoverflow", "0022766895.txt" ]
Q: Spring Data MongoDB Aggregation framework, exception accessing computed value in group I have a collection of trips and every trip has a startDateTime and a completionDateTime property. I'm trying to use the aggregation framework to find the average duration of a users' trips. My aggregation seems simple enough and but it throws an exception. There are 3 steps below, the first just matches the trips to a specific userId. In the second step of the pipeline I project the data I'm interested in along with the newly calculated duration of each trip. I expected the duration from the projection to be available in the group step but I get the IllegalArgumentException below. Duration Is not a property on my Trip class but from the examples I've seen in the docs I don't think it needs to be. Duration is a property on my analytics class. TypedAggregation<Trip> aggregation = newAggregation(Trip.class, match(Criteria.where("userId").is(aUserId)), project("completionDateTime", "startDateTime", "userId") .and("completionDateTime").minus("startDateTime").as("duration"), group("userId").avg("duration").as("averageDuration") ); AggregationResults<Analytics> result = mongoTemplate.aggregate(aggregation, Analytics.class); I believe the duration is getting calculated correctly as if I leave out the group step I get back a collection of documents and they all have the duration set. java.lang.IllegalArgumentException: Invalid reference 'duration'! at org.springframework.data.mongodb.core.aggregation.ExposedFieldsAggregationOperationContext.getReference(ExposedFieldsAggregationOperationContext.java:78) at org.springframework.data.mongodb.core.aggregation.GroupOperation$Operation.getValue(GroupOperation.java:367) at org.springframework.data.mongodb.core.aggregation.GroupOperation$Operation.toDBObject(GroupOperation.java:363) at org.springframework.data.mongodb.core.aggregation.GroupOperation.toDBObject(GroupOperation.java:308) at org.springframework.data.mongodb.core.aggregation.Aggregation.toDbObject(Aggregation.java:247) I'm using 1.3.4.RELEASE Any Suggestions? A: After upgrading to 1.4.1 I was able to get the desired result using: .andExpression("completionDateTime - startDateTime").as("duration")
[ "askubuntu", "0000858893.txt" ]
Q: Bypass the firewall for using the ssh command I'm working from a cafe, and I'm thinking there's a firewall on the router preventing me from using the command ssh 'ip address'. Is there exists a way to bypass the firewall such as I can access the remote machine? P.S. I want to access the remote machine via a local network. A: I understand that you want to access a remote machine on another location through the internet and not through a local connection. If this is the case, you have to access the router's settings and open the port the ssh server is using for incoming connections. There is no other way to bypass a closed port.
[ "stackoverflow", "0039420483.txt" ]
Q: PowerMockito Error Need a quick help. I am trying to write a test class and getting below error "can not resolve the method .thenreturn(org.apache.kafka.clients.producer) @Test public void testPublishData_Success() throws java.lang.Exception { when(GetPropValues.getPropValue(PublisherConstants.ATMID)).thenReturn("ATM"); when(GetPropValues.getPropValue(PublisherConstants.DATA_SOURCE)).thenReturn("PCE"); ReadAndWriteFiles mockFiles = Mockito.mock(ReadAndWriteFiles.class); PowerMockito.whenNew(ReadAndWriteFiles.class).withNoArguments().thenReturn(mockFiles); Mockito.when(mockFiles.getAllFiles()).thenReturn("someValue"); KafkaProducer mockProducer = Mockito.mock(KafkaProducer.class); PowerMockito.whenNew(KafkaProducer.class).withAnyArguments().thenReturn(mockProducer); producer.publishData(null, "Test", "Data1"); } Powermockito is fine in returning ReadAndWriteFiles.class object but it is throwing an error for KafkaProducer.class. on line PowerMockito.whenNew(KafkaProducer.class).withAnyArguments().thenReturn(mockProducer); Is there any other way to for this work around? Any suggestion will be appreciated. Note: KafkaProducer.class is in not a custom class but its inside from apache spark kafka libraries Main code is as per below KafkaProducer<String, String> producer = new KafkaProducer<String, String>(props); InputData inputMessage; try { inputMessage = populateData(timeStamp, dataCategory, data, atmId, topic); ReadAndWriteFiles readerWriter = new ReadAndWriteFiles(); File[] directory = readerWriter.getAllFiles(); if (directory != null && directory.length > 0) { if (connectionSet && !publishingData) { sendDataFromFiles(producer, directory); publishingData = false; } } else { producer.send(keyedMsg, new KafkaResponseHandler(inputMessage)); } } catch (IOException e) { } A: I think the error is KafkaProducer mockProducer = Mockito.mock(KafkaProducer.class); PowerMockito.whenNew(ReadAndWriteFiles.class).withAnyArguments().thenReturn(mockProducer) I think the returned value should be a mock for ReadAndWriteFiles class not a KafkaProducer ReadAndWriteFiles readMock = Mockito.mock(ReadAndWriteFiles.class) PowerMockito.whenNew(ReadAndWriteFiles.class).withAnyArguments().thenReturn(readMock) Mockito.when(readMock.getAllFiles()).thenReturn(anArrayOfFiles); The signature of the thenReturn method is as follow OngoingStubbing<T> [More ...] thenReturn(T value); So you are using to return a ReadAndWriteFiles you shouls return an object of the same class
[ "math.stackexchange", "0000295916.txt" ]
Q: Solving for the closed form of a recurrence relation Can someone concisely explain how we can find the closed form of a recurrence relation? I know the iterative process is generally the preferred method, but I'm having trouble deriving the steps and coming to a final solution. Here are two questions I've obtained from an old textbook. If possible, I'd greatly appreciate if the "where n is a power of 2" and "where e,f,g are positive integers and n is a multiple of f" effect the decisions we make whilst trying to conclude with a closed form. $T(n) = T(\frac{n}{2}) + \log_2{n}, T(1) = 1$ and n is a power of 2 $T(n) = eT(n-f)+g$ and e,f,g > 0 and n is a multiple of f Thank you! A: For the first $T(n)$ is not defined unless $n$ is a power of $2.$ We are given $T(1)$ and can use the recurrence to find $T(2),$ but there is no way to find $T(3)$ unless we view the division as integer division and say $3/2=1.$ For recurrences like this, we usually care about asymptotic behavior, so we can just think about powers of $2.$ Similarly in the second, having $n$ a multiple of $f$ means the recurrence will bottom out at $0.$ Having $e,f,g \gt 0$ makes sure $T(n)$ doesn't go negative. The text is being careful to give well-stated problems. Added: for the first, define $n=2^k$, so $k=\log_2 n$ and define $S(k)=T(2^k)=T(n)$. $S(k)$ is defined for all $k$. The recurrence becomes $S(k)=S(k-1)+k, S(0)=1$ By inspection we can see that $S(k)=1+\sum_{i=1}^k i=1+\frac 12 k(k+1)$ so $T(n)=1+\frac 12 \log_2 n (\log_2 n +1)$ For the second, let $m=\frac nf$ and define $P(m)=T(fm)=T(n)$. You didn't give a base case, so I will assume $T(0)=P(0)=0$. The recurrence becomes $P(m)=eP(m-1)+g$. If we just write out $P(3)=eP(2)+g=e(P(1)+g)+g=e(e(P(0)+g)+g)+g=e^2g+eg+g$ we can see that $P(m)=g\frac {e^m-1}{e-1}$ by summing the geometric series. You can make it more formal, but that is the answer. Now you would need to translate that back to the original $T(n)$
[ "stackoverflow", "0058112649.txt" ]
Q: How can I calculate arcore image score in Android I am setting up a android app by Kotlin, and I want to get image score for arcore. On this page they say: Run arcoreimg eval-img to get a quality score between 0 and 100 for each image. And I just found a program for Linux, macOS, Windows to unzip the arcore-android-sdk-1.11.0. I want to calculate arcore image score via my Android app. How can I calculate the image score if the arcore team doesn't support it? I found some posts that run the Windows program on Android, but It is 'How To Run Windows App(EXE) on Android Mobile' by use emulator. However, I want to write code that the app can calculate on its own. A: One possible solution could be to host arcoreimg tool in a docker and query this service instead. I know it is not ideal, but might be an option
[ "stackoverflow", "0050780643.txt" ]
Q: Count number of values in a cell unless blank I have a cell that uses a drop-down list that allows for multiple selections. How do I count the number of selections? I used this: =LEN(A2)-LEN(SUBSTITUTE(A2,",",""))+1 But this doesn't account for blank or no selection. How can I display 0 as well if there is no selection? A: If you want your formula to ignore consecutive comma's: =LEN(A2)-LEN(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A2,",,",","),",,",","),",",""))+1 It's doubled-up to account for odd numbers of sets of commas. or to totally jack-all @Jeeped's suggestions, if the values in your drop down do not have spaces, a better way might be: =LEN(A2)-LEN(TRIM(SUBSTITUTE(SUBSTITUTE(A2,","," ")," ","")))+1 A: If your selections do not have spaces then substitute commas for spaces, trim the result then count for spaces as above with commas. =LEN(trim(SUBSTITUTE(A2,","," ")))-LEN(SUBSTITUTE(trim(SUBSTITUTE(A2,","," "))," ",""))+sign(len(a2))
[ "stackoverflow", "0040050881.txt" ]
Q: TFS 2010 to TFS 2015 Migration and SharePoint Content database What is the proper procedure for dealing with the SharePoint TFS content database? We have migrated our TFS installation from TFS2010 to TFS2015 and are really unsure how to properly handle SharePoint. Under TFS2010, we had our SharePoint content databases hosted in SharePoint Foundation 2010. As part of the TFS2015 migration we installed SharePoint Foundation 2013 and re-attached the 2010 content database, but did not update the look and feel to SharePoint 2013. Everything seems work under the old look and feel, however if we do upgrade the look and feel to SharePoint 2013, some of the buttons on the widgets stop working. For example: clicking the New Work Item and the selected any type of work item does not do anything. Are we supposed to leave the look and feel alone, and in the old Sharepoint 2010 format , or are we missing a step? Online documentation seems to be sparse on the topic. A: You can either to use the same SharePoint site for TFS that you have right now or you'll need to upgrade your SharePoint instance first. TFS 2010 supported Office SharePoint Server 2007 (Standard, Enterprise) and Windows SharePoint Services 3.0. TFS 2015 supports SharePoint 2010 and 2013 (Foundation, Standard, Enterprise). After upgrading your SharePoint instance, you'll need to install TFS 2015 on it and then configure SharePoint Extensions. Here's a guide on how to migrate TFS databases including SharePoint databases in detailed steps: Migrating Team Foundation Server Databases This is also a related situation for your reference: Migration Update from Team Foundation Server (TFS) 2013 to TFS 2015 (With Reporting and SharePoint) Update Things That Don't Work Anymore After I Migrated to SharePoint 2013 The change from SharePoint 2010 to SharePoint 2013 is even more radical then it was from SharePoint 2007 to SharePoint 2010. This time we’re switching to HTML5 - which was built to work easily on all browsers and even other devices. In today's world, it was inevitable. There is also a big change in the way SharePoint shows us its content; Web Parts no longer use tables, for the most part, and the use of XSLT has been replaced by Display Templates. This means almost all your branded Web Parts and Content Query styles will no longer work. .... Source Link: What might not work so well anymore after the migration And according to TFS 2013 Upgrade - SharePoint 2010 to SharePoint 2013 Failure. SharePoint 2013 has two modes (hives), 2010 (v14) and 2013 (v15). Apparently,a new 2013 installation mostly only installs v15 features. You can also give a try with this. I don’t think all your old look and feel will be functional in 2013, given the huge changes in the UI. But since that site’s content and TFS function is fully browsable and usable as it is now with old look, at least you can still remain in 2010 mode.
[ "stackoverflow", "0033088051.txt" ]
Q: Mainting a common library among hundreds of small applications I have a question about creating a common library for a very large number of small applications. I joined a development team of 2 recently. We are about to expand to 3. We have over 200 applications that we maintain. All applications support our operations and all are in house development projects. All of these applications reference a lot of third party dependencies such as dapper, nlog, etc... But none reference a common in house library. I thought it would be best to wrap these third parties in a façade to allow interchangability and in addition provide common functionality that these applications use such as sending emails, instantiating database connections, etc. All applications would be modified to reference this library. I think it helps to add consistency to things like email and logging, however, I don't know how to manage 200 applications referencing a single version of a library. My original thought was to have all 200 apps reference the same version of the libraries, which would be rebuilt automagically by a CI build when it new one of it's dependencies (libraries) were changed, but from what I'm told this is too risky and not supported by TFS. Should I allow these 200 applications to all reference various versions of a common library I create, or is it really not worth the trouble and let all applications spin up their own logging, email sending, and audit logic? If the common library is the best practice for this, how do you keep track of the which application uses which version of the library when bugs are discovered, etc. Edit to clarify from potential duplicate question The potential duplicate question was in regards on how to create a build script that would automatically build projects based on their dependencies being changed. This question is asking if a common library that would need that sort of building mechanism is appropriate in the first place. A: You presumably keep third-party dependencies like NLog up-to-date using NuGet. Why not use NuGet for your in-house library as well? You can setup a private NuGet feed with reasonable effort. Some companies restrict which third-party libraries their developers may use. Therefore, they might not want developers to have access to everything in the official NuGet feed, or they might have a set of proprietary libraries they want to make available in addition to the official feed. In these scenarios, you can set up a custom NuGet feed, and you can configure Visual Studio to offer that feed instead of or in addition to the official feed. A feed can be local (a folder on the local machine or a network folder), or remote (an intranet or internet URL). Source: docs.nuget.org Depending on your comfort level placing your code compiled in an external data center, there are also a number of NuGet service providers listed at the same link.
[ "drupal.stackexchange", "0000218321.txt" ]
Q: Provide Menu in Module I am looking for a way to provide a whole menu (no menu items) within a module. I could find many ways how to do that in D7, but I really would like to da that in D8. A: You put the menu in the folder config/install of the module. An example from the devel module: /config/install/system.menu.devel.yml id: devel label: 'Development' description: 'Links related to Devel module.' langcode: en locked: true Then you can place the menu link items for this menu in *.links.menu.yml in the root directory of the module. Edit: As mentioned in the comment from @mradcliffe, some background info might be helpful. Menus are configuration entities. The storage of the configuration is for performance reasons in the database, but they were at the beginning of D8 in yaml files. If you sync the configuration to the harddisk you will find the configuration in a set of yaml files. You can put any of these yaml files in the config/install folder of your module. But you have to remove the uuid line, because the uuid is only valid for the installation you have exported the yaml file from. The menus are in system.menu.*.yml.
[ "math.stackexchange", "0000622974.txt" ]
Q: Asymptotics of two expressions involving logarithms (As I am new to algorithmic complexity so), EDIT: please give solutions for large x (means as x->infinity) ! A: You can subtitute $y=\ln x$ and apply logarithm laws, $$\ln\left(\frac{y+1}{y^3}\right)=\ln\left(1+\tfrac1y\right)-2\ln(y)=O(1/y)+O(\ln(y)),$$ which is both smaller or contained in $O(y^{\frac12})$ After the Edit: first simplify your expression. Then it reads as $$x\cdot\frac{0.2}{y}\cdot\frac{y+1}{y^3}$$ which is $O(x\ln(x)^{-3})$ which is contained in $o(x)$. A: Use backslash for special functions like $\ln$. You didn't specify whether $x \to 0$ or $x \to \infty$ or something else, so your question is not precise enough. But either way, the technique is always to look for the most significant term and "pull it out" in some way to get to some form with an asymptotic expansion. For example: $\ln(x+1) - \ln(x-1) \\ = \ln(x(1+\frac{1}{x})) - \ln(x(1-\frac{1}{x})) \\ = ( \ln(x) + \ln(1+\frac{1}{x}) ) - ( \ln(x) + \ln(1-\frac{1}{x}) ) \\ \approx ( \frac{1}{x} ) - ( - \frac{1}{x} ) \text{ as } x \to \infty \\ = \frac{2}{x}$ The asymptotic expansion used here is the Taylor series. [Edit: Now that the question has been clarified..] Use the same technique, since the outer function is increasing, we need to identify the asymptotically greatest term inside and factor it out: $\ln(\frac{\ln(x)+1}{\ln(x)^3}) \\ = \ln(\frac{1}{\ln(x)^2}(...)) \\ = -\ln(\ln(x)^2) + \ln(...) \\ \approx -\ln(\ln(x)^2) + ... \text{ as } x \to \infty$ again using the Taylor series.
[ "stackoverflow", "0037548349.txt" ]
Q: custom ArrayAdapter for listView with images out of memory I'm trying to show data from an xml file , I maid a class that parses the information into a list and I need to show the pictures and the tostring of each item therefor I created a custom ArrayAdapter. for some reason this error keeps popping up when I use the activity 05-31 17:14:13.338 24755-24755/com.yuvaleliav1gmail.foodchain E/AndroidRuntime: FATAL EXCEPTION: main Process: com.yuvaleliav1gmail.foodchain, PID: 24755 java.lang.OutOfMemoryError: Failed to allocate a 63489036 byte allocation with 16777216 free bytes and 20MB until OOM at dalvik.system.VMRuntime.newNonMovableArray(Native Method) at android.graphics.BitmapFactory.nativeDecodeStream(Native Method) at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:882) at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:858) at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:478) at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:516) at android.graphics.drawable.Drawable.createFromPath(Drawable.java:2577) at com.yuvaleliav1gmail.foodchain.CustomListViewAdapter.getView(CustomListViewAdapter.java:52) at android.widget.AbsListView.obtainView(AbsListView.java:2929) at android.widget.ListView.makeAndAddView(ListView.java:1945) at android.widget.ListView.fillUp(ListView.java:755) at android.widget.ListView.correctTooHigh(ListView.java:1456) at android.widget.ListView.fillGap(ListView.java:684) at android.widget.AbsListView.trackMotionScroll(AbsListView.java:7293) at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:4391) at android.widget.AbsListView.onTouchMove(AbsListView.java:5782) at android.widget.AbsListView.onTouchEvent(AbsListView.java:5610) at android.view.View.dispatchTouchEvent(View.java:9993) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2828) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2499) at android.widget.AbsListView.dispatchTouchEvent(AbsListView.java:5547) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2839) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2514) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2839) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2514) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2839) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2514) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2839) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2514) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2839) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2514) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2839) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2514) at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2831) at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1863) at android.app.Activity.dispatchTouchEvent(Activity.java:3046) at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:60) at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2792) at android.view.View.dispatchPointerEvent(View.java:10228) at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5344) at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5180) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4620) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4673) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4639) at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4781) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4647) at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4838) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4620) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4673) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4639) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4647) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4620) at android.view.ViewRootImpl.deliverI this is the code: import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.List; /** * Created by rippe on 5/31/2016. */ public class CustomListViewAdapter extends ArrayAdapter<Meal> { Context context; public CustomListViewAdapter(Context context, int resourceId, //resourceId=your layout List<Meal> items) { super(context, resourceId, items); this.context = context; } /*private view holder class*/ private class ViewHolder { ImageView imageView; TextView txtTitle; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; Meal rowItem = getItem(position); LayoutInflater mInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); if (convertView == null) { convertView = mInflater.inflate(R.layout.list_item, null); holder = new ViewHolder(); holder.txtTitle = (TextView) convertView.findViewById(R.id.title555); holder.imageView = (ImageView) convertView.findViewById(R.id.icon555); convertView.setTag(holder); } else holder = (ViewHolder) convertView.getTag(); holder.txtTitle.setText(rowItem.toString()); if(rowItem.getPicPath().compareTo("") != 0) holder.imageView.setImageDrawable(Drawable.createFromPath(rowItem.getPicPath())); return convertView; } } this is the activity: import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.widget.ArrayAdapter; import android.widget.ListView; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.List; public class XmlPullParser extends AppCompatActivity { ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_xml_pull_parser); listView = (ListView) findViewById(R.id.list); List<Meal> meals = null; try { XMLPullParserHandler parser = new XMLPullParserHandler(); meals = parser.parse(getStringFromFile(Globals.xmlFilePath)); CustomListViewAdapter adapter = new CustomListViewAdapter(this,R.layout.list_item, meals); listView.setAdapter(adapter); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public static FileInputStream getStringFromFile (String filePath) throws Exception { File fl = new File(filePath); FileInputStream fin = new FileInputStream(fl); return fin; } } this is the parser: although i don't thin the problem is in the parser but in the custom ArrayAdapter... import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; class XMLPullParserHandler { List<Meal> meals; private Meal meal; private String text; public XMLPullParserHandler() { meals = new ArrayList<Meal>(); } public List<Meal> getMeals() { return meals; } public List<Meal> parse(InputStream is) { XmlPullParserFactory factory = null; XmlPullParser parser = null; try { factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); parser = factory.newPullParser(); parser.setInput(is, null); int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { String tagname = parser.getName(); switch (eventType) { case XmlPullParser.START_TAG: if (tagname.equalsIgnoreCase("Meal") || tagname.equalsIgnoreCase("Comment") || tagname.equalsIgnoreCase("Weight")) { meal = new Meal(); meal.setTimestamp(parser.getAttributeValue(0)); } break; case XmlPullParser.TEXT: text = parser.getText(); break; case XmlPullParser.END_TAG: if (tagname.equalsIgnoreCase("Meal") || tagname.equalsIgnoreCase("Comment") || tagname.equalsIgnoreCase("Weight")) { // add employee object to list meals.add(meal); } else if (tagname.equalsIgnoreCase("Score")) { meal.setScore(text); } else if (tagname.equalsIgnoreCase("Description")) { meal.setDescription(text); } else if (tagname.equalsIgnoreCase("Note")) { meal.setNotes(text); } else if (tagname.equalsIgnoreCase("Picture")) { meal.setPicPath(text); } else if (tagname.equalsIgnoreCase("WeightNumber")) { meal.setWeightNumber(text); } else if (tagname.equalsIgnoreCase("CommentType")) { meal.setCommentType(text); } break; default: break; } eventType = parser.next(); } } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return meals; } } A: Turns out images that you load are big enough to cause OutOfMemoryError, learn about Loading Large Bitmaps Efficiently, or switch to using an image loading framework, such as Picasso or Glide.
[ "stackoverflow", "0056247969.txt" ]
Q: When copyting to clipboard, it prompt "drag-mouse-1 is undefined" I want to view and copy all the binding after M-g to the clipboard, so, strike M-g, it then prompt When copying the clipboard, it failed and prompt: M-g <drag-mouse-1> is undefind How could solve the problem? Additional notes: no menus if emacs -Q , I git emacs.d from purcell/emacs.d: An Emacs configuration bundle with batteries included A: I believe I have deciphered this question. I suspect you have the which-key library enabled (or something very similar). That is then displaying all the keys under the prefix binding M-g, after you have typed that key, while waiting for you to type the next key in the sequence. You are then attempting to use the mouse to select the text of the displayed bindings in the which-key buffer; however Emacs is still waiting for you to finish the key sequence, so when you click the mouse button it tells you about the sequence M-g <drag-mouse-1> You can't do what you're trying to do, because the which-key buffer does not persist after the key sequence has been completed. What you should do is use the standard method of obtaining the same information, which is to type C-h after the prefix. i.e. M-g C-h That will then show you a *Help* buffer with all the bindings under that prefix, and you will be able to copy the text from that buffer.
[ "stackoverflow", "0012876261.txt" ]
Q: Rails double encoding my json So I am trying to return an object which contains an array of other objects and i am getting back the objects all escaped eg(\"name\":\"My Name\"). I'm sure the problem is i am double encoding but I'm a ruby n00b so I am not sure how to do this properly @Results = Marker.where("ID = '#{params[:id]}' and Stop_Id IS null").all format.all { render json: { :Results => @Results.to_json(:include => :stops) } } Thanks in advance! A: You should override the as_json method in your model. See here for advice.
[ "stackoverflow", "0058236526.txt" ]
Q: Mat-checkbox checked property determined by modal response I have an array of users and in HTML I used *ngFor to generate a checkbox for each element. I also have an @Input assignedAccountIds[] which represents the default selected users. The checkbox element is the following one: <mat-checkbox color="primary" [disabled]="disableCurrentAccountCheckbox && account.id === currentAccountId" [checked]="isAccountSelected(account)" (change)="onSelectAccount($event, account)" > isAccountSelected method verify if a user exists in the selected items array to know if I need to check it or not, and here is the implementation: isAccountSelected(account: ClientAccount): boolean { return (this.assignedAccountIds || []).includes(account.id); } On the change output, the method implementation is the following one: onSelectAccount(event: MatCheckboxChange, account: ClientAccount): void { if ( !event.checked && this.currentAccountId && account.id === this.currentAccountId ) { const dialogRef = this.dialog.open(ConfirmationDialogComponent, { data: { message: `You will not be able to see this inspection if you unassign yourself!`, buttonColor: 'primary', buttonLabel: 'Unassign', }, position: { right: '10px', bottom: '10px', }, maxWidth: '580px', }); dialogRef .afterClosed() .pipe(untilDestroyed(this)) .subscribe(result => console.log(result)); } else { this.selectionChange.emit({ id: account.id, checked: event.checked }); } } So, what I'm actually trying to do is to display a confirmation modal when you want to unselect yourself from the list. And only after you select Yes or No from the modal, the checkbox will remain checked or will be unchecked. A: MatCheckbox does not provide a built-in way to "intercept" a check/uncheck action. You can only listen to the change event after it happens. However, you can use an ordinary click event to do the intercepting: Checkbox <mat-checkbox #cb (click)="confirmAssign($event)">Assigned</mat-checkbox> Dialog actions <mat-dialog-actions> <button mat-button [mat-dialog-close]="false">Cancel</button> <button mat-button [mat-dialog-close]="true">Unassign</button> </mat-dialog-actions> TS @ViewChild('cb', {static: true}) cb: MatCheckbox; constructor(public dialog: MatDialog) {} confirmAssign(event) { // only intercept if currently checked if (this.cb.checked) { // stop the click from unchecking the checkbox event.preventDefault(); // ask for confirmation this.dialog.open(ConfirmationDialogComponent).afterClosed().subscribe(confirmed => { if (confirmed) { // uncheck the checkbox setTimeout(() => this.cb.checked = false); } }); } }
[ "stackoverflow", "0054244630.txt" ]
Q: In Keras, on which weight is the dropout applied? I am currently trying to find a way to retrieve which weights are "ignored" for a given layer (especially when I use the "training" flag to use dropout during the test phase). Is there an easy way to find it or am I obligated to create a custom dropout layer ? A: There is no easy way. Keras' tensorflow backend simply calls tf.nn.dropout which works by generating a random matrix of the size of its input and sets values in the input to zero if the corresponding value in the random matrix is less than the threshold. Here is the key step, located in https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/nn_ops.py: # Sample a uniform distribution on [0.0, 1.0) and select values larger than # rate. random_tensor = random_ops.random_uniform( noise_shape, seed=seed, dtype=x.dtype) keep_prob = 1 - rate ret = (1 / keep_prob) * math_ops.cast(keep_prob >= random_tensor, x.dtype) * x You can't retrieve these results directly through keras since the random multiplication is applied immediately and not saved. However you can try to modify the source code to print or save the result of math_ops.cast(keep_prob >= random_tensor,x.dtype) which contains which weights were used in that use of dropout.
[ "scifi.stackexchange", "0000198031.txt" ]
Q: Has a human ever mastered the mind meld? In any canon series of Star Trek has a human been able to master the mind meld? A: Miranda Jones joins minds with Ambassador Kollos in TOS: Is There in Truth no Beauty? MIRANDA: Thank you, but the assignment's not yet definite. It will depend upon my ability to achieve a true mind-link with the Ambassador. SPOCK: I'm sure you will find it a fascinating experience. ... [later] MIRANDA: I am one with Kollos. Episode transcript She is an unusual human as she was born a telepath. A: According to the novelization of Star Trek III: The Search for Spock, authored by Vonda N. McIntyre, Spock's mother had mastered the Vulcan mind melding skills. In the book, there are additional scenes on Vulcan, with Amanda Grayson as the viewpoint character. The scenes provide some additional background on Vulcan mysticism for the reader, and as part of the exposition, it is revealed that Amanda has gone through the Vulcan spiritual training and reached the level of competence that is normally required of Vulcans. However, the canonicity of this material might be considered dubious. The books presents a subtly different description of the Vulcan mysticism than appears in the final movie. (These ideas may have originated with McIntyre, or they may have been from an earlier version of the film's treatment/script.) The character played by Judith Anderson is credited in the film as the "Vulcan High Priestess." However, in the book, her position does not seem to have any religious overtones, and by virtue of being the most skilled practitioner of the Vulcan mental arts, she was referred to simply as "the adept." (It is actually mentioned in the book that the current adept had actually recently stopped using that title, since she did not feel that it was right to set herself above all the other skilled Vulcans.) And, of course, there is the idea that a relatively normal human could expect to achieve Vulcan-level skills over the course of just living several decades on Vulcan.
[ "math.stackexchange", "0000772062.txt" ]
Q: Parallelograms formed by parallel lines Given in figure 4, there are 5 parallel lines intersected by 4 other parallel lines. How many unique parallelograms are there in figure 4? Answer: 60. When two pairs of parallel lines intersect, one parallelogram forms -> number of parallelograms are vector(4, 2) * vector(5, 2) = 6 * 10 = 60 I'm confused on how the 6 and 10 appeared. I thought dot notation would dictate that the answer be 24? Unless, I am completely mistaken and the two were not written as vectors. Any help would be greatly appreciated! A: I'm assuming it appeared as $${4\choose2}\cdot{5\choose2}=6\cdot10$$ Those aren't vectors, but rather binomial coefficents, pronounced "($4$ choose $2$) times ($5$ choose $2$)". $${n\choose k}=\frac{n!}{k!(n-k)!}$$
[ "stackoverflow", "0028381490.txt" ]
Q: Auto scroll while clicking UITableView didSelectRowAtIndexPath ios-ObjectiveC How to scroll up the TableView or cell while i am clicking loadmore from option from UITableView didSelectRowAtIndexPath A: NSIndexPath* ip = [NSIndexPath indexPathForRow:[arrData count]-1 inSection:0]; [self.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:NO]; arrData is the Data source you feed to the TableView. By setting IndexPath to [arrData count] you can go to the bottom of the TableView
[ "stackoverflow", "0019683630.txt" ]
Q: How to get AppointmentID on a buttonclick I have created an outlook add-in where i have a ribbon that adds a button to the appointment tab. This button has a callback method that opens IE and goes to a specific page. What i need: When you create an appointmnet and ID is stored somewhere(i assume). I need to get the ID of the appointment that i have opend when i click on my button. Simplify: click on an appointment----->appointmnet has a costom button---->click the button--->open a page with the appointmentID. I need to get the ID and add it to the url paramater when i open the page. I have been reading up on the appointment global ID here: http://msdn.microsoft.com/en-us/library/office/ff863645.aspx And all the links that follow that article but I have not found anything that can help. A: Im glad i have friends who know this better than me... soloution here: Outlook Ribbon Load Inspector.CurrentItem is null
[ "stackoverflow", "0006407808.txt" ]
Q: Check if url matches in template Is it possible to check in template that some url match any pattern from urls? A: You can use the "as" form of the url tag to check if a named URL exists. {% url path.to.view as the_url %} {% if the_url %} <a href="{{ the_url }}">Link to optional stuff</a> {% endif %} When "as" is used it does not raise an exception. A: This is something you'd normally want to do in a views.py file with the reverse() helper for named URLs with known args or resolve() for paths. If you do need this functionality in a template specifically, here is a hacky solution: @register.simple_tag def urlpath_exists(name): """Returns True for successful resolves()'s.""" try: return bool(resolve(path)) except Resolver404: return False Note: this doesn't guarantee that the URL is valid, just that there was a pattern match.
[ "stackoverflow", "0026727082.txt" ]
Q: Getting output of Migrate.exe in Batch file I have a batch file that runs a FluentMigrator migration based on user input. The last step is to run the migrator as below: "%~dp0\FluentMigrator.1.1.2.1\tools\Migrate.exe" /conn "DATA SOURCE=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=%HostName%)(PORT=%ServerPort%))(CONNECT_DATA=(SERVICE_NAME=%ServiceName%)));PASSWORD=%installerUserPW%;PERSIST SECURITY INFO=True;USER ID=%installerUserName%;" /provider oracle /context %installerUserName% /assembly ./bin/Debug/DatabaseMigrations.dll >> install_log.txt ECHO. echo ------------------------------------------------------------------------------->> install_log.txt echo ------------------ Database Setup has executed successfully ------------------ >> install_log.txt echo ------------------------------------------------------------------------------->> install_log.txt TYPE install_log.txt GOTO:EOF This works just as required - The Migrate.exe app prints all the output to the file, then the success message, then the file is written to the console so there is a console and file copy. But if the migration fails, for example if the user does not have write permissions for the database, it does not work as expected. In this case, the end message expects the file to have executed correctly. Is there any way to determine if the migrator has exited with an error? I would like to display: The migration code (If failed) The error message for failure (else) A success message EDIT: I originally asked about how to display both the error and general output - this was achieved by the >> install_log.txt 2>&1 code. Now I just need to figure out how to identify if an error has occurred on migration. A: The solution I found is as follows: "%~dp0\FluentMigrator.1.1.2.1\tools\Migrate.exe" /conn "DATA SOURCE=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=%HostName%)(PORT=%ServerPort%))(CONNECT_DATA=(SERVICE_NAME=%ServiceName%)));PASSWORD=%installerUserPW%;PERSIST SECURITY INFO=True;USER ID=%installerUserName%;" /provider oracle /context %installerUserName% /assembly ./bin/Debug/DatabaseMigrations.dll >> migrate_log.txt 2>> migrateerror_log.txt if exist migrate_log.txt ( if exist migrateerror_log.txt ( TYPE migrateerror_log.txt >> install_log.txt echo ------------------------------------------------------------------------------->> install_log.txt echo -------------------------- Database Setup has failed ------------------------- >> install_log.txt echo ------------------------------------------------------------------------------->> install_log.txt ) else ( echo ------------------------------------------------------------------------------->> install_log.txt echo ----------------- Database Setup has completed successfully ------------------ >> install_log.txt echo ------------------------------------------------------------------------------->> install_log.txt ) ) else ( echo ------------------------------------------------------------------------------->> install_log.txt echo ------------- An unexpected error has occurred in FluentMigrator ------------- >> install_log.txt echo ------------------------------------------------------------------------------->> install_log.txt )
[ "photo.stackexchange", "0000073192.txt" ]
Q: How do I auto-focus an EOS M when stopped down to kill the ambient? I'm trying to do take some portraits with two off-camera strobes. I want a dark background, so I'm using a high f-stop and high ISO to kill the ambient, relying on the strobes to light the model. But in this situation the viewfinder goes dark and the AF stops working and it's too dark to manually focus. Models are my children (who won't sit still:-), so I can't really 'pre-focus'. Gear: EOS-M, 70-300mm 4-5.6, 550EX & YN-560 A: You need to disable exposure simulation. The EOS M doesn't have a menu option for this but it is disabled with an ETTL flash or ETTL trigger in the hotshoe. (actually any Canon "dedicated" flash will also communicate with the camera and disable Exp Sim) You could also install Magic Lantern as it includes a menu option to disable Exp Sim.
[ "stackoverflow", "0055425724.txt" ]
Q: Globaly replace all new operators I'm using an RTOS in an (embedded) C++ application. Since i'm working on an embedded target i try to keep the heap allocations to a minimum. However at some point STL classes like vector come in very handy. Because i'm using a RTOS, i have to make sure that the new/malloc() call is thread safe. Luckyly my RTOS (FreeRTOS) provides it's own (threadsafe) malloc() routines. I only do have to use them. So far i implemented the following new/delete pair and linked it into the binary. void * operator new(size_t n) noexcept(false); void operator delete(void * p) noexcept(true); void operator delete(void * p, size_t n) noexcept(true); However looking at this https://en.cppreference.com/w/cpp/memory/new/operator_new shows me a dozen overloads of new (and as many overloads for delete). Do all new or delete overloads default to my replacement or am i missing an operator overload? A: The default behaviour of the standard library for many of the operator new and operator delete overloads is to forward to the "basic" versions of operator new and operator delete. The "basic" operators are: void* operator new (std::size_t count); void* operator new (std::size_t count, std::align_val_t alignment); // C++17 only void operator delete(void* ptr) noexcept; void operator delete(void* ptr, std::align_val_t alignment) noexcept; // C++17 only Assuming that you have a standard library implementation that implements the default behaviour as defined in the C++ standard¹, the above operators are the only ones that you need to replace. The default behaviour was first defined in the C++11 standard, so your standard library implementation must support this at minimum. [1]: See the section titled "Storage allocation and deallocation [new.delete]" in a C++ standard.
[ "stackoverflow", "0060378314.txt" ]
Q: Pointer to member of device object I know, that I should not dereference pointer to device. But is the following an dereferencation? struct example{ int a; float b; }; void test(){ example* p_e; cudamalloc(&p_e,sizeof(example)); float* db = &p_e->b; // is this line valid? } It works on my computer, but is this valid? edit: With it works, I meant, that it holds in my testrun that: reinterpret_cast<void*>(&p_e->b) == reinterpret_cast<void*>(reinterpret_cast<unsigned char*>(p_e)+sizeof(int)) A: Regarding this: float db = &p_e->b; I can't imagine a situation where the address of an entity in C or C++ is a float value. So from a language perspective, it makes no sense. If we modify that to: float *db = &p_e->b; That is a sensible construct, although whether it is "useful" depends on how you intend to use it. Taking the address of the location p_e->b requires taking the value of the pointer contained in p_e (a location in host memory, so no device dereferencing going on there) and adding to it the offset to the location b within the object. That offset doesn't involve any dereferencing. It can be computed simply by inspection of the class/structure definition. So none of that requires any dereferencing of pointers. The pointer that is produced (db) is now pointing to a location in device memory, so that pointer should only be used (dereferenced) in device code. But you could pass that pointer by value to a CUDA kernel and make "use" of it, sensibly. If you actually intended to populate the value db with the float contents pointed to by the pointer p_e->b, first of all your code does not do that, and second it would not generally be possible in host code to directly retrieve that data from the device, when the underlying base structure pointer (b_e) is allocated using cudaMalloc.
[ "stackoverflow", "0006873516.txt" ]
Q: firefox ignores background-size css Trying to scale an image down using the background-size CSS rule but seems to be ignored with Firefox 3.5 CSS .privatejoker { background: aqua url("../styles/images/home-privatejoker.png") no-repeat 0 0; background-size: 365px 341px; height:341px; margin: 0 auto; display:block; margin-top: -6px; } A: background-size was added to Firefox 3.6, however the -moz vendor prefix was required. Since version 4, it is no longer required. If you want to support Firefox 3.6 too, include the vendor prefix in addition to the normal property. Joseph provides a good link for further reading at MDN.
[ "stackoverflow", "0007876108.txt" ]
Q: How to access this._id in map function in MongoDB MapReduce? I'm doing a MapReduce in Mongo to generate a reverse index of tokens for some documents. I am having trouble accessing document's _id in the map function. Example document: { "_id" : ObjectId("4ea42a2c6fe22bf01f000d2d"), "attributes" : { "name" : "JCDR 50W38C", "upi-tokens" : [ "50w38c", "jcdr" ] }, "sku" : "143669259486830515" } (The field ttributes['upi-tokens'] is a list of text tokens I want to create reverse index for.) Map function (source of the problem): m = function () { this.attributes['upi-tokens'].forEach( function (token) { emit(token, {ids: [ this._id ]} ); } ); } Reduce function: r = function (key, values) { var results = new Array; for (v in values) { results = results.concat(v.ids); } return {ids:results}; } MapReduce call: db.offers.mapReduce(m, r, { out: "outcollection" } ) PROBLEM Resulting collection has null values everywhere where I'd expect an id instead of actual ObjectID strings. Possible reason: I was expecting the following 2 functions to be equivalent, but they aren't. m1 = function (d) { print(d['_id']); } m2 = function () { print(this['_id']); } Now I run: db.offers.find().forEach(m1) db.offers.find().forEach(m2) The difference is that m2 prints undefined for each document while m1 prints the ids as desired. I have no clue why. Questions: How do I get the _id of the current object in the map function for use in MapReduce? this._id or this['_id'] doesn't work. Why exactly aren't m1 and m2 equivalent? A: Got it to work... I made quite simple JS mistakes: inner forEach() in the map function seems to overwrite 'this' object; this is no longer the main document (which has an _id) but the iterated object inside the loop)... ...or it was simply because in JS the for..in loop only returns the keys, not values, i.e. for (v in values) { now requires values[v] to access the actual array value. Duh... The way I circumvented mistake #1 is by using for..in loop instead of ...forEach() loop in the map function: m = function () { for (t in this.attributes['upi-tokens']) { var token = this.attributes['upi-tokens'][t]; emit (token, { ids: [ this._id ] }); } } That way "this" refers to what it needs to. Could also do: that = this; this.attributes['upi-tokens'].forEach( function (d) { ... that._id... ... } probably would work just fine. Hope this helps someone.
[ "stackoverflow", "0049720118.txt" ]
Q: POKERHANDS - How to I delete from list after the use I have that code. And If I enter n argument is 3 it will be 3 hands. but I want to use any card only one time. totally there 52 cards. and each card can be use just one time. How to I delete the cards after the use? by the way, stdio.writeln is like print. same thing. n = int(sys.argv[1]) SUITS = ["Clubs", "Diamonds", "Hearts", "Spades"] RANKS = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"] rank = random.randrange(0, len(RANKS)) suit = random.randrange(0, len(SUITS)) deck = [] for rank in RANKS: for suit in SUITS: card = rank + " of " + suit deck += [card] for i in range(n): a = len (deck) for i in range(a): r = random.randrange(i, a) temp = deck[r] deck[r] = deck[i] deck[i] = temp for i in range(5): stdio.writeln(deck[i] + " ") stdio.writeln() A: Leverage List comprehenshion to compose a full stack of cards, get a copy of mixed card from it using random.sample() and draw cards up by list.pop() which will remove the card automatically. I reduced the RANKS a bit to shorten the print-outs: SUITS = ["Clubs", "Diamonds", "Hearts", "Spades"] RANKS = ["2", "3", "4", "5", "6"] #,'7", "8", "9", "10", "Jack", "Queen", "King", "Ace"] import random # in order StackOfCards = [ f'{r} of {s}' for r in RANKS for s in SUITS] # return random.sample() of full length input == random shuffled all cards mixedDeck = random.sample(StackOfCards, k = len(StackOfCards)) print("Orig:",StackOfCards) print() print("Mixed:",mixedDeck) print() # draw 6 cards into "myHand" removing them from "mixedDeck": myHand = [mixedDeck.pop() for _ in range(6)] print("Hand:",myHand) print() print("Mixed:",mixedDeck) Output: Orig: ['2 of Clubs', '2 of Diamonds', '2 of Hearts', '2 of Spades', '3 of Clubs', '3 of Diamonds', '3 of Hearts', '3 of Spades', '4 of Clubs', '4 of Diamonds', '4 of Hearts', '4 of Spades', '5 of Clubs', '5 of Diamonds', '5 of Hearts', '5 of Spades', '6 of Clubs', '6 of Diamonds', '6 of Hearts', '6 of Spades'] Mixed: ['2 of Clubs', '3 of Diamonds', '6 of Hearts', '4 of Spades', '5 of Clubs', '3 of Hearts', '6 of Spades', '5 of Hearts', '4 of Diamonds', '3 of Spades', '2 of Spades', '6 of Clubs', '4 of Clubs', '5 of Spades', '6 of Diamonds', '2 of Diamonds', '3 of Clubs', '2 of Hearts', '5 of Diamonds', '4 of Hearts'] Hand: ['4 of Hearts', '5 of Diamonds', '2 of Hearts', '3 of Clubs', '2 of Diamonds', '6 of Diamonds'] Mixed: ['2 of Clubs', '3 of Diamonds', '6 of Hearts', '4 of Spades', '5 of Clubs', '3 of Hearts', '6 of Spades', '5 of Hearts', '4 of Diamonds', '3 of Spades', '2 of Spades', '6 of Clubs', '4 of Clubs', '5 of Spades'] Using .pop() alleviated the need of removing something, if you really dislike it (why would you?) you can recreate a list without elements of another list by: l = [1,2,3,4,5,6] p = [2,6] l[:] = [ x for x in l if x not in p] # inplace modifies l to [1,3,4,5]
[ "stackoverflow", "0008773623.txt" ]
Q: Chrome mysteriously adds 3px to footer width The footer at my site Atlantic Sentinel has a width specified at 960px and a max-width also at 960px. It looks fine in IE but Chrome adds 3px to the width. Why, I can't figure it out. Here's the relevant CSS: #colophon { clear: both; display: table; width: 960px; max-width: 960px; background: #131313; overflow: hidden; border-top: 3px solid #0099cc;} #colophon .widget { display: table-cell; float: left; width: 22%; margin: 2em 0 2em 2em; background: #000; color: #ccc; text-align: justify;} It's not the margins on the widgets. I've tried removing one, so there's only three widgets, 22% wide, and the extra 3px is still there in Chrome. What am I missing? A: This seems to be a bug in webkit, to fix it just set your footer to explicitly collapse the borders you added to the top of your footer like so: #colophon { border-collapse: collapse; } Make sure to remove the overflow:hidden declaration as it is not needed anymore. EDIT. Yup, a bug. Managed to recreate it here, http://jsfiddle.net/PnYPr/ . Same problem as OP's in webkit. Will submit a bug report. EDIT 2. Bug reported.
[ "bitcoin.stackexchange", "0000096299.txt" ]
Q: Can a Ledger Nano X hold multiple BitCoin Wallets? From my reading of Ledger Nano X, it can hold multiple types of currency, for instance, BitCoin and Ethereum. Can it hold two or more separate BitCoin wallets with different balances? Frank A: Yes, you can have multiple bitcoin wallets in ledger nano x by adding a new account All these accounts share the same seed, but have different derivation path
[ "stackoverflow", "0030856501.txt" ]
Q: Resuming Activities in Android Studio I have an Android app that basically has 3 activities: game menu, showcase of data, and the game itself. When you complete the game the app is supposed to send you to the game menu. From what I understand this Activity is already running in the background, in order to go back I use: private Runnable aDesbloqueo = new Runnable() { @Override public void run() { startActivity(new Intent(moduloCuerpoGame.this, GameMenu.class)); } }; Now this creates a new "menu" activity, so when I press the back button it goes back to my "last" activity, then to the middle one, and then to the menu. The question is, what is the best way to go back to the menu from the last Activity without creating any new ones? A: Have you tried adding android:launchMode=“singleInstance” to that Activity in your manifest? Single instance means that Android won't create a new instance of your Activity every time you create a new Intent. Rather, it destroys the previous instance of that Activity in your "Activity stack." Try checking out the Activity instance documentation for a more detailed explaination.
[ "stackoverflow", "0056115959.txt" ]
Q: How to make Prometheus send Alerts to two different Alertmanagers based on Alert labels? I have the following two alerts: alert: InstanceDown expr: (up == 0) and (team == "foo") for: 5m labels: severity: page team: foo annotations: summary: "Instance {{$labels.instance}} down" alert: InstanceDown expr: (up == 0) and (team == "bar") for: 5m labels: severity: page team: bar annotations: summary: "Instance {{$labels.instance}} down" How can I make Prometheus to send the first alert into one alertmanager exposed at alertmanager.example.com/team-foo and second into another alertmanager exposed at alertmanager.example.com/team-bar? I figured I'll need to use service discovery and relabeling but couldn't get much further yet. I'm using prometheus-operator if it matters. A: I don't think you can filter which alerts go to which Alertmanager. You can however send all alerts to 2 (or N) Alertmanager instances and have each Alertmanager configured to route some alerts and ignore all others (i.e. route them to a named receiver with no email, no Slack, no nothing).
[ "judaism.stackexchange", "0000065613.txt" ]
Q: Anywhere in Torah speak about specific professions being praiseworthy and why? Are there any professions the Torah considers praiseworthy and why? A: As noted by Danny Schoemann in a comment, Kiddushin 82a - 82b lists some professions that are seen as praiseworthy (along with others that are not): Camel drivers (according to R. Yehudah) - because they work in the dangerous desert where they fear for their lives, and therefore their 'hearts are broken towards G-d'. (Rashi) Sailors - because they work in an even more fear-inducing environment than camel drivers. (Rashi) Embroiderers - because it is a clean and easy trade. Perfumers - as one is dealing with pleasant-smelling materials.
[ "stackoverflow", "0001968118.txt" ]
Q: How do I change the UITextField so it looks like the Search Text Field? I would like to change the standard iPhone UITextField so that it looks exactly like the search text field within the UISearchBar. You can see an example of this for the SMS text entry field within the iPhone Messages application. I do not believe that the UITextField has a style property that will meet this requirement. Any ideas? A: If you want, you can actually extract the background image from a uisearch bar and make it a stretchable image to use as the background of a UITextField. I did the same thing and it works like a charm for me. Here's the code i used to extract it: UIImage *img = [[[self.searchBar subviews] objectAtIndex:1] background]; NSData *imgdata = UIImagePNGRepresentation(img); NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [searchPaths objectAtIndex: 0]; [imgdata writeToFile:[documentsDirectoryPath stringByAppendingPathComponent:@"searchbarbg.png"] atomically:YES]; the second subview of the uisearchbar is the actual text field; this is subject to change in any future os releases though. this will save the PNG to the app's documents directory, where you can grab it and drop it into your project and use it as the text field's background. the left and top cap widths for the stretchable image are 15 pixels. A: It seems that this is not supported within iPhone OS 3.0. I just used a transparent UITextField with UIImageView as the background. I believe this is how the official iPhone SMS text entry works.
[ "softwareengineering.stackexchange", "0000126432.txt" ]
Q: What is OpenCL? I've been looking around, but I'm still not sure on the what OpenCL is. Other than multi processor stuff... Is it another graphics API like OpenGL and DirectX? Or something that works alongside OpenGL? I'm planning on learning OpenGL soon (with java if it makes a difference) so I want to know how/which direction to learn it with. Also, I hear things about CUDA which confuses me further. Just looking for some simple clarifying statements. Thanks. A: OpenCL is a language/API for doing general purpose highly parallel calculations on a graphics card, but can also be used to generate computed images which are displayed by openGL or directX It's an open standard (like openGL), CUDA is the NVIDIA only competitor. Why? Because your $100 graphics card can do 1000s of tasks in parallel - turning it in a mini-supercomputer!
[ "sharepoint.stackexchange", "0000007448.txt" ]
Q: How to enable search for Custom Site Collection Help? I've enabled the Custom Site Collection Help feature in my Sharepoint 2010 install, and verified that it works by creating a Help Collection folder and uploading some html files as Help Topics. The problem is that the search box at the top of the help windows doesn't work - it just gives me a message of "Search Service Not Found.". It looks like this only occurs when I have the custom site collection selected in the search scopes drop-down, as when I select one of the default Sharepoint search collections, such as "Sharepoint Server 2010", I can search and find results. I've reset the search index, done a full crawl and can search for and find help content from the main site search page (using the All Content scope), but still get the "Search Service not found" result. Has anybody else come across this problem and found a way resolve it? Is there another service hidden away somewhere that I have to enable? A: Actually, I received an answer on stackoverflow that solved this problem. After enabling the "Sharepoint Foundation Search" another step was necessary to associate the content databases covering the help content with the help service. The answer and a better explanation are here.
[ "gaming.stackexchange", "0000012917.txt" ]
Q: Preemptive zombie massacre, good idea? We know that above a certain total amount of zombies the only places where zombies spawn is in tiles with neighboring zombies. Would it be a good idea to start killing zombies strategically from the start, to try to keep some parts of the map zombie-free? Has anybody tried something like that before? It should also reduce the number of tiles with many zombies on them, reducing the chance of people getting stuck outside. I'm mainly wondering if it is even possible with the mostly crappy weapons you have in the beginning, and if the efforts would pay off. If I want to try it I'll have to convince my next town that it is a good idea. A: I don't think it is possible or feasible to do so from the beginning, or at all until you get plumbing up. You need to find the weapons in the first place! Punching zombies costs AP and only has a slim chance of success. Without a watch tower you have no other way of finding out about zombies other than bumping into them, AFAIK. Non-water-based weapons break easily and are expensive to repair; water weapons are just too costly before plumbing, not to forget water balloons are strictly throwaway!
[ "stackoverflow", "0003871621.txt" ]
Q: ASP.NET query substring I've got this field in my database year_start_1 and it is an integer field and an example of an ouput is 20100827 I'm trying to create a substring to create year, week, day and change the format to be 27/08/2010 Here's what i'm trying Dim query as String = "Select * from openquery (devbook, 'SELECT cast(year_start_1 as varchar(8)) as year_start_1, DATENAME(DAY, substring(CAST(year_start_1 AS VARCHAR(8)),6,2) + DATENAME(MONTH, substring(CAST(year_start_1 AS VARCHAR(8)),4,2) + DATENAME(YEAR, substring(CAST(year_start_1 AS VARCHAR(8)),1,4))) FROM web_statements')" It's just throwing up an error and I not sure why: Server was unable to process request I have tried using convert but it doesn't work. Any ideas? UPDATE with Chris's suggestion Dim query as String = "Select * from openquery (devbook, 'SELECT year_start_1, cast(year_start_1 as varchar(8)) as year_start_1, substring(CAST(year_start_1 AS VARCHAR(8)),7,2)+''/''+substring(CAST(year_start_1 AS VARCHAR(8)),5,2)+''/''+substring(CAST(year_start_1 AS VARCHAR(8)),1,4) FROM web_statements')" Still getting the error Thanks UPDATE Couldn't seem to get it to work within the query so had to do a work around in the ASP.Net code 'POINTS END DATE YEAR Dim strPointsDateEndYear = Mid(drv.Row("year_end_1"), 3, 2) Dim strPointsDateEndMonth = Mid(drv.Row("year_end_1"), 5,2) Dim strPointsDateEndDay = Right(drv.Row("year_end_1"), 2) Dim strPointsDateEnd As String = strPointsDateEndDay + "/" + strPointsDateEndMonth + "/" + strPointsDateEndYear Thanks for the help though A: Your first DATENAME doesn't seem to close all its brackets before the next DATENAME starts: DATENAME(DAY, substring(CAST(year_start_1 AS VARCHAR(8)),6,2) + DATENAME[...] Should I assume be: DATENAME(DAY, substring(CAST(year_start_1 AS VARCHAR(8)),6,2)) + DATENAME[...] Edit: Though having fixed that minor error (and converted it to debug) I'm getting errors about casting strings to dates. I'm not sure what the datename stuff is meant to do but how about this: DECLARE @year_start_1 int SET @year_start_1 = 20100827 SELECT cast(@year_start_1 as varchar(8)) as year_start_1, substring(CAST(@year_start_1 AS VARCHAR(8)),7,2)+'/'+substring(CAST(@year_start_1 AS VARCHAR(8)),5,2)+'/'+substring(CAST(@year_start_1 AS VARCHAR(8)),1,4) (converted to a non table based select for test/debug purposes) So what you would want for your final line of sql would be (untested): Select * from openquery (devbook, 'SELECT cast(year_start_1 as varchar(8)) as year_start_1, substring(CAST(year_start_1 AS VARCHAR(8)),7,2)+'/'+substring(CAST(year_start_1 AS VARCHAR(8)),5,2)+'/'+substring(CAST(year_start_1 AS VARCHAR(8)),1,4) FROM web_statements') Second Edit for debug notes: I thought it might also be worth suggesting how to debug this sort of problem. The error message suggested that the linked server you were sending the sub-statement to was unable to process the request. The first thing to try in this case would be to run the request directly on the server to see what happens. In this case in fact just parsing it on its own would have revealed the first errors I got. Once you have your statement running form management studio or whatever directly on the server you can try converting it back into the "openquery" style statement and see if ti still works. Bascially break down your complicated scenario into lots of smaller bits to test each one individually.
[ "stackoverflow", "0033646005.txt" ]
Q: Get first value of column in dataframe in pandas with offset indices I have a dataframe with offset indices and I'd like to access the first value of interested column: df = pd.DataFrame({"a": [0,1,2], "b":[3,4,5]}, index=[5,6,7]) In [20]: df Out[20]: a b 5 0 3 6 1 4 7 2 5 None of the .ix, .loc methods of pandas dataframe didn't help (or I used them inappropriate): In [24]: df.ix[0,"a"] KeyError: 0 In [27]: df["a"][0] KeyError: 0 I could do it with reset_index method but I'd like to keep original dataframe I found solution but I think it's not the best: In [29]: df["a"].values[0] Out[29]: 0 A: Use iloc[0] to access the first elements: In [193]: print(df['a'].iloc[0]) print(df['b'].iloc[0]) 0 3 or head: In [194]: df.head(1) Out[194]: a b 5 0 3
[ "stackoverflow", "0055188160.txt" ]
Q: Make a while loop delay repeating until ajax calls in it are complete Before I explain what I want to do, here's an MCV of what I'm coding $("#button").submit(function(event) { event.preventDefault(); var formData = new FormData(this); var myString = $('#textarea').val(); var myRegexp = /src="blob:([^'"]+)"/gm; match = myRegexp.exec(myString); var inProgress = 0; while (match != null) { var xhr = new XMLHttpRequest(); addr = match[1]; xhr.open('GET', 'blob:' + addr, true); xhr.responseType = 'blob'; xhr.onload = function(e) { if (this.status == 200) { var myBlob = this.response; var data = new FormData(); data.append('file', myBlob); $.ajax({ url: "uploader.php", type: 'POST', data: data, contentType: false, processData: false, beforeSend: function() { inProgress++; }, success: function(data) { myString = myString.replace("blob:" + addr, data); }, error: function() { // error }, complete: function() { --inProgress; } }); } else { // error } }; xhr.send(); match = myRegexp.exec(myString); } if (!inProgress) { formData.set('textarea', myString); submitForm(formData); } }); So, I have a text area and it contains an unknown number of BLOB objects. I first try to find these BLOB objects using regexp and then I upload them to the server using a PHP file called uploader.php. Once the file is uploaded, it will return the URL of the uploaded file and I want to replace the BLOB URL by the URL of the uploaded file in the text area and then submit the final content of the textarea to the server for further processing. It turns out that when I run the code, only the last instance of the regexp is replaced by its uploaded URL. The others remain as they were. I suspect that this is because the while loop does not wait for the ajax requests to be complete. I had a similar problem when trying to submit the form and I solved it by following the suggestions in this answer but I don't know how to fix this issue this time. Any idea is appreciated Update: I tried to make ajax work synchronously but my browser said that it was deprecated and it didn't work. A: It seems you don't really need it to be synchronous (and I can't see a case when it's better to make an async action look synchronous), but rather only need it to be sequential. It is possible to make async actions sequential by the use of callbacks (which are rewritable as Promise and in turn rewritable as async/await methods but I'll keep it simple): // myString is made global for simplicity var myString; function uploadBlob(myBlob, addr, callback) { var data = new FormData(); data.append('file', myBlob); $.ajax({ url: "uploader.php", type: 'POST', data: data, contentType: false, processData: false, success: function(data) { // file uploaded OK, replace the blob expr by the uploaded file url(data) myString = myString.replace("blob:" + addr, data); callback(); }, error: function() { // error, the uploaded most likely failed, we leave myString alone // or alternatively replace the blob expr by empty string // because maybe we dont want to post blob in the final form submit // uncomment if needed // myString = myString.replace("blob:" + addr, ""); callback(); } }); } function getBlobAndUpload(addr, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', 'blob:' + addr, true); xhr.responseType = 'blob'; xhr.onload = function(e) { if (this.status == 200) { var myBlob = this.response; uploadBlob(myBlob, addr, callback); } else { // error, but callback anyway to continue processing callback(); } }; xhr.send(); } function processAddresses(addresses, callback, current) { var index = current || 0; // all addresses processed? if (index >= addresses.length) { // yes no more address, call the callback function callback(); } else { var addr = addresses[index]; // once the get/upload is done the next address will be processed getBlobAndUpload(addr, function() { processAddresses(addresses, callback, index + 1); }); } } $("#button").submit(function(event) { event.preventDefault(); var formData = new FormData(this); var addresses = []; // initialize both localString and myString to the content of the textArea // localString will be used to extract addresses, // while myString will be mutated during the upload process var localString = myString = $('#textarea').val(); var myRegexp = /src="blob:([^'"]+)"/gm; match = myRegexp.exec(localString); // collect all addresses first while (match != null) { addr = match[1]; addresses.push(addr); match = myRegexp.exec(localString); } // initiate sequential processing of all addresses, and // pass the callback function triggering the form submit processAddresses(addresses, function() { // all the successfully uploaded blob exprs in my string should // be now replaced by the remote file url now (see commented part // in upload blob error for a variation of the feature formData.set('textarea', myString); submitForm(formData); }); });
[ "stackoverflow", "0039259367.txt" ]
Q: PyQt5: Progamically adding QWidget to layout, doesn't show Qwidget when a spacer is added Edit: I have tried a few more things. If I move the spacer to a layout below the spacer I am adding to it doesn't exibit the same exact behavior. Its still not optimal, and isn't going to work because my end goal is to have a scrollArea with a spacer inside that i add my widgets to, but this would not look right. I think the problem is the widgets are getting to a size zero I just do not know why or how to fix it. I have two ui files made in QtDesigner. The first file is my main window at the start of the program I load the second ui file and place it into a vertical spacer in the middle of the first one. Additional copies are placed each time a button is clicked. This all works great until I add a vertical spacer to push the items to the top. I have tired adding it from Designer and in the code. Both have the same result. I have looked on google quite a bit and tried a lot of suggestions. I tried setting the second ui files parent as a Qwidget I added on the first that contained the vertical layout. I tried setting the minimum sizes and sizing polices to various things. Below is my current code, any ideas or suggestions would be appreciated! #!python3 import sys from PyQt5 import QtWidgets, QtCore, uic class TimesheetWidget(QtWidgets.QWidget): def __init__(self, parent=None): super(TimesheetWidget, self).__init__(parent) self.parent = parent self.tableRows = dict() def setup(self): self.labelSaved.hide() self.addTableRow() def addTableRow(self): thisRow = len(self.tableRows) self.tableRows[thisRow] = uic.loadUi("gui/tableRow.ui") self.tableRows[thisRow].addButton.clicked.connect(self.addTableRow) self.spacer.addWidget(self.tableRows[thisRow]) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) timesheet = TimesheetWidget() Mytimesheet = uic.loadUi("gui/timesheet.ui", baseinstance=timesheet) Mytimesheet.setup() Mytimesheet.show() sys.exit(app.exec_()) here is a link to the ui files (they are to long to post): gist link for ui files A: I finally fixed this by trying random things over and over until something worked. It turned out that on my second ui file I did not have a top level layout. (I am not sure if that's what its called.) To fix this I right clicked on the top level widget and choose layout and selected horizontal layout, although I think any would have worked. Here is a picture that shows the top level widget with the cancel symbol on it. Once I added the layout that went away and everything worked!
[ "stackoverflow", "0010044197.txt" ]
Q: How to get QThreads to work in a console PySide program? I'm trying to learn how to use threading in a python program. I'm using PySide and QThreads since I'm going to implement gui afterwards with PySide. I have understood the main consept of threading, at least I think. But I'm still confused with event loops. And I think that is the problem with my aplication. Here is a sample application that I can't get to work properly. In my main class I have several worker threads and I want to them to report their progress to the main main class. But the main program don't print progress messages in real time. How could I get this to work? from PySide import QtCore import time, sys class MyWorkerThread(QtCore.QThread): message = QtCore.Signal(str) def __init__(self, id, parent=None): super(MyWorkerThread, self).__init__(parent) self.id = id def run(self): for i in range(10): self.message.emit("%d: %d" % (self.id, i)) time.sleep(0.2) class MainProgram(): def __init__(self, parent=None): self.threads = [] self.addWorker(MyWorkerThread(1)) self.addWorker(MyWorkerThread(2)) def addWorker(self, worker): worker.message.connect(self.printMessage, QtCore.Qt.QueuedConnection) self.threads.append(worker) def startWorkers(self): for worker in self.threads: worker.start() worker.wait() self.workersFinished() def workersFinished(self): QtCore.QCoreApplication.instance().quit() @QtCore.Slot(str) def printMessage(self, text): sys.stdout.write(text+'\n') sys.stdout.flush() if __name__ == '__main__': app = QtCore.QCoreApplication(sys.argv) m = MainProgram() m.startWorkers() sys.exit(app.exec_()) A: worker.wait() is the problem. This call blocks the main thread (in this case the one running event loop) until the worker finishes its job. Here is a slightly changed version (I've commented my changes): from PySide import QtCore import time, sys class MyWorkerThread(QtCore.QThread): message = QtCore.Signal(str) def __init__(self, id, parent=None): super(MyWorkerThread, self).__init__(parent) self.id = id def run(self): for i in range(10): self.message.emit("%d: %d" % (self.id, i)) time.sleep(0.2) class MainProgram(): def __init__(self, parent=None): self.threads = [] self.addWorker(MyWorkerThread(1)) self.addWorker(MyWorkerThread(2)) def addWorker(self, worker): worker.message.connect(self.printMessage, QtCore.Qt.QueuedConnection) # connect the finished signal to method so that we are notified worker.finished.connect(self.workersFinished) self.threads.append(worker) def startWorkers(self): for worker in self.threads: worker.start() # no wait, no finished. you start the threads and leave. def workersFinished(self): if all(worker.isFinished() for worker in self.threads): # wait until all the threads finished QtCore.QCoreApplication.instance().quit() @QtCore.Slot(str) def printMessage(self, text): sys.stdout.write(text+'\n') sys.stdout.flush() if __name__ == '__main__': app = QtCore.QCoreApplication(sys.argv) m = MainProgram() m.startWorkers() sys.exit(app.exec_())
[ "ru.stackoverflow", "0000636933.txt" ]
Q: Валидация входящих данных Yii по integer Вечер добрый, не получается сделать валидацию входящих данных в Yii2, в модели пишу правило, но вылетает исключение. ['idUpdateMessage', 'numerical', 'integerOnly'=>true] A: Разобрался сам, для проверки входящих данных по integer нужно писать так: ['idUpdateMessage', 'integer', 'integerOnly'=>true, 'message'=>'Что писать если значение не integer']
[ "stackoverflow", "0020143592.txt" ]
Q: How to insert multiple rows by mysqli_multi_query()? I am trying to do multiple insertions using mysqli_multi_query() and following is my code. The issue is its not executing the result . Kindly let me know what i did wrong? $query = "INSERT INTO crap_table (name, number, class)VALUES ('Peter', 35,'BS')"; $query .= "INSERT INTO crap_table (name, number, class)VALUES ('Sahil', 35,'MS')"; mysqli_multi_query($con,$query); A: mysqli_multi_query Executes one or multiple queries which are concatenated by a semicolon. You need to have a ; between them. Like $query = "INSERT INTO crap_table (name, number, class)VALUES ('Peter', 35,'BS');"; ^ $query .= "INSERT INTO crap_table (name, number, class)VALUES ('Sahil', 35,'MS')"; Provided that you are connected to the database already? Like $con= mysqli_connect("localhost", "my_user", "my_password", "world");
[ "math.stackexchange", "0001398026.txt" ]
Q: Understanding Multiplicative Inverse in RSA Okay so I am reading up on RSA, trying to understand how it works, and I come across this $ x∈ℤp, x−1 ∈ℤp ⟺ \gcd(x,p) = 1$ Now it then gives an example, as follows: Lets work in the set $ℤ9$, then $4∈ℤ9$ and $\gcd(4,9)=1$. Therefore 4 has a multiplicative inverse (written 4^1) in $\mod9$, which is 7. And indeed, $4⋅7=28=1\mod9.$ Now I do not understand how one can simply say the inverse is 7. Essentially my question is, where has this come from? Apologies if I am being stupid Thanks for the help, sorry I do not know how to format properly! A: Remember that in the ordinary real numbers the multiplicative inverse of $a$, written $\frac1a$, is the number $x$ such that $a\cdot x=1$. Here we're not working with real numbers, but with residues modulo $n$, which means (primitively speaking) that after each addition or multiplication we're supposed to reduce to one of the residues $0, 1, 2, \ldots, n-1$. So in the integers modulo $9$, it is indeed the case that $4\cdot 7=1$ because $28$ and $1$ are the same thing when we work modulo $9$. Since $7$ is something that makes $1$ when multiplied by $4$, it is by definition the multiplicative inverse of $4$. Or did you ask how the author discovered that the right number to try was $7$ rather than something else? In this case, he probably just tried all of the possible numbers modulo 9 one my one until finding one that would work (there are only 9 numbers to try). For larger moduli, the extended Euclidean algorithm can be used to find modular inverses. There's a pretty good chance that the text you're reading will explain how that works if you just read on and keep faith for a page or so. So far it's probably just explaining what "multiplicative inverse" means and how to recognize one if you come across it. Actually finding it is the logical next step.
[ "stackoverflow", "0005435889.txt" ]
Q: wcf ria services method return I have a Silverlight site with wcf ria services, this is just a test. The service is as follow [EnableClientAccess()] public class PersonService : DomainService { [Invoke] public string[] GetPersonNames() { return new string[] { "abc", "cba", "ddd", "ttt" }; } [Invoke] public string GetName() { return "teste"; } [Invoke] public string Test(string str) { return str; } } I have a xaml page where I call the service SLRiaTest.Web.PersonContext person = new SLRiaTest.Web.PersonContext(); public MainPage() { InitializeComponent(); person.GetPersonNames(OnFinished,null); } private void OnFinished(InvokeOperation<string[]> obj) { var list = obj.Value; } but the Value is always null and the break point that I have in the serice never gets hit. I search the internet high and low and can't find anything that might tell me what I'm doing wrong, any help would be great, I'm desperate.... I suppose that I can use RIA service without entity framework right? A: The details on what does and does not work for calls across the wire in RIA Services are complex. If you want a detailed answer on what is going on here, you'll have better luck asking on the RIA Services forum However, you're kind of going against the design of RIA Services. If you want to return a collection of objects, you should use Query instead of Invoke. [EnableClientAccess()] public class PersonService : DomainService { [Query] public IEnumerable<string> GetPersonNames() { return new string[] { "abc", "cba", "ddd", "ttt" }; } } ... public MainPage() { InitializeComponent(); person.Load(person.GetPersonNamesQuery(), OnFinished, null); } private void OnFinished(LoadOperation<IEnumerable<string>> obj) { var list = obj.Value; } I just did that off the top of my head so might have some minor errors. But that's the general idea.
[ "stackoverflow", "0003791745.txt" ]
Q: Working with hierarchical data in Mongo Note: I ended up answering my own question shortly after posting this. Thanks and sorry if you spent time reading my rediculously long post. Introduction I'm sort of a Mongo noob, just trying to get the hang of things here. I am looking at trying to create a hierarchical data structure to which i can add nodes/leaves dynamically. The schema is fixed, but the nodes on any given tree should be able to change at any time. The main thing I'm looking for is how to add/remove nodes on deeply nested nodes without rewriting the whole tree. Here'es an example for a static analysis program, the collection is called "builds". A sparse document would look like this (_id's removed for brevity's sake): { name: "build from changeset #5678", assemblies: [ { name: "someAssembly1.dll", warnings: [ { level: 0, message: "something doesn't conform to our standard" } ] } ] } So to kick it off, I do the following; db.builds.insert({name: "build from changeset #5678}) Then, add an assembly: db.builds.update({name: "build from changeset #5678"}, {$addToSet: {assemblies: {name: "someAssembly1.dll"}}}) The REAL Question Now, how do I add a warning? I was thinking it might be something like this: db.builds.update({ name: "build from changeset #5678", "assemblies.name": "someAssembly1.dll" },{ $addToSet: { assemblies.warnings: { level: 0, name: "something doesn't conform to our standard" } } }) But that gives me "missing : after property id (shell):0" I also tried putting quotes around "assemblies.warnings", but that says "can't append to array using string field name [warnings]" Does anyone know Mongo any better than I and can help me? Am I wrong in trying to do deeply nested trees on Mongo? Would I be better off doing it with multiple collections and somewhat relational? I was under the impression that NOT doing relational (as well as ACID) was one of the main benefits for Mongo, but then again, maybe thats just my noob showing again. A: So I've been struggling with this all day, and sure enough, the moment I post it to StackOverflow I run across something that gives me the answer. The proper answer looks like this: db.builds.update({ name: "build from changeset #5678", "assemblies.name": "someAssembly1.dll" },{ $addToSet: { "assemblies.$.warnings": { level: 0, name: "something doesn't conform to our standard" } } }) Note the "assemblies.$.warnings" I found it here: http://groups.google.com/group/mongodb-user/browse_thread/thread/e8f4ea5dc1955a98#
[ "stackoverflow", "0058906971.txt" ]
Q: Confirm checked list box In the below code I am trying to output a message to confirm if a checkbox was ticked or not. How do I go about checking each box? private void btnRemove_Click(object sender, EventArgs e) { //Validate input data //check if a dvd was entered //here i want to check to see if any of my check boxes were ticked. if (chkDVD == "") { MessageBox.Show("No DVD Selected!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //Save data in DVDs File //Display Confirmation Message MessageBox.Show("DVD Succesfully removed!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } A: Assuming that you're using a standard WinForms checkbox, then all you need is to replace your current if statement with the following line: if (!chkDVD.Checked) If not, please post more of your code relating to what checkboxes you have.
[ "stackoverflow", "0009809812.txt" ]
Q: converting from HTML to Wordpress.. not sure why CSS styling was lost/isn't working? I built a site in HTML/CSS, and everything was to my liking. However, in the conversion from HTML to Wordpress(WP), the CSS styling seems to have been lost. I'm new to this, so it's difficult for me to pinpoint what's going on.. The #main article <p> section doesn't seem to be following the #main article p {float: right; margin-top: -85px; margin-left: 230px; padding-left: ; width: 403px;} parameters. Any ideas on what has happened? <div id="main"> <article> <?php if(have_posts()) : while(have_posts()) : the_post(); ?> <div id="headline"> <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></h1> </div><!-- end headline --> <div class="postinfo"> <ul> <li>Posted by <?php the_author(); ?></li> <li><?php the_date(); ?></li> <li>tags: <a href="#">cool</a>, <a href="#">awesome</a></li> </ul> </div><!-- end postinfo --> <p><?php the_content(); ?></p> </article><!-- end article --> <?php endwhile; ?> <?php else :?> <p>I'm not quite sure what you're looking for.</p> <?php endif; ?> </div><!-- end main --> #main { float: left; margin-left: 315px; margin-top: 310px; } #main article .postinfo { list-style-type: none; margin-left: ; width: 150px; } #main article p { float: right; margin-top: -85px; margin-left: 230px; padding-left: ; width: 403px; } EDIT: here it is live here it is live A: You don't need the <p></p> tags around <?php the_content(); ?> since that will be generated within the content, and you are basically wrapping that in a paragraph. It is a also good idea to have the static html files open and your Wordpress project side by side, so you can inspect elements on both and make sure your selectors match. This usually helps me figure out when I'm missing the selector for some reason.
[ "stackoverflow", "0008290027.txt" ]
Q: PHP Ignoring if else statements I have an if statement for retrieving the lat and long from an address and insert it into a sql database. I have the basic structure of the form working but wish to include empty field checking and pregmatch but if i try an enter more else if statements the nothing happens. // Your Google Maps API key $key = "key"; // Desired address $address = 'http://maps.google.com/maps/geo?q='.$location.'&output=json&oe=utf8&sensor=false&key=$key'; // Retrieve the URL contents $data = file_get_contents($address); // Parse the returned XML file $jsondata = json_decode($data,true); if (is_array($jsondata )&& $jsondata ['Status']['code']==200){ $lat = $jsondata ['Placemark'][0]['Point']['coordinates'][0]; $lon = $jsondata ['Placemark'][0]['Point']['coordinates'][1]; } elseif (mysql_query("INSERT INTO database (type, category, suggest, title, url, description, phone, fax, facebookpage, twitterpage, busemail, number, streetAddress, city, state, zip, country, name, email, latitude, longitude) VALUES ('$type', '$category', '$title', '$url', '$description', '$phone', '$fax', '$facebookpage', '$twitterpage', '$busemail', '$number', '$streetAddress', '$city', '$state', '$zip', '$country', '$name', '$email', '$lat', '$lon')"); { die( header ("Location: http://www.exampleerrorpage.com" ) . mysql_error()); } else { mail( $email, "Subject", $message, $headers ); header( "Location: http://www.examplecomplete.com/" ); } Thanks in advance for any help. Edit only have basic knowledge in php and am still very much a newbie. Be Gentle. Thanks again. EDIT - The address portion of the form my not always be there. So the geocode does not always need to execute. A: Just slowly go through your logic again and think. Your programs says: If the JSON data is valid, set the two variables $lat and $lon, else (if the JSON data is not valid but) if the SQL query returns true, die with an error, else (if none of the above), send an email. You simply have a very screwed up if-then-else logic. Logic-wise, you probably want something along the lines of: if (/* JSON data not valid */) { die('Error'); } $lat = ...; $lon = ...; // Prevent SQL injection! $lat = mysql_real_escape_string($lat); $lon = mysql_real_escape_string($lon); $query = "INSERT INTO ..."; if (!mysql_query($query)) { die(mysql_error()); } if (!mail(...)) { die('Error sending mail'); }
[ "math.stackexchange", "0001561397.txt" ]
Q: Multivariable Calculus - Chain rule - Partial derivatives computation Suppose you are given that $f$ is a differentiable function of two variables $u$ and $v$. Let $g(r,s)=f(r^2-s^2, 2rs)$. Compute $\nabla g(r,s)$ in terms of $\partial f\over\partial u$, $\partial f\over\partial v$ and other functions. I expressed $f$ as $f(u,v)=f(r^2-s^2, 2rs)$ and set $u=r^2-s^2$ and $v=2rs$. To calculate the gradient I did: $$\nabla g(r,s)=\frac{\partial g}{\partial r}\mathbf i + \frac{\partial g}{\partial s}\mathbf j$$ From there: $$=\left({\partial f\over\partial u}{\partial u\over\partial r}\right)\mathbf i + \left({\partial f\over\partial v}{\partial v\over\partial s}\right)\mathbf j$$ This is the step where I lost points but I can't seem to figure out where I went wrong. A: In replacing $\frac{\partial g}{\partial r}$ with $\left({\partial f\over\partial u}{\partial u\over\partial r}\right)$, you are treating $f$ as if it were a function of $u$ alone, and similarly in replacing $\frac{\partial g}{\partial s}$ with $\left({\partial f\over\partial v}{\partial v\over\partial s}\right)$, you are treating $f$ as if it were a function of $v$ alone. The correct formulas are:$$\frac{\partial g}{\partial r} = {\partial f\over\partial u}{\partial u\over\partial r} + {\partial f\over\partial v}{\partial v\over\partial r}\\\frac{\partial g}{\partial s} = {\partial f\over\partial u}{\partial u\over\partial s} + {\partial f\over\partial v}{\partial v\over\partial s}$$
[ "stackoverflow", "0027875865.txt" ]
Q: Magento Add Multiple Buttons to Sale Order View I have a file extending Mage_Adminhtml_Block_Sales_Order_View: NameSpace_Module_Block_Sales_Order_View Within it: public function __construct() { parent::__construct(); $_label = Mage::helper('sales')->__('Button 1'); $this->_addButton('button_one', array( 'label' => $_label, 'onclick' => $omittedJs, 'class' => 'go' ),0,15); $_label = Mage::helper('sales')->__('Button 2'); $this->_addButton('button_two', array( 'label' => $_label, 'onclick' => $omittedJs, 'class' => 'go' ),0,15); } For some reason, only Button 2 will display, if I remove Button 2, Button 1 will display. How can I get both buttons to show up? A: Try following instead of your code. $_label = Mage::helper('sales')->__('Button 1'); $this->_addButton('button_one', array( 'label' => $_label, 'onclick' => $omittedJs, 'class' => 'go' ),0,15); $_label = Mage::helper('sales')->__('Button 2'); $this->_addButton('button_two', array( 'label' => $_label, 'onclick' => $omittedJs, 'class' => 'go' ),0,16); Last argument in _addButton defines position. It was same in your code
[ "stackoverflow", "0051736204.txt" ]
Q: Highlighting plain html in JS I'm writing a (dynamic) RegEx parser for plain HTML to extract values. To show the current RegEx result, I want to show the HTML code highlighted with the current result. I have the HTML code in a variable and my RegEx match function returns the current result and the index of the result. Therefore, I injected a <span class="highlight"> to the position of the found string, and close it by </span> after the length of the match. My current problem is: If I set the element with element.text(newtext), my injected HTML is not parsed. On the other hand, if I set the element with element.html(newtext), the full HTML is parsed and possibly broken. If I first escape the HTML tags to not be parsed, the index of RegEx.match of the raw html is not equal to the escaped html, therefore the injection is on the wrong place. Is there a nice way to handle html code as plain text, but injection of highlighting html goes to the right place using an index? Example Think of a full html source code - this is a one line snippet of my weather station: <td bgcolor="#EDEFEF"><input name="inHumi" disabled="disabled" type="text" value="63" /></td> The user enters a RegEx matching value=", therefore value=" should be highlighted in the html string. Sample code The JS code looks like this. Think of all set variables are user-defined in an HTML form, therefore the user enters the RegEx and the HTML source code as text, and the RegEx match should be visible in that form. var rawhtml = '<td bgcolor="#EDEFEF"><input name="inHumi" disabled="disabled" type="text" value="63" /></td>'; var regex = 'value=\"'; var result = rawhtml.match(regex); var result_string = result[0]; var result_index = result.index; $("#visiblehtml").html(rawhtml.substring(0, result_index) + "<span class='highlight'>" + rawhtml.substring(index, index + result_string.length) + "</span>" + rawhtml.substring(index + result_string.length)); Inserting this span in the middle of the input field, the html will break. Also, setting the element with .html will parse and show the full rawhtml, not the rawhtml source. A: Here I answer my own question with my solution. I was thinking much to complicated and now have a pragmatic way. I first inject an own, unique token to the raw html. Then I encode the html (here I use the htmlEncode function from https://stackoverflow.com/a/14346506/3466839). Last I replace my tokens by the real highlight code. Then I can set the result into the element with .html. var rawhtml = '<td bgcolor="#EDEFEF"><input name="inHumi" disabled="disabled" type="text" value="63" /></td>'; var regex = 'value=\"'; var result = rawhtml.match(regex); var result_string = result[0]; var result_index = result.index; var visiblehtml = rawhtml.substring(0, result_index) + "***highlight*" + rawhtml.substring(index, index + result_string.length) + "*highlight***" + rawhtml.substring(index + result_string.length); var visiblehtml = htmlEncode(visiblehtml); visiblehtml = visiblehtml.replace('***highlight*', '<span class="highlight">'); visiblehtml = visiblehtml.replace('*highlight***', '</span>'); $("#visiblehtml").html(visiblehtml); I'm sorry that my question was not good and was downvoted. If you leave comments what I have done wrong, I'll do that better next time. Thanks for your engagement helping so many people!
[ "stackoverflow", "0012140498.txt" ]
Q: Achieve strategy pattern when we have different return type I have SaveManager Abstract class and my concrete classes TVSaveManager, DataSaveManager and VoiceSaveManager implementing SaveManager Abstract class. List<SaveManager> lstPrdSaveManager; public SaveResponseModel SaveProducts(SaveProductsRequest objSaveProductsRequest) { SaveResponseModel saveResponseModel = new SaveResponseModel(); lstPrdSaveManager = SaveManagerFactory.GetSaveManagers(objSaveProductsRequest, saveResponseModel); lstPrdSaveManager.ForEach(saveManager => { saveResponseModel = saveManager.MapAndSaveProduct(); }); return saveResponseModel; } Factory class will decide which manager to create and send us the list. I will loop thru the list and invoke the common interface 'MapAndSaveProduct' that every concrete classes will adhere. I guess more or like a strategy pattern. But the thing is all the concrete savemanage's MapAndSaveProduct method return type is different. TVResponse for TvSaveManager and DataResponse for DataSaveManager and so on. So i created SaveResponseModel class to club all the return types (I am passing SaveResponseModel to factory so that it will get passed to all concrete savemanager class's constructor. Individual class will set the desired property., like TvSaveManager -> saveResponseModel.TvResponse). I get desired result and code looks clean. Questions are, 1) Is it the correct way to use this pattern when we have different type? 2) If concrete class have different types, should not we use strategy pattern? 3) Should I approach to different design pattern in this case. if yes which one? A: You've got a combination of Strategy and Visitor in a single group of methods; this is absolutely OK. You could separate them out by giving the responses a common interface, and adding a visitor to it for harvesting the right response. This would apply two patterns in sequence, rather than applying both at the same time. interface IResponseVisitor { void VisitTvResponse(TvResponse r); void VisitDataResponse(DataResponse r); } interface IResponse { void Accept(IResponseVisitor v); } class TvResponse : IResponse { public void Accept(IResponseVisitor v) { v.VisitTvResponse(this); } } class DataResponse : IResponse { public void Accept(IResponseVisitor v) { v.VisitDataResponse(this); } } Now all your MapAndSaveProduct implementations could return the common IResponse. You could collect them all, and then go through them with an implementation of IResponseVisitor, and do what you need for each type inside the corresponding Accept method.
[ "stackoverflow", "0000675953.txt" ]
Q: How to print an entire istream to standard out and string How do you print an istream variable to standard out. [EDIT] I am trying to debug a scenario wherein I need to ouput an istream to a log file A: You ouput the istream's streambuf. For example, to output an ifstream to cout: std::ifstream f("whatever"); std::cout << f.rdbuf(); A: Edit: I'm assuming that you want to copy the entire contents of the stream, and not just a single value. If you only want to read a single word, check 1800's answer instead. The obvious solution is a while-loop copying a word at a time, but you can do it simpler, as a nice oneliner: #include <iostream> #include <iterator> ... std::istream i; std::copy(std::istream_iterator<char>(i), std::istream_iterator<char>(), std::ostream_iterator<char>(std::cout)); The stream_iterators use operator << and >> internally, meaning they'll ignore whitespace. If you want an exact copy, you can use std::istreambuf_iterator and std::ostreambuf_iterator instead. They work on the underlying (unformatted) stream buffers so they won't skip whitespace or convert newlines or anything. You may also use: i >> std::noskipws; to prevent whitespace from disappearing. Note however, that if your stream is a binary file, some other characters may be clobbered by the >> and << operators. A: This will print the whole stream, 1 character at a time: char c; c = my_istream.get(); while (my_istream) { std::cout << c; c = my_istream.get(); } This will print the whole thing, but discard whitespace: std::string output; while(my_istream >> output) std::cout << output;
[ "stackoverflow", "0005289274.txt" ]
Q: How can I refresh a JScrollPane after choosing an element from a JComboBox? I have a JComboBox, and I want to load in a JScrollPane a different content everytime I choose a different element from the JComboBox. The content consists of a various number of JLabels and JTextFields. What I have done: JScrollPane scrollPane; JComboBox combo; JPanel back = new JPanel(new BorderLayout()); combo = new JComboBox({ "Bird", "Cat", "Dog", "Rabbit", "Pig" }); combo.addActionListener(new AnimalLoader()); scrollPane = showPanel((String) combo.getSelectedItem()); back.add(combo, BorderLayout.NORTH); back.add(scrollPane, BorderLayout.SOUTH); back.setVisible(true); protected JScrollPane showPanel(String name) { JPanel contentPanel = new JPanel(new JLabel(name)); scrollPane = new JScrollPane(contentPanel); return scrollPane; } private class AnimalLoader implements ActionListener { public void actionPerformed(ActionEvent e) { JComboBox cb = (JComboBox) e.getSource(); String selected = (String) cb.getSelectedItem(); scrollPane = showPanel(selected); } } I didn't manage to make this reload a different JScrollPane when I choose another item. Only the JScrollPane that belongs to the first item (the default one) of the JComboBox is loaded. Any ideas of what I've done wrong please? A: scrollPane = showPanel(selected); Don't create a new scoll pane when you select an item. Instead you need to change the panel that is contained in the viewport of the scroll pane. That is, your "showPanel" method should return the panel, not a scrollpane. Then you can use: scrollPane.setViewportView( showPanel(selected) ); Next time a proper SSCCE should be posted.
[ "stackoverflow", "0033041363.txt" ]
Q: What does "read -p" do in a linux shell script? I have a script that I have copied and edited. There are a couple of lines in there that I need explaining if possible please. These are the lines: read -p "please enter the username you wish to create: " username if id -u $username >/dev/null 2>&1; then What does read -p do? What does id -u do? What does >/dev/null 2&1; do? Then further on in the script, it has this line that says this: sudo useradd -g $group -s $bash -d $homedir -m $username -p $password Again please could someone explain all the minus signs in this line please? (-g, -s, -d, -m, -p) A: First off, the structure <command> -<option> means that you want to execute <command> using the option corresponding to <option>. A - after a command means that the following letter is an option. Most commands have several options you can use. Options are usually defined using either a single letter or a couple of words separated by -. Side Note: For options that are a couple of words rather than a single letter, often it will use two minus signs -- instead of one, signifying that it is a "long named" option. So, using the read -p example, this means you want to execute read using the p option, which stands for prompt. Now, sometimes an option will require an argument. In your examples, the options to useradd have arguments. Arguments are usually defined like <command> -<option> [argument]. So, in the useradd example, $group is an argument for the option g. Now for the commands themselves: read is a bash built-in (not a POSIX shell command) that reads from standard input. The -p option makes it read as a prompt, meaning it doesn't add a trailing newline before trying to read input. if checks the return status of the test command (in this case id -u $username >/dev/null 2>&1) If the return status is 0, the then part is executed id prints user groups and ids The -u option "prints only the effective user ID". >/dev/null 2>&1 redirects standard input and standard error to /dev/null, meaning they do not get printed to the terminal. useradd creates a new user -g sets the initial group for the user -s sets the name of the user's login shell -d sets the name of the user's login directory -m says to create the user's home directory if it does not exist. -p defines the user's encrypted password. For future reference, you can look up commands in the linux manual pages by doing man <command> on the command line. These manual pages tell you what a command does, as well as explaining all of its options. Bash built-ins like read are all on a single man page that is not the easiest thing to use. For those I find googling them easier. Usually http://ss64.com/ will come up in the results, which contains the info from the bash built-ins man page, but separated into different pages by command. I find this much easier to use.
[ "stackoverflow", "0002307157.txt" ]
Q: Alternative to the "switch" Statement I do not want to use Switch in my code, so I'm looking for some alternative Example with Switch: function write(what) { switch(what) { case 'Blue': alert ('Blue'); break; ... case 'Red': alert ('Red'); break; } } Example without Switch: colors = []; colors['Blue'] = function() { alert('Blue'); }; colors['Red'] = function() { alert('Red'); }; function write(what) { colors[what](); } My questions are: Do you know any other alternatives? Is this best solution? A: I have only a note about your second approach, you shouldn't use an Array to store non-numeric indexes (that you would call in other languages an associative array). You should use a simple Object. Also, you might want to check if the what argument passed to your write function exists as a property of your colors object and see if it's a function, so you can invoke it without having run-time errors: var colors = {}; colors['Blue'] = function() { alert('Blue'); }; colors['Red'] = function() { alert('Red'); }; function write(what) { if (typeof colors[what] == 'function') { colors[what](); return; } // not a function, default case // ... } A: I used a structure like this today: var chosenColor = 'red'; var colorString = { 'red': 'The color is red.', 'green': 'The color is green.', 'blue': 'The color is blue.', }[chosenColor] || 'The color is unknown.'; I like that it's a really small amount of code to choose a string based on choice. You could also pass it to a function: alert({ 'red': 'The color is red.', 'green': 'The color is green.', 'blue': 'The color is blue.', }[chosenColor] || 'The color is unknown.');