date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/15
1,190
4,455
<issue_start>username_0: I have an error while i want to register in the app. I had a table registers which i deleted it. When i wanted to register, all data went to that table. Now i want them to go to users table and i have the following functions and model. But when i submit the info to be registered, this error pops out ``` QLSTATE[42S02]: Base table or view not found: 1146 Table '24gardi.registers' doesn't exist (SQL: select count(*) as aggregate from `registers` where `username` = <EMAIL>) ``` This is the controller: ``` public function ShowRegisterForm() { $title = "ثبت نام"; return view('register')->with('title', $title); } public function register(Request $request) { $this->validation2($request); $register = User::create([ 'username' => $request->input('username'), 'password' => <PASSWORD>($request->input('username')), 'register_type' => $request->input('username'), 'first_name' => $request->input('username'), 'last_name' => $request->input('username'), 'gender' => $request->input('username'), 'email' => $request->input('username'), 'mobile' => $request->input('username'), 'national_id' => $request->input('username'), 'personnel_pic' => $request->input('username'), 'contract_pic' => $request->input('username'), 'national_id_pic' => $request->input('username'), 'profile_pic' => $request->input('username') ]); if ($register) { return redirect('/')->with('success', 'ثبت نام با موفقیت انجام شد.'); } return redirect('/register')->with('errors', 'ثبت نام با موفقیت انجام نشد.'); } public function validation2($request) { return $this->validate($request, [ 'username' => 'required|unique:registers|max:255', 'password' => 'required|max:255', 'first_name' => 'required|max:255', 'last_name' => 'required|max:255', 'national_id' => 'required|unique:registers|max:10', 'gender' => 'required|max:5', 'email' => 'required|email|unique:registers|max:255', 'mobile' => 'required|max:13' ]); } ``` This is the route (the named route is the one getting used in the form in view): ``` Route::Get('/register', 'UsersController@ShowRegisterForm'); Route::Post('/register', 'UsersController@register')->name('custom.register'); ``` And this is the model(and yes i have added use App\User (the model for users table) in the controller called UsersController): ``` protected $table = 'users'; protected $fillable = [ 'register_type', 'username', 'password', 'first_name', 'last_name', 'national_id', 'gender', 'mobile', 'email', 'personnel_pic', 'national_id_pic', 'contract_pic', 'profile_pic', 'score' ]; public function tours () { return $this->belongsToMany('App\Tour'); } public function comments () { return $this->hasMany('App\Comment'); } public function suggestions () { return $this->belongsToMany('App\Suggestion'); } /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'remember_token', ]; ``` What im trying to say is that i dont undrestand why the error pops out. Please if anyone knows what the error is help me.<issue_comment>username_1: You are referencing to a wrong table in your in Validations() ``` public function validation2($request) { return $this->validate($request, [ 'username' => 'required|unique:users|max:255', 'password' => '<PASSWORD>', 'first_name' => 'required|max:255', 'last_name' => 'required|max:255', 'national_id' => 'required|unique:users|max:10', 'gender' => 'required|max:5', 'email' => 'required|email|unique:users|max:255', 'mobile' => 'required|max:13' ]); } ``` Read more about validations [here](https://laravel.com/docs/5.6/validation) Upvotes: 2 [selected_answer]<issue_comment>username_2: You should change the `unique:registers` in the `validation2` method to `unique:users` Upvotes: 0
2018/03/15
418
1,252
<issue_start>username_0: I have to insert an object `{"category" : "Vehicle"}` in the `rated` array below using Mongo shell commands. How can I do that? ``` { "rating": { "userid": 1234, "bookingid": 4567, "rated": [ { "_id": "5aaa356f6b992b2068a1b691", "category": "Driver", "comment": "Good", "rating": 5 }, { "_id": "5aaa356f6b992b2068a1b690", "category": "Overall", "rating": 7 } ] }, "_id": "5aaa356f6b992b2068a1b68f", "__v": 0 } ```<issue_comment>username_1: It's quite simple. Use `$push` method to push an object into an array. ``` db.ratings.update( { _id: ObjectId('5aaa356f6b992b2068a1b68f') }, { $push: { rated: {"category" : "Vehicle"} } } ) ``` Here, `ratings` is the collection name. This will insert an object into the rated array. Upvotes: 2 <issue_comment>username_2: ``` db.collection.update({ "_id": ObjectId("5aaa356f6b992b2068a1b68f") }, { $addToSet: { 'rating.rated': { "category": "Vehicle" } } } ) ``` Upvotes: 0
2018/03/15
2,544
9,392
<issue_start>username_0: Scenario is, that I'm categorizing tweets into 6 different Polarities viz. Positive, Moderately Positive, Highly Positive, Negative, Moderately Negative and Highly Negative. Since, this procedure undergoes through steps of NLP (using NLTK) I need to go sentence / tweet by tweet. **The Problem:** These polarities are defined by patters after POS tagging. One of the Pattern includes: Verb + Verb + Adjective includes in D (Drought related terms) and in F (Frequent words) I need those Frequent words, that change this sentence into any of those 6 Polarities to be saved into my dataframe. **Snippet:** Here's what I tried ``` for (w1, tag1), (w2, tag2), (w3, tag3) in nltk.trigrams(PoS_TAGS): if tag1.startswith("RB") and tag2.startswith("RB") and tag3.startswith("JJ"): tri_pairs.append((w1, w2, w3)) if tri_pairs[0] or tri_pairs[1] or tri_pairs[2] in D: print("[True]: Tri Pairs are found in Drought Rel. Term") for j in range(len(F)): if tri_pairs[0] or tri_pairs[1] or tri_pairs[2] in F[j]: print("[True]: Tri Pairs are found in Frequent Wordset") if RES is "Positive": RES = "Highly Positive" elif RES is "Negative": RES = "Highly Negative" print "="*25,F[j] FW_list.append(F[j]) else: print"[False]: Doesn't Match with Frequent Wordset\n" else: print"[False]: Tri Pairs Matched Nowhere in D\n" else: print "[TriPair(F)]: Pattern for Adverb, Adverb, Adjective did not match.\n Looking for Bi-Pair Patterns\n" print(tri_pairs) print(">"*13,FW) ``` As you can notice, I tried to print in most ways using List or even inside loop. Both have returned nothing useful. Similarly, other two patterns decide left out polarities. I have also written code to add it in dataframe: ``` fuzzy_df = fuzzy_df.append({'Tweets': tweets[i], 'Classified': RES, 'FreqWord': FW}, ignore_index=True) ``` but so far the csv is returned blank for that column. Edit 1: ------- Frequent words are already available with me. They are as follows: ``` >>> F ['drought', 'water', 'love', 'rain', 'year', 'famine', 'farmers', 'crops', 'south', 'http', 'europe', 'scarcity', 'near', 'thought', 'ever', 'devastates', 'feed', 'message', 'eduaubdedubu', 'instant', 'italy', 'severe', 'by', 'beaches', 'wildfires', 'heat', 'us'] ``` Edit 2 ------ CSV looks like this: ``` Tweets,Classified,FreqWord real time strategy password wastelands depletion groundwater skyrocketing debts make years anantapur drought worse,Negative, calm director day science meetings nasal talk cutting edge remote sensing research drought veg fluorescence calm love,Positive, love thought drought,Positive, neville rooney end ever tons trophy drought,Positive, lakes drought,Positive, lakes fan joint trailblazers dot forget play drought,Positive, reign mother kerr funny none tried make come back drought,Positive, wonder could help thai market b post reuters drought devastates south europe crops,Negative, ``` INPUT File: ``` tweets,polarity real time strategy password wastelands depletion groundwater skyrocketing debts make years anantapur drought worse,Positive calm director day science meetings nasal talk cutting edge remote sensing research drought veg fluorescence calm love,Positive hate thought drought,Negative ``` Although, the output I've shown above is tokenized and stop words are also removed. EXPECTED OUTPUT FILE: ``` Tweets,Classified,FreqWord real time strategy password wastelands depletion groundwater skyrocketing debts make years anantapur drought worse,Negative,water calm director day science meetings nasal talk cutting edge remote sensing research drought veg fluorescence calm love,Positive,drought love thought drought,Positive,drought neville rooney end ever tons trophy drought,Positive,rain lakes drought,Positive,drought lakes fan joint trailblazers dot forget play drought,Positive,farmer reign mother kerr funny none tried make come back drought,Positive,crops wonder could help thai market b post reuters drought devastates south europe crops,Negative,crops ``` Edit 3 ------ ``` FW = '' for i in range(len(tweets)): sent = nltk.word_tokenize(tweets[i]) PoS_TAGS = nltk.pos_tag(sent) from nltk.sentiment.vader import SentimentIntensityAnalyzer sia = SentimentIntensityAnalyzer() one_sentence = tweets.iloc[i] scores = sia.polarity_scores(text=one_sentence) print "POS:", scores.get('pos') print "NEG:", scores.get('neg') print "NEU:", scores.get('neu') POS = scores.get('pos') NEG = scores.get('neg') NEU = scores.get('neu') RES = str() if POS > NEG: RES = 'Positive' elif NEG > POS: RES = 'Negative' elif NEU >= 0.5 or POS > NEU: RES = 'Positive' elif NEU < 0.5: RES = 'Negative' # -------------------------------------------------------- PATTERN ADVERB, ADVERB, ADJECTIVE (Down) tri_pairs = list() for (w1, tag1), (w2, tag2), (w3, tag3) in nltk.trigrams(PoS_TAGS): if tag1.startswith("RB") and tag2.startswith("RB") and tag3.startswith("JJ"): tri_pairs.append((w1, w2, w3)) if tri_pairs[0] or tri_pairs[1] or tri_pairs[2] in D: print("[True]: Tri Pairs are found in Drought Rel. Term") # TRIGGER AREA for j in range(len(F)): if tri_pairs[0] or tri_pairs[1] or tri_pairs[2] in F[j]: print("[True]: Tri Pairs are found in Frequent Wordset") if RES is "Positive": RES = "Highly Positive" FW = F[j] #fuzzy_df['FreqWord'].map(lambda x: next((y for y in x.split() if y in F), 'Not Found')) elif RES is "Negative": RES = "Highly Negative" FW = F[j] else: print"[False]: Doesn't Match with Frequent Wordset\n" else: print"[False]: Tri Pairs Matched Nowhere in D\n" else: print "[TriPair(F)]: Pattern for Adverb, Adverb, Adjective did not match.\n Looking for Bi-Pair Patterns\n" print(tri_pairs) # -------------------------------------------------------- PATTERN ADVERB, ADJECTIVE (Down) bi_pairs = list() for (w1, tag1), (w2, tag2) in nltk.bigrams(PoS_TAGS): if tag1.startswith("RB") and tag2.startswith("JJ"): bi_pairs.append((w1, w2)) if bi_pairs[0] or bi_pairs[1] in D: print("[True]: Bi Pairs are found in Drought Rel. Term") for k in range(len(F)): if bi_pairs[0] or bi_pairs[1] is F[k]: print("[True]: Bi Pairs are found in Frequent Wordset") if RES is "Positive": RES = "Moderately Positive" FW = F[k] elif RES is "Negative": RES = "Moderately Negative" FW = F[k] else: print("[False]: Bi Pairs found missing in Freq. Wordset") else: print("[False]: Bi Pairs Matched Nowhere in D") else: print("[BiPair(F)]: Pattern Not Matched, Looking for Mono Pattern") print(bi_pairs) # -------------------------------------------------------- PATTERN ADJECTIVE (Down) for w, tag in PoS_TAGS: print w, " - ", tag if tag.startswith("JJ"): if w in D: print("Matched with D") for l in range(len(F)): if w is F[l]: print("Matched with F") if RES is "Positive": RES = "Positive" FW = F[l] elif RES is "Negative": RES = "Negative" FW = F[l] else: print("Unmatched in F") FW = F[l] in sent else: print("Unmatched in D") else: print w, "is not an ADJECTIVE" # -------------------------------------------------------- MAKING ENTRY OF RECORDS OF TWEETS and POLARITY RESULT fuzzy_df = fuzzy_df.append({'Tweets': tweets[i], 'Classified': RES, 'FreqWord': FW}, ignore_index=True) # ADDING RECORDS IN DATAFRAME fuzzy_df.to_csv("fuzzy.csv", index=False) ```<issue_comment>username_1: It's quite simple. Use `$push` method to push an object into an array. ``` db.ratings.update( { _id: ObjectId('5aaa356f6b992b2068a1b68f') }, { $push: { rated: {"category" : "Vehicle"} } } ) ``` Here, `ratings` is the collection name. This will insert an object into the rated array. Upvotes: 2 <issue_comment>username_2: ``` db.collection.update({ "_id": ObjectId("5aaa356f6b992b2068a1b68f") }, { $addToSet: { 'rating.rated': { "category": "Vehicle" } } } ) ``` Upvotes: 0
2018/03/15
459
1,413
<issue_start>username_0: I have a container that will hold: - A div that has specific width (50px) and floats to the right. - A button before the above div, that will that the remaining width inside the container. ``` Retarded Button ``` CSS: ``` .responsive-button__container { width: 500px; border: 3px solid black; display: flex; display: -ms-flexbox; } button { width: 100%; } .awesome-logo { margin-left: auto; width: 50px; background: red; } ``` It works fine on Chrome, Safari, and Firefox. But breaks on IE 10 (The div that's supposed to float on the right gets displayed outside of the container) Codepen: <https://codepen.io/d30jeff/pen/GxZPXw> **Edit:** I've decided to use javascript to reduce the button size so the `.awesome-logo` wouldn't get push out of the container at the mean time.<issue_comment>username_1: It's quite simple. Use `$push` method to push an object into an array. ``` db.ratings.update( { _id: ObjectId('5aaa356f6b992b2068a1b68f') }, { $push: { rated: {"category" : "Vehicle"} } } ) ``` Here, `ratings` is the collection name. This will insert an object into the rated array. Upvotes: 2 <issue_comment>username_2: ``` db.collection.update({ "_id": ObjectId("5aaa356f6b992b2068a1b68f") }, { $addToSet: { 'rating.rated': { "category": "Vehicle" } } } ) ``` Upvotes: 0
2018/03/15
559
2,136
<issue_start>username_0: When I'm trying to import a class from the parent folder, which is exported in an index-file, I'm getting this error: TypeError: Super expression must either be null or a function, not undefined When I'm importing it in other places, there is no problem. Import: `import { BaseComponent } from '../';` Index-file in parent folder: ``` import BaseComponent from './BaseComponent'; import Header from './Header'; import NavigationBar from './NavigationBar'; export { BaseComponent, Header, NavigationBar }; ``` Import in other file: `import { BaseComponent, NavigationBar, Header } from './common';` Why does the import not work when it's in a child folder? **UPDATE** File structure: ``` common/ BaseComponent/ index.js Header/ index.js NavigationBar/ index.js (import not working for BaseComponent) index.js (export file) App.js (correct import) ``` **UPDATE 2** This import does work, but I'm trying to use index files to combine the classes: `import BaseComponent from "../BaseComponent";` **UPDATE 3** [![Screenshot error](https://i.stack.imgur.com/4l7do.png)](https://i.stack.imgur.com/4l7do.png)<issue_comment>username_1: **Answer for future reference** I solved this problem by exporting the classes in the index file more directly. I have no clue why the original idea won't work, but this solution does the trick: ``` export {default as BaseComponent} from './BaseComponent'; export {default as Header} from './Header'; export {default as NavigationBar} from './NavigationBar'; ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: @Olivier You are mixing default export syntax and named export syntax. You need to match import and export syntax, so: ``` export default BaseComponent { ... ^^^^^^^ => export default... matches import BaseComponent from '../BaseComponent' ^^^^^^^^^^^^^ ==> import witout {} ``` and ``` export BaseComponent { ... ^^^^^^^^^^^^^ => named export matches import { BaseComponent } from '../BaseComponent' ^^ ^^ ==> use {} to named imports! ``` Upvotes: 2
2018/03/15
2,252
6,560
<issue_start>username_0: I'm writing a Restricted Boltzmann Machine in tensorflow and for the sake of understanding the algorithm, I want to print things on the way as I'm calculating them. I've made a simple attempt on the first part of the algorithm: ``` import tensorflow as tf import numpy as np X_train = np.genfromtxt("binMNIST_data/bindigit_trn.csv", dtype=float, delimiter=",") Y_train = np.genfromtxt("binMNIST_data/targetdigit_trn.csv", dtype=float, delimiter=",") X_test = np.genfromtxt("binMNIST_data/bindigit_tst.csv", dtype=float, delimiter=",") Y_test = np.genfromtxt("binMNIST_data/targetdigit_tst.csv", dtype=float, delimiter=",") ds_train = tf.data.Dataset.from_tensor_slices((X_train, Y_train)) ds_test = tf.data.Dataset.from_tensor_slices((X_test, Y_test)) it = tf.data.Iterator.from_structure(ds_train.output_types, ds_train.output_shapes) train_init_op = it.make_initializer(ds_train) test_init_op = it.make_initializer(ds_test) vb = tf.placeholder(tf.float64, [784]) hb = tf.placeholder(tf.float64, [500]) W = tf.placeholder(tf.float64, [784, 500]) # Features and labels x, y = it.get_next() _h = tf.nn.sigmoid(tf.matmul(tf.reshape(x, [1, 784]), W)+hb) h = tf.nn.relu(tf.sign(_h-tf.random_uniform(tf.shape(_h), dtype=tf.float64))) #Initial bias values vb_init = np.zeros([784]) hb_init = np.zeros([500]) #Initial W value W_init = np.zeros([784, 500]) with tf.Session() as sess: sess.run(train_init_op) print(sess.run(_h, feed_dict={vb:vb_init, hb:hb_init, W:W_init})) print(sess.run(h)) ``` But unfortunately, the last line of the program leads to this error: ``` Traceback (most recent call last): File "/Users/sahandzarrinkoub/.virtualenvs/untitled/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1361, in _do_call return fn(*args) File "/Users/sahandzarrinkoub/.virtualenvs/untitled/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1340, in _run_fn target_list, status, run_metadata) File "/Users/sahandzarrinkoub/.virtualenvs/untitled/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py", line 516, in __exit__ c_api.TF_GetCode(self.status.status)) tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_2' with dtype double and shape [784,500] [[Node: Placeholder_2 = Placeholder[dtype=DT_DOUBLE, shape=[784,500], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/sahandzarrinkoub/Documents/Programming/ANN/lab4/notebook/RBM.py", line 41, in print(sess.run(h)) File "/Users/sahandzarrinkoub/.virtualenvs/untitled/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 905, in run run\_metadata\_ptr) File "/Users/sahandzarrinkoub/.virtualenvs/untitled/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1137, in \_run feed\_dict\_tensor, options, run\_metadata) File "/Users/sahandzarrinkoub/.virtualenvs/untitled/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1355, in \_do\_run options, run\_metadata) File "/Users/sahandzarrinkoub/.virtualenvs/untitled/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1374, in \_do\_call raise type(e)(node\_def, op, message) tensorflow.python.framework.errors\_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder\_2' with dtype double and shape [784,500] [[Node: Placeholder\_2 = Placeholder[dtype=DT\_DOUBLE, shape=[784,500], \_device="/job:localhost/replica:0/task:0/device:CPU:0"]()]] Caused by op 'Placeholder\_2', defined at: File "/Users/sahandzarrinkoub/Documents/Programming/ANN/lab4/notebook/RBM.py", line 24, in W = tf.placeholder(tf.float64, [784, 500]) File "/Users/sahandzarrinkoub/.virtualenvs/untitled/lib/python3.5/site-packages/tensorflow/python/ops/array\_ops.py", line 1746, in placeholder return gen\_array\_ops.\_placeholder(dtype=dtype, shape=shape, name=name) File "/Users/sahandzarrinkoub/.virtualenvs/untitled/lib/python3.5/site-packages/tensorflow/python/ops/gen\_array\_ops.py", line 3051, in \_placeholder "Placeholder", dtype=dtype, shape=shape, name=name) File "/Users/sahandzarrinkoub/.virtualenvs/untitled/lib/python3.5/site-packages/tensorflow/python/framework/op\_def\_library.py", line 787, in \_apply\_op\_helper op\_def=op\_def) File "/Users/sahandzarrinkoub/.virtualenvs/untitled/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 3271, in create\_op op\_def=op\_def) File "/Users/sahandzarrinkoub/.virtualenvs/untitled/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1650, in \_\_init\_\_ self.\_traceback = self.\_graph.\_extract\_stack() # pylint: disable=protected-access InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder\_2' with dtype double and shape [784,500] [[Node: Placeholder\_2 = Placeholder[dtype=DT\_DOUBLE, shape=[784,500], \_device="/job:localhost/replica:0/task:0/device:CPU:0"]()]] ``` To put it simply, it's complaining that I haven't fed it any values for the placeholders. Of course I'd prefer not to do that and instead have tensorflow use whatever I've given it in the previous `sess.run()` call. Is this possible to do?<issue_comment>username_1: I found out the answer myself: Simply pass in `_h` to the `feed_dict` of the last `sess_run()` call. No need to send in everything again: with printing: ``` with tf.Session() as sess: sess.run(train_init_op) h0 = sess.run(_h, feed_dict={vb:vb_init, hb:hb_init, W:W_init}) print(h0) print(sess.run(h, feed_dict={_h:h0})) ``` Upvotes: 0 <issue_comment>username_2: Even if your solution works for your problem, you may want to consider the more general approach of getting everything you need in a single call. ``` sess.run(train_init_op) print(sess.run(_h, feed_dict={vb:vb_init, hb:hb_init, W:W_init})) print(sess.run(h)) ``` becomes ``` _, _h_val, h_val = sess.run([train_init_op, _h, h], feed_dict={vb:vb_init, hb:hb_init, W:W_init}) print(_h_val) print(h_val) ``` Because a `Session` is stateful, you do not have a guarantee that successive calls are consistent. The most common example are random generators that draw new numbers are drawn each time they are queried. When you make a single call to `Session.run`, you are *(almost)* certain that returned values are consistent. Upvotes: 2 [selected_answer]
2018/03/15
710
1,954
<issue_start>username_0: I have an array as shown here ``` 25|12|3|53 ``` I want to break and store the values in the array on to variables as shown below. ``` $variable1 = 25 $variable2 = 12 ... ``` Any suggestions would be appreciated<issue_comment>username_1: Certainly that is possible: ``` php $input = [25,12,3,53]; foreach ($input as $key = $val) { $varname = 'var' . ($key+1); $$varname = $val; } var_dump([$var1, $var2, $var3, $var4]); ``` The output obviously is: ``` array(4) { [0]=> int(25) [1]=> int(12) [2]=> int(3) [3]=> int(53) } ``` Upvotes: 2 <issue_comment>username_2: To do exactly as you asked: ``` $array = array(25, 'another', 'yet another', 'value'); foreach($array as $index => $value) { ${'variable' . ++$index} = $value; } echo $variable1; //shows 25 ``` Upvotes: 2 <issue_comment>username_3: you can use bracket `{ }` to create new variable from variable ``` foreach ($array as $i => $arr) { ${'variable'.$i+1} = $arr; } ``` Upvotes: 0 <issue_comment>username_4: Taking the elements of an array into variables only makes sense, if you have a specific number of elements, so you can work with that distinct set of variables in your code. In all other cases you should go on to work with arrays instead. Because of that, this answer assumes, that your array has a distinct set of elements. In that case you can use [`list()`](http://php.net/manual/en/function.list.php) to transform the elements into variables: ``` $array = [12, 25, 3, 53]; list($value1, $value2, $value3, $value4) = $array; echo $value1; // echoes 12 echo $value2; // echoes 25 echo $value3; // echoes 3 echo $value4; // echoes 53 ``` With PHP 7.1 and higher the following short code can be used aswell: ``` $array = [12, 25, 3, 53]; [$value1, $value2, $value3, $value4] = $array; echo $value1; // echoes 12 echo $value2; // echoes 25 echo $value3; // echoes 3 echo $value4; // echoes 53 ``` Upvotes: 0
2018/03/15
1,603
5,867
<issue_start>username_0: Consider the following simple (contrived) code example: ``` #include class Foo { std::size\_t size; char \*buf; public: Foo(std::size\_t s) { size = s; buf = new char[size]; for (int i = 0; i < size; i++) { buf[i] = 'a'; } } void hexprint() const { for (int i = 0; i < size; i++) { std::cout << buf[i]; } std::cout << std::endl; } char &operator[](std::size\_t pos) const { // TODO: check pos return buf[pos]; } void calcSomething(int param, char \*result) const { // calcuate something with param \*result = 'b'; } }; int main() { const Foo foo(3); char \*c = &foo[0]; char result; // do something with c foo.hexprint(); // output aaa foo.doSomething(56, c); // upps passed in c, instead of &result // still compiler was happy foo.hexprint(); // output baa // called only const functions but the const object // is still mutated } ``` The member function `calcSomething` of the class `Foo` calculates something and stores the result in what the pointer `result` points to. Now from compiler's perspective, this member function can be marked as `const`. But since it **modifies** what a pointer points to, there is a possibility that the object can be still be modified through the pointer (like shown in the example). Now my questions are: 1. Should I qualify `calcSomething` as `const` anyway even if it modifies content a pointer points to, just because the compiler allows it? 2. Is qualifying `calcSomething` as `const` more helpful to compiler's optimization process? 3. On the other hand, can qualifying `calcSomething` as `const` mislead the clients in thinking that it will *never ever* mutate object it is invoked on? Especially, *if it is not obvious* that there are pointers involved? 4. Is there any rules to follow when I can safely qualify a (member) function as `const`?<issue_comment>username_1: The rot has set in here since `i` is a `public` member. If it wasn't then you would not be able to pass `&a.i` at the calling site. You should qualify your functions as `const` if you don't *explicitly* modify the member data in the function body. Upvotes: 0 <issue_comment>username_2: You are not modifiying a member in the method, hence it should be `const`. Your example is just fine, as `a` is not `const`. You would get the proper error if you tried that: ``` const A a; a.calcSomething(56, &a.i); // yay stupid mistake isnt possible ``` Upvotes: 0 <issue_comment>username_3: Qualifying a member-function as `const` does not mean it doesn't have any side-effects, but that it doesn't modify its objects logical state, at least through the `this`-pointer. Just remember that the `const` applies to `*this`! Qualifying `*this` as `const` is unlikely to have *any* effect on the optimizer. Do it if it is logically correct. Sure there are some people who aren't clear on what parts are state of the object, or what the difference between logical `const` and physical `const` is, so some may be confused. Anyway, are you sure `i` should be part of the public interface? That seems to be putting the *leaky* in the *leaky abstraction*. Upvotes: 2 <issue_comment>username_4: > > Should I qualify calcSomething as const anyway even if it modifies content a pointer points to, just because the compiler allows it? > > > Yes. The object itself is not modified (via `this` pointer at least!), so it is fine. > > Is qualifying calcSomething as const more helpful to compiler's optimization process? > > > Just because `this` is const within the current function does not mean that at the same time a non-const function is called (e. g. in another thread). So there shouldn't be too many assumptions the compiler can make from, although I cannot exclude that there are some options without peeking into the standard... > > On the other hand, can qualifying calcSomething as const mislead the clients in thinking that it will never ever mutate object it is invoked on? Especially, if it is not obvious that there are pointers involved? > > > const is a contract, a promise: the function declared const won't change the object called on via the `this` pointer. `this` is implicitly const within the function; still you could cast it away and and modify it anyway, but you break the contract, the promise then! And: the object could have `mutable` members - these are allowed to be changed even if the object is const... Any further guarantees are not given by const (my thread example above, for instance), and no one should assume more than what is assured in the contract. Whoever does - own fault... > > Is there any rules to follow when I can safely qualify a (member) function as const? > > > Very simply: Make your function const unless you modify some non-mutable members... --- Referring to your example: ``` a.calcSomething(56, &a.i); ``` As long as `a` is not const, this is fine, even if `a` is indirectly modified this way. The function itself just follows a pointer, and it does not matter where it points to. If `a` was const, you would not be able to call this function, as `a.i` would then be const, too, and you would try to assign a pointer to const to a pointer to non-const... Side note: There are exceptions, but in most cases member variables represent some kind of internal state of the object and then it is not a good idea to have them public anyway... Upvotes: 1 <issue_comment>username_5: Yes! The argument: ``` int *result ``` Is a pointer to a external variable. So it can be modified. In a `const` method you can not modify the internal state of the class. ``` class A { public: int i{0}; int my_result; void calcSomething(int param, int *result) const { // calcuate something with param *result = 42; // Ok this->my_result = 42 ; /// ERROR: because the method is const. } }; ``` Upvotes: 0
2018/03/15
573
1,832
<issue_start>username_0: I am trying to add `html -` tag as prefix and suffix to each element of list of strings. Here is the list of string : ``` IList lstUniversities = new List(); lstUniversities.Add("1Harward University, USA"); lstUniversities.Add("2Yale University, USA"); lstUniversities.Select(u => "- " + u + " ").ToList(); ``` **Expected Output:** ``` - 1Harward University, USA - 2Yale University , USA ``` May I know why the `html -` tag is not appended ?<issue_comment>username_1: Because [`Select()`](https://msdn.microsoft.com/en-us/library/bb548891(v=vs.110).aspx) returns a new collection of type `IEnumerable`, it does not modify the existing one. so, you need to refer to that new one which `.Select(u => "- " + u + " ").ToList();` returns like: ``` lstUniversities = lstUniversities.Select(u => "- " + u + " ").ToList(); ``` Now we are assigning the new collection to out `lstUniversities` variable and we should see the expected output. Alternatively use a `foreach` or `for` loop to do that: ``` for(int i=o; i < lstUniversities.Count; i++) lstUniversities[i] = "- " + lstUniversities[i] + " "; ``` or with [ForEach()](https://msdn.microsoft.com/en-us/library/bwabdf9z%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396): ``` lstUniversities.ForEach(u => { u = "- " + u + " "; }); ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: May I suggest using a stringbuilder. Not expansive and results in very readable code, and leaves your input list clean. ``` var stringbuilder = new StringBuilder(); foreach (var item in lstUniversities) { stringbuilder.Append("- "); //stringbuilder.Add("1Harward University, USA"); stringbuilder.Append(item); stringbuilder.Append(" "); } ``` Upvotes: 0
2018/03/15
669
2,372
<issue_start>username_0: I need to have URI of the default ringtone. I can have the default ringtone using this code ``` Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); Ringtone rt = RingtoneManager.getRingtone(context,uri); ``` and in the rt (Ringtone), I can see the mUri like in the screenshot but it is not a public property, so I cannot have it. How can I have that property? Note: There is a getUri in the RingtoneManager.java but it is hidden. ``` /** {@hide} */ public Uri getUri() { return mUri; } ``` [![Screen Shot](https://i.stack.imgur.com/HPAYa.jpg)](https://i.stack.imgur.com/HPAYa.jpg)<issue_comment>username_1: ``` public void RingtonesList() { RingtoneManager manager = new RingtoneManager(this); manager.setType(RingtoneManager.TYPE_RINGTONE); Cursor cursor = manager.getCursor(); while (cursor.moveToNext()) { String title = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX); String uri = cursor.getString(RingtoneManager.URI_COLUMN_INDEX); // Do something with the title and the URI of ringtone Log.d("URI",""+uri); } } Also give permission ``` Upvotes: 1 <issue_comment>username_2: ``` Uri defaultRingtoneUri = RingtoneManager.getActualDefaultRingtoneUri(getActivity().getApplicationContext(), RingtoneManager.TYPE_RINGTONE); Ringtone defaultRingtone = RingtoneManager.getRingtone(getActivity(), defaultRingtoneUri); ``` Hope this works for you ! :) Upvotes: 2 <issue_comment>username_3: ``` String mimeType; if (outPath.endsWith(".m4a")) { mimeType = "audio/mp4a-latm"; } else if (outPath.endsWith(".wav")) { mimeType = "audio/wav"; } else { // This should never happen. mimeType = "audio/mpeg"; } ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.DATA, outPath); values.put(MediaStore.MediaColumns.TITLE, title.toString()); values.put(MediaStore.MediaColumns.SIZE, fileSize); values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType); Uri uri = MediaStore.Audio.Media.getContentUriForPath(outPath); final Uri newUri = getContentResolver().insert(uri, values); ``` I am using this to set a file as ringtone for my phone, similar to Toque123, Tonos123, Sonneries123, Belsoli123, Chakushinon123 Upvotes: 0
2018/03/15
380
1,481
<issue_start>username_0: Hello every one I am working with laravel and developing my first package and I need to add some css and javascript files with my package can any one answer me what is the right way to do this task.<issue_comment>username_1: You cannot directly add the assets from Your Laravel Package for that you have `publish()` assets first. In your Service Provider ``` /** * * @return void */ public function boot() { $this->publishes([ __DIR__.'/path/to/assets' => public_path('vendor/courier'), ], 'public'); } ``` Then use it in your views using `asset()` Hope this helps Upvotes: 2 <issue_comment>username_2: As @laravel levaral suggested you need to publish assets first afterwards in your root directory you will find public folder. Inside public you can make 'js' and 'css' folders in which you can store those files. In order to access your assets through out the whole laravel project you just need to call it from your blade file using asset() For js file:- `E.g:-` Likewise for css file:- `E.g:-` Upvotes: 2 [selected_answer]<issue_comment>username_3: Whenever I write Laravel packages, I strive to keep the JavaScript inline. When I can't do that, I will use the GitHub raw URL for the JavaScript/CSS asset and load that directly in the Laravel view. That way whenever anyone uses my Laravel packages and forgets or doesn't know about doing the `php artisan vendor:publish` command (~85%), it still just 'works'. Upvotes: 2
2018/03/15
994
3,650
<issue_start>username_0: In a project of mine, I try to display Angular Components (like an Autocomplete Dropdown Search) in a table. Because of the requirements I have (like multi-selecting different cells with `ctrl`+click) I decided to give it a go with handsontable. I've used the [handsontable renderer](https://docs.handsontable.com/pro/1.18.0/demo-custom-renderers.html) and [add the components dynamically](https://medium.com/front-end-hacking/dynamically-add-components-to-the-dom-with-angular-71b0cb535286). The code looks like this matrix.component.ts ```js this.hot = new Handsontable(this.handsontable.nativeElement, { data: this.tableData, colWidths: [80, 300], colHeaders: ['Id', 'Custom Component'], columns: [ { data: 'id', }, { data: 'id', renderer: (instance: any, td: any, row: any, col: any, prop: any, value: any, cellProperties: any) => { if (cellProperties.hasOwnProperty('ref')) { (cellProperties.ref as ComponentRef).instance.value = row; } else { cellProperties.ref = this.loadComponentAtDom( CellContainerComponent, td, ((component: any) => { component.template = this.button4Matrix; component.value = row; })); } return td; }, readOnly: true, }, ], }); private loadComponentAtDom(component: Type, dom: Element, onInit?: (component: T) => void): ComponentRef { let componentRef; try { const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component); componentRef = componentFactory.create(this.injector, [], dom); onInit ? onInit(componentRef.instance) : console.log('no init'); this.appRef.attachView(componentRef.hostView); } catch (e) { console.error('Unable to load component', component, 'at', dom); throw e; } return componentRef; } ``` What's my current issue is the lifecycle of the rendered angular components. Stuff I tried: 1. **Do nothing** *Tried Solution*: Doing nothing and leaving everything to Angular *Problem*: Angular never calling the ngOnDestroy of the CellContainer. 2. **Saving componentRefs** *Tried Solution*: Saving the componentRef in an Array and after a certain amount of rendering trying to destroy the components I rendered some time ago. Counting via time, handsontable hooks (verticalScroll/beforeRender/afterRender), in the render-method *Problem*: Destroy of the angular component always throws an error ('cannot read property'nativeNode' of null') or the components get displayed completely wrong 3. **Check during rendering if an element is there** *Tried Solution*: During the render: I checked if there's already a component and if it was I used to recycle the already-there component by adding a new value only. *Problem*: The values get completely mixed up during scrolling. A link to my solution (and an implemented solution #3) is available on [github](https://github.com/phhbr/handsontable-filled-with-ng-components). Does anyone have an idea of how to handle this in a clean way? If not the application gets slow & unusable after a little bit of scrolling & using the table. Better refer : <https://handsontable.com/docs/8.2.0/tutorial-cell-function.html><issue_comment>username_1: may be you need to try changeDetection as below, forcing the new changes to your component. ``` changeDetection: ChangeDetectionStrategy.OnPush ``` Upvotes: -1 <issue_comment>username_2: Using a cell renderer. Use the renderer name of your choice when configuring the column: ```js const container = document.getElementById('container'); const hot = new Handsontable(container, { data: someData, columns: [{ renderer: 'numeric' }] }); ``` Upvotes: 1
2018/03/15
575
2,361
<issue_start>username_0: After clicking on a link it opens up PDF in a new tab in chrome. The PDF can contains more than one page. The PDF is inside an tag . What I want to achieve is by using either javascript or jQuery to be able to scroll the PDF in developer's tool console of chrome browser. When I click right on page, I can't see the source code. I tried using ``` window.scrollBy(0,200) window.scrollTo(0,200) ``` but javascript doesn't seem to work. The source of the pdf is something like below ``` ``` Is there any other method or way through which I can achieve to scrolling through the PDF? Is there any command which I can enter in chrome's developer console which will scroll through PDF?<issue_comment>username_1: In short you can't - A PDF is not a DOM element it is a document that is rendered by a special PDF reader in the browser. Each browser has its own mechanism for rendering PDFs and there is no way to programmatically control them like you want. At best you can skip pages like using something like so (presuming your embed is the first on the page) ``` var x = document.getElementsByTagName('embed')[0] x.src = "url/to/your.pdf?page=page_number" ``` This will cause the embedded PDF to navigate to `page_number` Edit: You could (theoretically) achieve this if you could use an old browser that still has support for an NPAPI PDF plugin - then you could simulate arrow key presses that would allow you to scroll through the document. However in all modern browsers this isn't possible as you can't trigger keyevents without some kind of user interaction (for really good reasons!). Upvotes: 2 <issue_comment>username_2: While at the moment you cannot make a cross browser solution, because how pdfs are rendered is not part of a standard, chromium based browsers (chrome, edge, opera, etc.) wrap the pdf displaying plugin with elements that enable some interaction with it using the DOM. Around the embed tag you found chrome builds some divs using a web-component for the GUI including the scrollbar! And guess what happens when you scroll this container? ``` let scroller = document.getElementsByTagName('pdf-viewer')[0].shadowRoot.getElementById('scroller') scroller.scrollBy(0,200) ``` I suspect this is part of Chromes Initiative to explain browser behavior that was part of the web-component move Upvotes: 2
2018/03/15
543
1,934
<issue_start>username_0: I'm having trouble installing one of my python scripts. It has the following structure: ``` myproject setup.py src myproject otherfolders main.py __init__.py ``` And my `setup.py`creates an entry point like this: ``` from setuptools import setup, find_packages setup(name='mypackage', version='2.4.0', author='me', author_email='...', package_dir={'':'src'}, packages=find_packages('myproject'), install_requires=[ "networkx", "geopy", "pyyaml" ], zip_safe=False, entry_points={ 'console_scripts': [ 'myproject=myproject.main:main', ], }, ) ``` Now, after installing this successfully with `sudo python setup.py install`, I run `mypackage` and get an import error: `No module named mypackage.main`. I am aware that there are lots of similar questions and I tried most/all solutions suggested [here](https://stackoverflow.com/questions/338768/python-error-importerror-no-module-named), e.g., checking the `__init__.py` and setting `PYTHONPATH`, but the problem still exists. I'm running this on two different Ubuntu 16.04 machines. I'm pretty sure this worked before, but even when I go back to an earlier commit it doesn't work now. I noticed the installation works with `develop` but still fails with `install`. Does that make sense to anyone?<issue_comment>username_1: `packages=find_packages('mypackage')` -> `packages=find_packages('myproject')`. Also you should use `myproject.main`. Upvotes: 0 <issue_comment>username_2: The problem was in [`find_packages()`](https://setuptools.readthedocs.io/en/latest/setuptools.html#using-find-packages): > > Some projects use a src or lib directory as the root of their source tree, and those projects would of course use "src" or "lib" as the first argument to `find_packages()`. > > > Hence, I had to change `find_packages('myproject')` to `find_packages('src')`. Upvotes: 4 [selected_answer]
2018/03/15
2,269
8,176
<issue_start>username_0: My app using Altbeacon library for beacon scanning. my code working well to api level 24(android 7) but doesn't not working on oreo(8.0.0) at first, my gradle setting compileSdkVersion and targetSdkVersion is 26, i thought it was because of this. so, i reference this\*\*<https://developer.android.com/about/versions/oreo/background.html#services>\*\*, fix my gradle setting(compileSdkVersion 25, targetSdkVersion 25). and install this app on device (apilevel 24, 26) on 24 level device working well, but 26 is not. that's my code. In **Activity.onCreate** ``` Intent intent = new Intent(this, BeaconService.class); startService(intent); ``` in **BeaconService**(Altbeacon Library) ``` @Override public void onBeaconServiceConnect() { final Handler h = new Handler(getApplicationContext().getMainLooper()); Beacon[] tempBeacon = new Beacon[2]; bm.addRangeNotifier(new RangeNotifier() { @Override public void didRangeBeaconsInRegion(final Collection beacons, final Region region) { if (beacons.size() > 0) { //call method this context } Log.d("beacon", "detect"); } }); try { bm.startRangingBeaconsInRegion(new Region("test", Identifier.parse("A1200001-EABC-9876-D001-E00000000001"), Identifier.parse("32001"), null)); } catch (RemoteException e) { } } ``` EDIT: beacon is detected, but it takes a very long time. And i saw log below 03-15 18:25:02.639 2419-2419/app.eco.inulibrary D/ScanJobScheduler: Scheduling ScanJob (job:208352940/app.eco.inulibrary/org.altbeacon.beacon.service.ScanJob) to run every 310000 millis 03-15 18:25:02.917 2419-2419/app.eco.inulibrary D/ScanJobScheduler: Scheduling ScanJob (job:208352940/app.eco.inulibrary/org.altbeacon.beacon.service.ScanJob) to run every 300000 millis 03-15 18:36:00.176 2419-2419/app.eco.inulibrary I/ScanJob: Running periodic scan job: instance is org.altbeacon.beacon.service.ScanJob@a6ca148 03-15 18:36:01.751 2419-3951/app.eco.inulibrary D/RangeState: adding id1: a1200001-eabc-9876-d001-e00000000001 id2: 32001 id3: 2001 to existing range for: org.altbeacon.beacon.service.RangedBeacon@bf2cb74 03-15 18:36:01.968 2419-2419/app.eco.inulibrary D/Callback: attempting callback via local broadcast intent: org.altbeacon.beacon.range\_notification how to solve this problem?<issue_comment>username_1: Android O introduces new limits on Background services. Services like the `BeaconService` shown in the code will be killed by the operating system shortly after the app switches to background mode. The AndroidBeaconLibrary has been updated to account for this by using the Android job scheduler to handle beacon scanning on Android 8+. But for this to work, **you must use the `BeaconManager` or `RegionBootsrap` classes to start scanning**, rather than starting the `BeaconService` directly with an `Intent`. This way, the library will know to use the job scheduler on Android 8+ and the `BeaconService` on earlier versions. Further, you will need to move your code that starts scanning and initializes ranging out of an `Activity` and into a custom `android.app.Application` class. This is because Android 8 will kill your Activity along with the app when it is in the background, and you will need to have your ranging set up in an Android component that is created automatically when the app is re-launched in the background for periodic scanning. I recommend you rework your setup be as described in **Starting an App in the Background** in the sample code [here](http://altbeacon.github.io/android-beacon-library/samples.html). That sample only sets up monitoring, but you can start ranging in the `didDetermineStateForRegion` callback shown. Finally, make sure you have library version 2.13+ which has full support for changes in Android 8.1. To understand more about how background beacon detection has changed in Android 8, see my blog post [here.](http://www.username_1tech.com/2017/08/07/beacon-detection-with-android-8) Upvotes: 3 [selected_answer]<issue_comment>username_2: So I have been playing with this for a long time, trying to figure out the best way to scan for beacons in the background without annoying users with Foreground Service notifications. Here is what I have figured out so far: * ***Running in the Foreground***: Obviously we need to run scanning in the foreground to get anywhere. So I have used some snippets from @davidyoung and built a beacon scanner to run in a background service. I used to run beaconManager on the background settings, but Android 8 makes that difficult so I switched to running it in the foreground * ***Stupid Notification***: After switching to running the scanner in the foreground, I realized just how annoying that Foreground Service notification was. I tried to make a custom notification that at least looked cool, since my users would be stuck with it anyway, but it is still annoying. Then it dawned on me... **Run the scanner in the Foreground when the screen is off, then switch to background scanning when the screen is on!** --- ***Screen Driven Scanning***: After thinking about this for a while, I finally came to this conclusion after remembering that **Nearby** does a quick scan on 'ScreenOn' events. I thought about doing something similar, but figured it was better to just run a Foreground Service instead of hoping my scanning jobs got scheduled in time. The general structure included the following: * A *BroadcastReceiver class* and a *Service class* as found [here](https://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/). * 2 Notification calls * A PostDelayed Handler --- ***Results***: My service is started on the MainActivity, which starts my ScannerService. I have it set to run in the foreground onStartCommand from the MainActivity (when the user opens the app) and stay running until they lock their screen. Once the screen locks, the app enters a loop based on screen activity. When the user unlocks their phone (on Android 7-), the foreground notification clears immediately as the service switches to a background service. On Android 8, send a notification to the same ID used to start the foreground BeaconManager service, then cancel the notification on a handler after 2.5 seconds while switching to background settings. The notification prevents the user from getting the "Background Services are Using Battery" notification, but is short enough to disappear before they unlock the screen. Upvotes: 0 <issue_comment>username_3: The results of my tests: 1. Android Oreo (API >= 26) For Oreo i best solution call method *startScan()* with P*endingIntent (BroadcastReceiver)* . Small example: ``` ... val bluetoothManager = applicationContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager val bluetoothAdapter = bluetoothManager.adapter bleScanner = bluetoothAdapter.getBluetoothLeScanner() val listOfFiters = ArrayList() val builder = ScanFilter.Builder() val filter = builder.build() listOfFiters.add(filter) val startScan = bleScanner?.startScan(listOfFiters, null, getPendingIntent()) ... private fun getPendingIntent(): PendingIntent { return PendingIntent.getBroadcast( this, REQ\_CODE, Intent(this.applicationContext, BeaconBLEReceiver::class.java), PendingIntent.FLAG\_UPDATE\_CURRENT) } ``` Manifest: ``` ``` This implicit (is not on the [list of exceptions](https://developer.android.com/guide/components/broadcast-exceptions), but it works?) Broadcast works for at least several hours (Huawei Y6, Mate10). Restart can be solved by WorkManager. 2. Api <= 26 *startScan()* does not support PendingIntent - BroadcastReceiver can not be started. *startScan()* is only started once with callback. Here is probably the best solution [android-beacon-library](https://github.com/AltBeacon/android-beacon-library) or custom implementation background service with *startScan()*. 3. Only warnings. Android Nearby Notifications ends December 6th, 2018 ([google block](https://android-developers.googleblog.com/2018/10/discontinuing-support-for-android.html)) Upvotes: 0
2018/03/15
387
1,507
<issue_start>username_0: I found this error in my wordpress site Warning: require(/home/cjstech/public\_html/wp-admin/wp-blog-header.php): failed to open stream: No such file or directory in /home/cjstech/public\_html/wp-admin/index.php on line 17 I will gladly appreciate anyone who has some knowledge about how to fix this issue. Thanks!<issue_comment>username_1: You need to modify the index.php file as below to resolve this issue, only if you are running WordPress installation from the root directory. You just need to change the following lines: Require ('. /wp-blog-header.php'); To this: Require ('wp-blog-header.php'); Upvotes: 2 <issue_comment>username_2: I can see this error is in wp-admin flolder, Where normally developer din't make any changes. According to wordpress rule, avoid over writing the wp-admin and wp-include folder files. Because the changers in this folder (like: wp-admin, wp-includes) exist till the wordpress in not updated. **So, It means your application is not secure and any virus or hacking is effecting your application.** **Solution:** **Temporary:** Download any wordpress version in your local system or open any existing wordpress in you system and go to wp-admin/index.php file and copy the whole code and paste the code in your application at the same location( wp-admin/index.php). **Permanent:** Clean your code and file's in you hosting. **Note:** if you have multiple application running in your hosting then clean all the application Upvotes: 1
2018/03/15
320
938
<issue_start>username_0: I want to update multiple values with if else shorthand, like this: ``` let a = 0; let b = 1; let bool = true; if(bool) { a = 4; b = 7; } ``` with shorthand like this: ``` bool ? a = 8, b = 10 : null ``` but `Unexpected token ,`<issue_comment>username_1: You can wrap them in the `()`. It will evaluate expressions inside `()` and return the last one's result. ``` bool ? (a = 8, b = 10) : null ``` But if you consider `null` and `undefined` to be the same you can just use `&&` ``` bool && (a = 8, b = 10) ``` Upvotes: 1 <issue_comment>username_2: You could use a logical AND. ``` bool && (a = 8, b = 10); ``` [Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator) says: > > You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. > > > Upvotes: 3 [selected_answer]
2018/03/15
751
2,579
<issue_start>username_0: For my simple application where I chose to write my own solution for blog comments, I'm doing these 3 steps: **1. Taking data from basic HTML form inputs** via POST, then escaping the strings like this: ``` $komentar = htmlspecialchars($_POST['komentar'], ENT_QUOTES, 'UTF-8'); ``` **2. Using PDO** for db insertion: ``` $stmt = $conn->prepare("INSERT INTO komentare (id, jmeno, komentar, clanek) VALUES (DEFAULT, ?, ?, ?)"); $stmt->bind_param("sss", $jmeno, $komentar, $clanek); $stmt->execute(); $stmt->close(); $conn->close(); ``` **3. Listing the results back** using plain SELECT and loop-echoing like this: ``` $sql = "SELECT jmeno, komentar FROM komentare WHERE clanek = '$clanek' ORDER BY id DESC"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $zviratkoNum = rand(1,10); $vypis_jmeno = $row["jmeno"]; $vypis_komentar = $row["komentar"]; echo "". $vypis\_jmeno. "" . $row["komentar"] . ""; } } else { echo "##### Zatím zde nejsou žádné komentáře "; } $conn->close(); ``` --- I thought it's a bad practice because while I escape the input (hopefully properly), I'm retrieving data back not escaped. But to my surprise, it get's echo'ed into DOM as a text (screenshot from my real test comment): [![enter image description here](https://i.stack.imgur.com/Ck4JD.png)](https://i.stack.imgur.com/Ck4JD.png) 1. Why? 2. Is it bad practice? Thanks in advance, Adam<issue_comment>username_1: `htmlspecialchars` converts a string of text into a format suitable for inserting into an HTML document. A database is not an HTML document. Characters with special meaning in HTML (such as `&`) generally have no special meaning in a database. So you are: 1. Taking text and converting it to HTML source code 2. Taking HTML source code and putting it in a database 3. Taking HTML source code out of the database and converting it to HTML source code (so it is \*double) encoded and gives you the HTML that will display HTML source code) 4. Putting that into an HTML document --- When escaping data, do so just before you put it in the data format you are escaping it for. Don't convert to HTML before putting it into the database. Do that only before you put it into the HTML document. Upvotes: 3 [selected_answer]<issue_comment>username_2: It is meant to be this way. You escape the input properly so that the original value can be stored. Filtering the actual html input from 'bad code' like Upvotes: 0
2018/03/15
2,266
7,790
<issue_start>username_0: I'm new to Angular and Angular Material, now I'm working as a support in some project. There's a grid with filters and one checkbox, which checks if user in grid is active, inactive, or not chosen. It would be simpler with only two options (active, inactive) but well, I have to make 3 states for it: 1. 1st click - Checked for active 2. 2nd click - Unchecked for inactive 3. 3rd click - Indeterminate for not chosen Here is checkbox example from official Angular Material documentation: <https://stackblitz.com/angular/rxdmnbxmkgk?file=app%2Fcheckbox-configurable-example.html> How to make it in the most simply way?<issue_comment>username_1: One way to do this is to set MAT\_CHECKBOX\_CLICK\_ACTION to 'noop' and then you'll have to set the checked values with (click). Don't forget to bind both [ngModel] and [indeterminate]. ``` providers: [ {provide: MAT_CHECKBOX_CLICK_ACTION, useValue: 'noop'} ] ``` Have a look at this: <https://github.com/angular/material2/blob/master/src/lib/checkbox/checkbox.md> Upvotes: 0 <issue_comment>username_2: If you need a working example you can also clone the **material2** project [here](https://github.com/angular/material2), and then: ``` cd material2 npm i npm run demo-app ``` Open the demo app and navigate to the checkbox component. Upvotes: 0 <issue_comment>username_3: **@angular/material >= 9** Here is a ready-to-use component: ``` import { Component, forwardRef, Input } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { MatCheckboxDefaultOptions, MAT_CHECKBOX_DEFAULT_OPTIONS } from '@angular/material/checkbox'; @Component({ selector: 'app-tri-state-checkbox', templateUrl: './tri-state-checkbox.component.html', styleUrls: ['./tri-state-checkbox.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TriStateCheckboxComponent), multi: true, }, { provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: { clickAction: 'noop' } as MatCheckboxDefaultOptions }, ], }) export class TriStateCheckboxComponent implements ControlValueAccessor { @Input() tape = [null, true, false]; value: any; disabled: boolean; private onChange: (val: boolean) => void; private onTouched: () => void; writeValue(value: any) { this.value = value || this.tape[0]; } setDisabledState(disabled: boolean) { this.disabled = disabled; } next() { this.onChange(this.value = this.tape[(this.tape.indexOf(this.value) + 1) % this.tape.length]); this.onTouched(); } registerOnChange(fn: any) { this.onChange = fn; } registerOnTouched(fn: any) { this.onTouched = fn; } } ``` and template: ``` ``` Usage: ``` is done is done ``` You can also override default tape to e.g. enum values: ``` is done ``` where `customTape` replaces default values `[null, true, false]` ``` customTape = [Status.open, Status.complete, Status.cancelled]; ``` **@angular/material <= 8** Just change ``` { provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: { clickAction: 'noop' } as MatCheckboxDefaultOptions }, ``` to the deprecated since version 9 `MAT_CHECKBOX_CLICK_ACTION` ``` { provide: MAT_CHECKBOX_CLICK_ACTION, useValue: 'noop' }, ``` Upvotes: 6 [selected_answer]<issue_comment>username_4: I tried to reply this [Answer](https://stackoverflow.com/a/53081648/9817319) but I don't have enough reputation. First thank you for the answer and deep explanation. I was having trouble with the edition of the checkboxes and I figured out that if the value is false this line ```js this.value = value || this.tape[0]; ``` doesn't work and the color is not updated either. I changed it for this one ```js this.value = value !== null ? value : this.tape[0]; ``` I hope this comment help others. Upvotes: 2 <issue_comment>username_5: Thanks for this solution! Using Angular 9.1.7 here. I needed a custom set of values. This didn't work out of the box. Thanks to this ([post](https://stackoverflow.com/a/59619029/2075469)) for enlightening me on the solution to create 2-way binding I changed the parts as follows: Template: ``` ``` Typescript: ``` import {Component, EventEmitter, forwardRef, Input, Output} from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { MatCheckboxDefaultOptions, MAT_CHECKBOX_DEFAULT_OPTIONS } from '@angular/material/checkbox'; @Component({ selector: 'app-tri-state-checkbox', templateUrl: './tri-state-checkbox.component.html', styleUrls: ['./tri-state-checkbox.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TriStateCheckboxComponent), multi: true, }, { provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: { clickAction: 'noop' } as MatCheckboxDefaultOptions }, ], }) export class TriStateCheckboxComponent implements ControlValueAccessor { internalValue: any; guiValue: any; disabled: boolean; isIndeterminate: boolean; @Input() states = [null, true, false]; @Output() triStateValueChange = new EventEmitter(); @Input() get triStateValue(): any { return this.internalValue; } set triStateValue(v) { this.internalValue = v; this.writeValue(); } onChange = (x: any) => {console.log(`onChange:${x}`); }; onTouched = () => {}; writeValue() { if (this.internalValue === this.states[0]) { this.guiValue = true; } // undetermined else if (this.internalValue === this.states[1]) { this.guiValue = true; } // true else if (this.internalValue === this.states[2]) { this.guiValue = false; } // false else { console.error (`Wrong value for tri state checkbox : ${this.internalValue}`); } this.isIndeterminate = ( this.internalValue === this.states[0] ); } setDisabledState(disabled: boolean) { this.disabled = disabled; } next() { this.determineNextValue(); this.onTouched(); this.onChange(this.guiValue); } determineNextValue(){ if (this.internalValue === this.states[0]) {this.internalValue = this.states[1]; } else if (this.internalValue === this.states[1]) {this.internalValue = this.states[2]; } else if (this.internalValue === this.states[2]) {this.internalValue = this.states[0]; } this.triStateValueChange.emit(this.internalValue); } registerOnChange(fn: any) { this.onChange = fn; } registerOnTouched(fn: any) { this.onTouched = fn; } } ``` And the usage: Template: ``` Labeltext ``` And the setup of the source (TS) using the component: (the variable `targetVariable` is used as a source/target using 2-way binding. ``` export enum TriStateValues { on, off, dontcare }; let targetVariable = TriStateValues.on; const locTriState = [ TriStateValues.dontcare, TriStateValues.on , TriStateValues.off]; ``` Upvotes: 0 <issue_comment>username_6: > > @angular/material >= 9 > > > In my scenario , it works. `color: 'primary'` must be provide. ``` providers: [{ provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: { clickAction: 'noop', color: 'primary' } as MatCheckboxDefaultOptions }] ``` Upvotes: 0 <issue_comment>username_7: I wanted a solution for this without requiring another component and in a reactive form and this does seem to do the trick, although there is a duplicated animation in one transition: `component.ts` ```js onChangeCheckbox(checkbox: MatCheckbox): void { if (checkbox.indeterminate){ checkbox.indeterminate = false; checkbox.checked = true; } // by the time you click it is changed else if (!checkbox.indeterminate && !checkbox.checked ){ checkbox.checked = false; }else if (!checkbox.indeterminate && checkbox.checked ){ checkbox.indeterminate = true; } } ``` `component.html` ```html Checkbox Name ``` Upvotes: 2
2018/03/15
2,317
8,095
<issue_start>username_0: I am developing a mail editor based in TinyMCE, in which the user should be able to insert "snippets"/"templates"/"placeholders" which should be treated as units, not text. For instance, when creating the email to participants for an event, one "template" should be **[EventName]** or **[ParticipantName]**. The user can choose where that "template" should be placed in the mail, and when sending, it will be replaced with the actual name of the event and participant. I'm thinking about it as a sort of html element that gets inserted in the text, so it behaves just like a single character when deleting - the whole element gets deleted, not just a piece of it. Example: *Hello **[ParticipantName]**! Welcome to **[EventName]**, we hope you will enjoy it.* This should NOT be able to happen when editing (part of "template" deleted): *Hello **[ParticipantN** ! Welcome to **[EventName**], we hope you will enjoy it.*<issue_comment>username_1: One way to do this is to set MAT\_CHECKBOX\_CLICK\_ACTION to 'noop' and then you'll have to set the checked values with (click). Don't forget to bind both [ngModel] and [indeterminate]. ``` providers: [ {provide: MAT_CHECKBOX_CLICK_ACTION, useValue: 'noop'} ] ``` Have a look at this: <https://github.com/angular/material2/blob/master/src/lib/checkbox/checkbox.md> Upvotes: 0 <issue_comment>username_2: If you need a working example you can also clone the **material2** project [here](https://github.com/angular/material2), and then: ``` cd material2 npm i npm run demo-app ``` Open the demo app and navigate to the checkbox component. Upvotes: 0 <issue_comment>username_3: **@angular/material >= 9** Here is a ready-to-use component: ``` import { Component, forwardRef, Input } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { MatCheckboxDefaultOptions, MAT_CHECKBOX_DEFAULT_OPTIONS } from '@angular/material/checkbox'; @Component({ selector: 'app-tri-state-checkbox', templateUrl: './tri-state-checkbox.component.html', styleUrls: ['./tri-state-checkbox.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TriStateCheckboxComponent), multi: true, }, { provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: { clickAction: 'noop' } as MatCheckboxDefaultOptions }, ], }) export class TriStateCheckboxComponent implements ControlValueAccessor { @Input() tape = [null, true, false]; value: any; disabled: boolean; private onChange: (val: boolean) => void; private onTouched: () => void; writeValue(value: any) { this.value = value || this.tape[0]; } setDisabledState(disabled: boolean) { this.disabled = disabled; } next() { this.onChange(this.value = this.tape[(this.tape.indexOf(this.value) + 1) % this.tape.length]); this.onTouched(); } registerOnChange(fn: any) { this.onChange = fn; } registerOnTouched(fn: any) { this.onTouched = fn; } } ``` and template: ``` ``` Usage: ``` is done is done ``` You can also override default tape to e.g. enum values: ``` is done ``` where `customTape` replaces default values `[null, true, false]` ``` customTape = [Status.open, Status.complete, Status.cancelled]; ``` **@angular/material <= 8** Just change ``` { provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: { clickAction: 'noop' } as MatCheckboxDefaultOptions }, ``` to the deprecated since version 9 `MAT_CHECKBOX_CLICK_ACTION` ``` { provide: MAT_CHECKBOX_CLICK_ACTION, useValue: 'noop' }, ``` Upvotes: 6 [selected_answer]<issue_comment>username_4: I tried to reply this [Answer](https://stackoverflow.com/a/53081648/9817319) but I don't have enough reputation. First thank you for the answer and deep explanation. I was having trouble with the edition of the checkboxes and I figured out that if the value is false this line ```js this.value = value || this.tape[0]; ``` doesn't work and the color is not updated either. I changed it for this one ```js this.value = value !== null ? value : this.tape[0]; ``` I hope this comment help others. Upvotes: 2 <issue_comment>username_5: Thanks for this solution! Using Angular 9.1.7 here. I needed a custom set of values. This didn't work out of the box. Thanks to this ([post](https://stackoverflow.com/a/59619029/2075469)) for enlightening me on the solution to create 2-way binding I changed the parts as follows: Template: ``` ``` Typescript: ``` import {Component, EventEmitter, forwardRef, Input, Output} from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { MatCheckboxDefaultOptions, MAT_CHECKBOX_DEFAULT_OPTIONS } from '@angular/material/checkbox'; @Component({ selector: 'app-tri-state-checkbox', templateUrl: './tri-state-checkbox.component.html', styleUrls: ['./tri-state-checkbox.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TriStateCheckboxComponent), multi: true, }, { provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: { clickAction: 'noop' } as MatCheckboxDefaultOptions }, ], }) export class TriStateCheckboxComponent implements ControlValueAccessor { internalValue: any; guiValue: any; disabled: boolean; isIndeterminate: boolean; @Input() states = [null, true, false]; @Output() triStateValueChange = new EventEmitter(); @Input() get triStateValue(): any { return this.internalValue; } set triStateValue(v) { this.internalValue = v; this.writeValue(); } onChange = (x: any) => {console.log(`onChange:${x}`); }; onTouched = () => {}; writeValue() { if (this.internalValue === this.states[0]) { this.guiValue = true; } // undetermined else if (this.internalValue === this.states[1]) { this.guiValue = true; } // true else if (this.internalValue === this.states[2]) { this.guiValue = false; } // false else { console.error (`Wrong value for tri state checkbox : ${this.internalValue}`); } this.isIndeterminate = ( this.internalValue === this.states[0] ); } setDisabledState(disabled: boolean) { this.disabled = disabled; } next() { this.determineNextValue(); this.onTouched(); this.onChange(this.guiValue); } determineNextValue(){ if (this.internalValue === this.states[0]) {this.internalValue = this.states[1]; } else if (this.internalValue === this.states[1]) {this.internalValue = this.states[2]; } else if (this.internalValue === this.states[2]) {this.internalValue = this.states[0]; } this.triStateValueChange.emit(this.internalValue); } registerOnChange(fn: any) { this.onChange = fn; } registerOnTouched(fn: any) { this.onTouched = fn; } } ``` And the usage: Template: ``` Labeltext ``` And the setup of the source (TS) using the component: (the variable `targetVariable` is used as a source/target using 2-way binding. ``` export enum TriStateValues { on, off, dontcare }; let targetVariable = TriStateValues.on; const locTriState = [ TriStateValues.dontcare, TriStateValues.on , TriStateValues.off]; ``` Upvotes: 0 <issue_comment>username_6: > > @angular/material >= 9 > > > In my scenario , it works. `color: 'primary'` must be provide. ``` providers: [{ provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: { clickAction: 'noop', color: 'primary' } as MatCheckboxDefaultOptions }] ``` Upvotes: 0 <issue_comment>username_7: I wanted a solution for this without requiring another component and in a reactive form and this does seem to do the trick, although there is a duplicated animation in one transition: `component.ts` ```js onChangeCheckbox(checkbox: MatCheckbox): void { if (checkbox.indeterminate){ checkbox.indeterminate = false; checkbox.checked = true; } // by the time you click it is changed else if (!checkbox.indeterminate && !checkbox.checked ){ checkbox.checked = false; }else if (!checkbox.indeterminate && checkbox.checked ){ checkbox.indeterminate = true; } } ``` `component.html` ```html Checkbox Name ``` Upvotes: 2
2018/03/15
400
1,278
<issue_start>username_0: I noticed that console.info() no longer shows an (i) icon to the left of the line. There is no difference between console.info() and console.log(). On 49.0.2623.112 (on XP) it looks like this: [![Output from console.info()](https://i.stack.imgur.com/acrcf.png)](https://i.stack.imgur.com/acrcf.png) My current version is 64.0.3282.140 but I think the icon has been gone for a while. Is there some setting to get the icon back?<issue_comment>username_1: As already specified by Josh Lee, it sadly got removed. I tried replicating the behavior. Take a look at it: <https://github.com/evertdespiegeleer/console.info> Upvotes: 2 <issue_comment>username_2: Josh Lee's link suggest the following workaround: ``` console.log("%ci%c Hello", "color: white; background: blue;", ""); ``` Elaborating on that, one can have ``` function logInfo(text, bgColor, color) { console.log(`%c${text}`, `color: ${color}; background: ${bgColor};`); } logInfo('test 1', 'orange', 'black'); logInfo('test 2', 'white', 'green'); logInfo('test 3', 'green', 'white'); ``` This actually gives us more flexibility - and one can customize his own special output types. In a short: would chrome not have removed the feature, I would not learn about this :) Upvotes: 2
2018/03/15
1,040
2,840
<issue_start>username_0: From GeeksforGeeks I found this defination : > > Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. > > > Example: > > > > ``` > > First Pass: > ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. > ( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4 > ( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2 > ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them. > > Second Pass: > ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ) > ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2 > ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) > ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) > > ``` > > Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted. > > > What if I do this in reverse order like from n-1 to 0? Is it right because I am putting my array's smallest bubble into the first position on the first pass. I have written my code like this: ``` for (int i = 0; i < array.length; i++) { for (int j = array.length - 1; j > 0; j--) { if (array[j - 1] > array[j]) { int temp = array[j - 1]; array[j - 1] = array[j]; array[j] = temp; } } } ```<issue_comment>username_1: Yes, your code will work. But in order to increase the efficiency of your program in terms of speed, you should change the condition in the second `for` loop. As you have written ``` for (int j = array.length - 1; j > 0; j--) { ... } ``` Here, in the Second Pass, when the value of `j` is 1 then, it will unnecessarily check this condition ``` array[j - 1] > array[j] ``` Because, After the first pass, `array[0]` is already the smallest. So, you don't need to check that again. And in the third pass, there will be two unnecessary conditions and so on and so on. Therefore, I recommend you to use `j > i` as the condition of second `for` Loop. Then your whole line will be ``` for (int j = array.length - 1; j > i; j--) { ... } ``` Upvotes: 2 <issue_comment>username_2: The idea is finally to sort the list. Below is the Python code for filling the lowest number first and then going to the highest number ``` def selection_sort(input_list): for init in range(0,len(input_list)): pos_of_min=init for nxt in range(pos_of_min+1,len(input_list)): if input_list[pos_of_min]>input_list[nxt]: pos_of_min=nxt input_list[init]=input_list[pos_of_min] input_list[pos_of_min]=input_list[init] return input_list arr_unsorted=[25,67,23,21,90,89,45,63] sorted_result=selection_sort(arr_unsorted) print(sorted_result) ``` Upvotes: 1
2018/03/15
675
2,249
<issue_start>username_0: Say, if I want to change the color of an ng-repeat element when a certain condition is satisfied. I tried using element.css, but that changes the color of all the elements in ng-repeat. ``` ### {{ day }} ``` Here is my controller and directive : ``` var app = angular.module('exampleApp', []); // Controller app.controller('dayController', function($scope){ $scope.days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] $scope.today = $scope.days[new Date().getDay()]; $scope.tomorrow = $scope.days[(new Date().getDay() + 1) % 7]; }); // Directive app.directive("highlight", function () { return function (scope, element, attrs) { if (scope.today == attrs["highlight"]) { // Change the color of that day } } }); ```<issue_comment>username_1: You don't need a directive to achieve such simple stuff. Just use `ng-class` and you will be fine: ### View ``` ### {{ day }} ``` ### CSS ``` .highlight-today { background-color: red; } ``` ### AngularJS application ``` var myApp = angular.module('myApp', []); myApp.controller('MyCtrl', function($scope) { $scope.days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] $scope.today = $scope.days[new Date().getDay()]; $scope.tomorrow = $scope.days[(new Date().getDay() + 1) % 7]; }); ``` **> [demo fiddle](http://jsfiddle.net/5c8h4bz6/)** Upvotes: 3 [selected_answer]<issue_comment>username_2: Just add `element.css('background-color', 'yellow');` inside the if condition. here is the working code: ```html (function() { var app = angular.module('exampleApp', []); // Controller app.controller('dayController', function($scope) { $scope.days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] $scope.today = $scope.days[new Date().getDay()]; $scope.tomorrow = $scope.days[(new Date().getDay() + 1) % 7]; }); // Directive app.directive("highlight", function() { return function(scope, element, attrs) { if (scope.today == attrs["highlight"]) { // Change the color of that day element.css('background-color', 'yellow'); } } }); }()); ### {{ day }} ``` Upvotes: 1
2018/03/15
912
2,949
<issue_start>username_0: I am trying to use u-net with keras implementation, I am using the following repo <https://github.com/zhixuhao/unet> it works well, but my problem is a two-class segmentation problem, so I want to set the accuracy metric to jaccard, and also the loss function I tried to define the function: ``` def Jac(y_true, y_pred): y_pred_f = K.flatten(K.round(y_pred)) y_true_f = K.flatten(y_true) num = K.sum(y_true_f * y_pred_f) den = K.sum(y_true_f) + K.sum(y_pred_f) - num return num / den ``` and call it in the compilation: ``` model.compile(optimizer = Adam(lr = 1e-4), loss = ['binary_crossentropy'], metrics = [Jac]) ``` When I do that the jaccard accuracy in every iteration decreases till it reach ZERO !! Any explanation of why that happen ?? P.S: The same thing happens with the Dice. P.S: The output layer is conv 1 \* 1 with sigmoid activation function Update: ======= Attached the original implementation in keras of the binary accuracy: ``` def binary_accuracy(y_true, y_pred): return K.mean(K.equal(y_true, K.round(y_pred)), axis=-1) ``` And I can see that it also uses rounding to get the output prediction.<issue_comment>username_1: Try these functions bellow, copied from [github](https://github.com/ZFTurbo/ZF_UNET_224_Pretrained_Model/blob/master/zf_unet_224_model.py). Use jacard\_coef in keras metrics and if you want jacard\_coef\_loss keras loss ``` def jacard_coef(y_true, y_pred): y_true_f = K.flatten(y_true) y_pred_f = K.flatten(y_pred) intersection = K.sum(y_true_f * y_pred_f) return (intersection + 1.0) / (K.sum(y_true_f) + K.sum(y_pred_f) - intersection + 1.0) def jacard_coef_loss(y_true, y_pred): return -jacard_coef(y_true, y_pred) model.compile(optimizer = Adam(lr = 1e-4), loss = [jacard_coef_loss], metrics = [jacard_coef]) ``` Upvotes: 0 <issue_comment>username_2: You're rounding your function (`K.round`). That causes two problems: * (real problem) The function is not differentiable and will not be capable of being a loss function (A "None values not supported" error will be shown) * Whenever your network is unsure and has any values below 0.5, those values will be considered zero. If the amount of black (zero) pixels in `y_true` is greater than the white (1) ones, this will happen: * your network will tend to predict everything to zero first, and this will indeed result in a better binary crossentropy loss! + And also a better Jaccard if not rounded + But a zero Jaccard if rounded * and only later, when the learning rates are more finely adjusted, it will start bringing out the white pixels where they should be. You should really be using a non-rounded function for both reasons above. And plot your outputs sometimes to see what is going on :) Notice that if you're using this as a loss function, multiply it by -1 (because you will want it to decrease, not increase) Upvotes: 3 [selected_answer]
2018/03/15
1,588
5,266
<issue_start>username_0: I try to make a level indicator which beeps quicker when the phone reach an horizontal position (using the accelerometer), the beep sound plays after a touch on the screen and stop if screen is touched again. So I made the following code, and the problem I have is that since I've add the "beep" sound part (with MyRunnable function called in the onTouch event), my app crashes after few seconds (it works fine for few second and I have no error messages after the build). I really have no clue on what the problem could be. I'm stuck here and need some help, thanks ! public class MainActivity extends AppCompatActivity implements SensorEventListener, View.OnTouchListener { ``` Sensor mySensor; SensorManager SM; float ANGLEX, ANGLEY, ANGLEZ; int aX, aY, aZ; int roundANGLEX, roundANGLEY, roundANGLEZ; int Xetal, Yetal; double centre; int Rcentre; int Rcentre2; boolean active; int test; int i=0; private Handler myHandler; private Runnable myRunnable = new Runnable() { @Override public void run() { // Play a periodic beep which accelerates according to Rcentre2 ToneGenerator toneGen1 = new ToneGenerator(AudioManager.STREAM_MUSIC, 100); toneGen1.startTone(ToneGenerator.TONE_PROP_BEEP,150); myHandler.postDelayed(this,(long) Math.sqrt(Rcentre2*20)+50); } }; @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Créée notre Sensor Manager SM = (SensorManager) getSystemService(SENSOR_SERVICE); //Accéléromètre mySensor = SM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); //Registre Sensor Listener SM.registerListener(this, mySensor, 1000000, 1000000); ((ConstraintLayout) findViewById(R.id.layout_main)).setOnTouchListener((View.OnTouchListener) this); } @Override public void onAccuracyChanged(Sensor sensor, int i) { //Pas utilisé } @Override public void onSensorChanged(SensorEvent sensorEvent) { float z_stable = ((int) ((sensorEvent.values[2]) * 100)) / 100.0f; ANGLEX = (float) (((float) (Math.acos(sensorEvent.values[0] / 9.807)) * (180 / Math.PI))); //I get the accelerometer's values ANGLEY = (float) (((float) (Math.acos(sensorEvent.values[1] / 9.807)) * (180 / Math.PI))); ANGLEZ = (float) (((float) (Math.acos(z_stable / 9.807)) * (180 / Math.PI))); roundANGLEX = Math.round(ANGLEX); roundANGLEY = Math.round(ANGLEY); roundANGLEZ = Math.round(ANGLEZ); aX = roundANGLEX; aY = roundANGLEY; aZ = roundANGLEZ; Xetal = aX - 88; //Xetal and Yetal are 0 when phone is on plane surface Yetal = aY - 90; //and go from -90 to +90 centre = Math.sqrt(Xetal * Xetal + Yetal * Yetal); //gives the "distance" from the "center => the smaller centre gets, the closer the phone approach horizontal Rcentre = (int) Math.round(centre); Rcentre2 = (int) Math.round(centre * 100); } public boolean onTouch(View view, MotionEvent motionEvent) { if (active == true) { active = false; myHandler.removeCallbacks(myRunnable); } else if (active == false) { active = true; myHandler = new Handler(); myHandler.postDelayed(myRunnable,0); } return false; } ``` } Here are the Logcat infos, it seems to shows some problems but I don't know what that means. [logcat information](https://i.stack.imgur.com/cLuty.png)<issue_comment>username_1: Try these functions bellow, copied from [github](https://github.com/ZFTurbo/ZF_UNET_224_Pretrained_Model/blob/master/zf_unet_224_model.py). Use jacard\_coef in keras metrics and if you want jacard\_coef\_loss keras loss ``` def jacard_coef(y_true, y_pred): y_true_f = K.flatten(y_true) y_pred_f = K.flatten(y_pred) intersection = K.sum(y_true_f * y_pred_f) return (intersection + 1.0) / (K.sum(y_true_f) + K.sum(y_pred_f) - intersection + 1.0) def jacard_coef_loss(y_true, y_pred): return -jacard_coef(y_true, y_pred) model.compile(optimizer = Adam(lr = 1e-4), loss = [jacard_coef_loss], metrics = [jacard_coef]) ``` Upvotes: 0 <issue_comment>username_2: You're rounding your function (`K.round`). That causes two problems: * (real problem) The function is not differentiable and will not be capable of being a loss function (A "None values not supported" error will be shown) * Whenever your network is unsure and has any values below 0.5, those values will be considered zero. If the amount of black (zero) pixels in `y_true` is greater than the white (1) ones, this will happen: * your network will tend to predict everything to zero first, and this will indeed result in a better binary crossentropy loss! + And also a better Jaccard if not rounded + But a zero Jaccard if rounded * and only later, when the learning rates are more finely adjusted, it will start bringing out the white pixels where they should be. You should really be using a non-rounded function for both reasons above. And plot your outputs sometimes to see what is going on :) Notice that if you're using this as a loss function, multiply it by -1 (because you will want it to decrease, not increase) Upvotes: 3 [selected_answer]
2018/03/15
458
1,728
<issue_start>username_0: Jenkins SECURITY-248 states that I should "Disable the visualization of Injected Environment variables in the global configuration." I cannot find this setting in the Configuration. Any help will be appreciated.<issue_comment>username_1: Configure Global Security {buildhost}/configureSecurity/ at the bottom is "Do not show injected variables" Upvotes: 2 <issue_comment>username_2: You can do the following to make sure to address this security issue correctly: 1. Check to see if you have any files affected by this security issue by executing this command: `sudo find . -name "injectedEnvVars.txt"` 2. Delete all the files recursively by executing the following command: `sudo find . -name "injectedEnvVars.txt" -delete` 3. Re-execute step #1 to make sure there are no files left. 4. Go to the Jenkins instance, from `Configure Global Security` under `Environment Injector Plugin` check `Do not show injected variables`. [![Prevent the plugin from leaking secrets again](https://i.stack.imgur.com/JojYK.png)](https://i.stack.imgur.com/JojYK.png) 5. From `Configure Global Security` under `Hidden security warnings`, click on `Security Warnings` and then uncheck `Environment Injector Plugin: Exposure of sensitive build variables stored by EnvInject 1.90 and earlier`. This will make sure to hide that error message so it doesn’t appear again. [![Prevent the warning message from showing #1](https://i.stack.imgur.com/yN8MQ.png)](https://i.stack.imgur.com/yN8MQ.png) [![Prevent the warning message from showing #2](https://i.stack.imgur.com/nYlh5.png)](https://i.stack.imgur.com/nYlh5.png) **Reference:** <https://jenkins.io/security/advisory/2018-02-26/#SECURITY-248> Upvotes: 6 [selected_answer]
2018/03/15
1,390
4,954
<issue_start>username_0: I am new to React. I am building a component in Visual Studio 2017 where a user enters some text and, according to that, values are fetched from a database and shown in a `div`. Below is the class and interfaces I am using. ``` interface ISearchForm { suggestionList: ISuggestionList[]; searchText: string; } interface ISuggestionList { queryDetails: IQueryDetails; data: IDataForUsers[]; } interface IQueryDetails { search: string; returncount: number; skip: number; top: number; } interface IDataForUsers { users: IUsers[]; } interface IUsers { profileId: string; firstName: string; middleName: string; lastName: string; } ``` The reason I have such a complex structure, is beacuse the API returns a complex JSON, like below: ``` "querydetails": { "search": "sample string 1", "returncount": 2, "skip": 3, "top": 4 }, "data": { "users": [{ "profileId": "sample string 1", "firstName": "sample string 2", //I want to retrieve array of this key for every user "middleName": "sample string 3", "lastName": "sample string 4", }, { "profileId": "sample string 1", "firstName": "sample string 2", "middleName": "sample string 3", "lastName": "sample string 4", }] } ``` Below is my class. Now this whole code is in typescript: ``` import * as React from 'react'; import { RouteComponentProps } from 'react-router'; export class Search extends React.Component, ISearchForm> { constructor() { super(); this.state = { suggestionList: [], searchText: '' }; this.handleSerachTextChange = this.handleSerachTextChange.bind(this); }//Some more code after this } ``` On text change event, I make an API call and assign the response to `suggestionList[]` ``` handleSerachTextChange(e: any) { this.setState({ searchText: e.target.value }); this.setState({ suggestionList: [] }); if (e.target.value == '') {} else { var propsForAPI = { search: e.target.value, skip: 0, top: 10 }; var jsonData = JSON.stringify(propsForAPI); fetch('apiURL', { method: 'POST', headers: { 'Content-type': 'application/json' }, body: jsonData }) .then(response => response.json() as Promise) .then(data => { this.setState({ suggestionList: data }); }); } } ``` This is what my render method looks like. It gives me an error on runtime, when I try to use `this.state.suggestionList.map()`. The reason I created my inner `div` is because of [this video](https://www.youtube.com/watch?v=yh1DOKh4jas). ``` public render() { return { this.state.suggestionList.map((dataArray) => { { dataArray.data.map((usersList) => { { usersList.users.map((userArray) => { { userArray.firstName } }) } }) } }) } } ``` Can somebody tell me why I am getting this error? Or how I can retrieve a list of `firstName`s for all of the users? I don't want to change the response that I am getting from my API call. Any help would be appreciated.<issue_comment>username_1: Look at this: ``` .then(response => response.json() as Promise) .then(data => { this.setState({ suggestionList: data }); }); ``` the `this.state.suggestionList` initially is an array, but that chunk of code set it as somewhat not an array. Replace `this.setState({ suggestionList: data });` by `this.setState({ suggestionList: data.users });` Upvotes: 0 <issue_comment>username_2: If your `suggestionList` equals the data you receive, `data` is not an array but an object, you can't iterate on it. So, in my opinion you can just iterate on your users list like this: Try updating your initial state with ``` this.state = { suggestionList: { data: null }, searchText: '' }; ``` then update your render like ``` { this.state.suggestionList.data ? this.state.suggestionList.data.users.map(user => {user.firstName}) : null } ``` Upvotes: 0 <issue_comment>username_3: In your code, you are expecting your JSON result to be of type `ISuggestionList[]`. But that does not match *at all*. You need to fix your types before attempting anything else. * The JSON result is of type `ISuggestionList`, not an array of that type * Similarly `data` inside `ISuggestionList` is also not an array but an object that has a `users` property. So it’s `IDataForUsers` (again no array). * Since your JSON is only a single `ISuggestionList`, `ISearchForm` also shouldn’t have multiple `ISuggestionList` elements. Once you have fixed that, you should get compiler errors that should guide you towards the right usage of your objects. Then you will also realize that you cannot use `map` on `state.suggestionList` because it’s not an array. Also, you should really adjust the naming of your types. You should use singular names for things that represent a single thing, and not call something `List` when that isn’t an actual list of things. Upvotes: 3 [selected_answer]
2018/03/15
635
2,245
<issue_start>username_0: This tutorial of Google Kubernetes Engine seems not to work. > > <https://cloud.google.com/kubernetes-engine/docs/tutorials/hello-app> > > > ``` $ gcloud beta container clusters create hello-cluster --num-nodes=3 WARNING: You invoked `gcloud beta`, but with current configuration Kubernetes Engine v1 API will be used instead of v1beta1 API. `gcloud beta` will switch to use Kubernetes Engine v1beta1 API by default by the end of March 2018. If you want to keep using `gcloud beta` to talk to v1 API temporarily, please set `container/use_v1_api` property to true. But we will drop the support for this property at the beginning of May 2018, please migrate if necessary. ERROR: (gcloud.beta.container.clusters.create) ResponseError: code=400, message=v1 API cannot be used to access GKE regional clusters. See http:/goo.gl/Vykvt2 for more information. ``` It seems this command request `GKE regional clusters` but I have no idea how to stop it.<issue_comment>username_1: It worked well by adding `--zone=` option. ``` gcloud container clusters create hello-cluster --num-nodes=3 --zone=asia-northeast1-a ``` You can find a proper zone name with the following command; ``` gcloud compute zones list ``` `NAME` and `REGION` are slightly different. Please remind to use `NAME` to the `--zone=` option. You can find it in this `Available regions & zones` document also. > > <https://cloud.google.com/compute/docs/regions-zones/#available> > > > Hope it helps. Upvotes: 3 <issue_comment>username_2: Ensure you specify the "project ID" not the "project name" ``` $ gcloud beta container clusters create hello-cluster --project=project-id --zone=europe-west1-a ``` Upvotes: 0 <issue_comment>username_3: checkout the role of your service account. Upvotes: -1 <issue_comment>username_4: Try enabling Google Kubernetes Engine API. More : <https://cloud.google.com/kubernetes-engine/docs/how-to/creating-a-cluster> Upvotes: 0 <issue_comment>username_5: You need to set your zone, region and also enable the Kubernetes API [here](https://cloud.google.com/kubernetes-engine/docs/how-to/creating-a-cluster) for your current project before you can use the `gcloud container clusters create` command. Upvotes: 0
2018/03/15
1,236
4,012
<issue_start>username_0: We have a Node.js lib, recently we added a type definitions for it. But how could I test the type definition?<issue_comment>username_1: The tests in [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) are files that are supposed to type-check correctly. So the test exercises different parts of the API, and it's run through the compiler (but the generated JavaScript code is not actually executed). See, for example, tests for [@types/express](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/express/express-tests.ts). For your own project, I guess you'd write a similar test file yourself, and compile it as part of your build (if it compiles, then the test succeeds). Of course, if you already have existing TypeScript code using those type definitions, that might be sufficient test. [Typings-checker](https://www.npmjs.com/package/typings-checker) is a proof-of-concept that also allows testing failures (incorrectly typed code should not compile). Upvotes: 3 <issue_comment>username_2: I wrote a lib for this purpose, check it out: <https://github.com/qurhub/qur-typetest> The typescript compiler only checks that types are correct, but it is not capable of checking whether your type fails when you expect it to fail. So, in the mentioned library you write tests like this: ``` const str: string = "foo" ``` in order to ensure type `string` compiles when assigned to value `"foo"`. And you write tests like this: ``` // tt:throws:Type '1' is not assignable to type 'string'. const str: string = 1 ``` in order to ensure type `string` fails to compile when assigned to value `1`. Of course, instead of `string` you should test your actual complex types, like, for example, mapped types. Upvotes: 2 <issue_comment>username_3: Microsoft's [`dtslint`](https://github.com/Microsoft/dtslint) is a handy tool for testing type declarations. As the name suggests its a static analysis tool that doesn't run your test files but only type-checks them. You can additionally supplement tests with comment-based assertions that the tool evaluates: ```js import { f } from "my-lib"; // f is(n: number) => void // $ExpectType void f(1); // Can also write the assertion on the same line. f(2); // $ExpectType void // $ExpectError f("one"); ``` [`tsd`](https://github.com/SamVerschueren/tsd) is another tool with similar assertions: ```js import {expectType} from 'tsd'; import concat from '.'; expectType(concat('foo', 'bar')); expectType(concat(1, 2)); ``` Also as of Typescript 3.9 you can use the built-in `// @ts-expect-error` comment: > > When a line is prefixed with a // @ts-expect-error comment, TypeScript will suppress that error from being reported; but if there’s no error, TypeScript will report that // @ts-expect-error wasn’t necessary. ([source](https://devblogs.microsoft.com/typescript/announcing-typescript-3-9/#ts-expect-error-comments)) > > > Upvotes: 3 <issue_comment>username_4: An option if one is only checking types is to use syntax highlighting. In a test file I do something like this: ``` const t=(result:true)=>console.log(result) const f=(result:false)=>console.log(result) type MyType = string t(false as ( 'dog' extends MyType ? true : false )) t(false as ( 1 extends MyType ? true : false )) f(true as ( 1 extends MyType ? true : false )) let x : 'a' | 'b' t(false as ( 'a' extends typeof x ? true : false )) t(false as ( 'b' extends typeof x ? true : false )) t(false as ( 'c' extends typeof x ? true : false )) ``` [code with syntax highlight](https://www.typescriptlang.org/play?#code/MYewdgzgLgBFC8AKATgUwgVwDZQFxWQ1QEp4A+USELVAOixAH<KEY>) The structure is: `t(false as ( <<>> extends <<>> ? true ; false ))` Upvotes: 0
2018/03/15
618
2,358
<issue_start>username_0: I've been using NTLK classifiers to train datasets and classify single record. For training the records I use this function, ``` nltk.NaiveBayesClassifier.train(train_set) ``` For classifying a single record, ``` nltk.NaiveBayesClassifier.classify(record) ``` where, "record" is the variable name. In Scikit classifiers, for training dataset, the function used is, ``` from sklearn.ensemble import RandomForestClassifier classifier = RandomForestClassifier() classifier.fit(X_train, y_train) ``` What is the function to classify single record in scikit learn classifiers? i.e., is there something like this classifier.classify() ? Predict method only classifies for whole test set converted into a sparse matrix vector, like y\_pred = classifier.predict(X\_test) ``` y_pred = classifier.predict(X_test) ``` I couldn't classify for a single record; I get this error : ``` File "C:\Users\HSR\Anaconda2\lib\site-packages\sklearn\utils\validation.py", line 433, in check_array array = np.array(array, dtype=dtype, order=order, copy=copy) ValueError: could not convert string to float: This is a bot ``` If predict can be used to classify a single record, then how to do it?<issue_comment>username_1: If you are looking for a method that helps you to predict which class your data would fall in, I believe, ``` from sklearn.ensemble import RandomForestClassifier classifier = RandomForestClassifier() classifier.fit(X_train, y_train) classifier.predict(record) ``` would help. To know more about the available APIs, please follow this [link to the documentation](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html). It looks like, you are looking for a text classifier. Here is a `scikit-learn` [example](http://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html#training-a-classifier) of a text classifier. The page gives a thorough introduction to working with text data in `scikit-learn`. Upvotes: 2 <issue_comment>username_2: You need to apply all of the same preprocessing that you applied to your training data, sklearn classifiers don't know what you did to turn your text into training data. However, this can be done using sklearn's pipelines. `predict` does also expect an array, but you can pass it an array of one sample. Upvotes: 0
2018/03/15
467
1,892
<issue_start>username_0: I have a Entity using a different database than the one in use by the default connection, so into entity's annotations i have put : ``` /** * MyClassName * * @ORM\Table(name="mytable", schema="`myschema`") * @ORM\Entity(repositoryClass="App\...\MyClassNameRepository") */ class MyClassName { ... ``` It 's work. But i would like to set schema like this : ``` schema="`%myapp.specificschema%`" ``` I want to do that because i want to set a different name of database in production and environnement, and i want to change this parameter only once in only one file. But it's seems to be impossible because doctrine cannot access parameters ... Thanks in advance for any reply !<issue_comment>username_1: If you are looking for a method that helps you to predict which class your data would fall in, I believe, ``` from sklearn.ensemble import RandomForestClassifier classifier = RandomForestClassifier() classifier.fit(X_train, y_train) classifier.predict(record) ``` would help. To know more about the available APIs, please follow this [link to the documentation](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html). It looks like, you are looking for a text classifier. Here is a `scikit-learn` [example](http://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html#training-a-classifier) of a text classifier. The page gives a thorough introduction to working with text data in `scikit-learn`. Upvotes: 2 <issue_comment>username_2: You need to apply all of the same preprocessing that you applied to your training data, sklearn classifiers don't know what you did to turn your text into training data. However, this can be done using sklearn's pipelines. `predict` does also expect an array, but you can pass it an array of one sample. Upvotes: 0
2018/03/15
1,440
4,599
<issue_start>username_0: Array.fill() ------------ ``` Array(10).fill(0); ``` Array.Apply() ------------- ``` Array.apply(0, new Array(10)); ``` Both are doing similarly same. So what is the difference between them and which one is best for performance? I got a pretty much answer. But Update: ------- **Array.fill()** ```js console.log(Array(10).fill(undefined)); ``` **Array.Apply()** ```js console.log(Array.apply(undefined, new Array(10))); ``` > > Now both are doing similarly same. So what is the difference between them and which one is best for performance? > > ><issue_comment>username_1: > > Both are doing similarly same. > > > No, they aren't. The first fills the array with the value `0`. The second fills it with `undefined`. Note that the `0` you're passing in the second example is completely ignored; the first argument to `Function#apply` sets what `this` is during the call, and [`Array` with multiple arguments](https://tc39.github.io/ecma262/#sec-array-items) doesn't use `this` at all, so you could pass anything there. Example: ```js var first = Array(10).fill(0); console.log(first); var second = Array.apply(0, new Array(10)); console.log(second); ``` ```css .as-console-wrapper { max-height: 100% !important; } ``` > > So what is the difference between them... > > > See above. :-) Also, see notes below on the follow-up question. Subjectively: `Array.fill` is clearer (to me). :-) > > ...and which one is best for performance? > > > It's irrelevant. Use the one that does what you need to do. --- In a follow-up, you've asked the difference between ``` Array(10).fill(undefined) ``` and ``` Array.apply(undefined, new Array(10)) ``` The end result of them is the same: An array with entries whose values are `undefined`. (The entries are really there, e.g. `.hasOwnProperty(0)` will return `true`. As opposed to `new Array(10)` on its own, which creates a sparse array with `length == 10` with no entries in it.) In terms of performance, it's extremely unlikely it matters. Either is going to be plenty fast enough. Write what's clearest and works in your target environments ([`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) was added in ES2015, so doesn't exist in older environments, although it can easily be polyfilled). If you're really concerned about the difference in performance, write your real-world code both ways and profile it. Finally: As far as I know there's no particular limit on the size of the array you can use with `Array.fill`, but `Function#apply` is subject to the maximum number of arguments for a function call and the maximum stack size in the JavaScript platform (which could be large or small; the spec doesn't set requirements). See the [MDN page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) for more about the limit, but for instance `Array.apply(0, new Array(200000))` fails on V8 (the engine in Chrome, Chromium, and Node.js) with a "Maximum call stack size exceeded" error. Upvotes: 4 [selected_answer]<issue_comment>username_2: I did a test for that: ``` const calculateApply = function(items){ console.time('calculateApply'); Array.apply(undefined, new Array(items)); console.timeEnd('calculateApply'); } const calculateFill = function(items){ console.time('calculateFill'); Array(items).fill(undefined); console.timeEnd('calculateFill'); } const getTime = function(items){ console.log(`for ${items} items the time of fill is: `) calculateFill(items) console.log(`for ${items} items the time of apply is:`) calculateApply(items) } getTime(10) getTime(100000) getTime(100000000) ``` and here is the result: ``` for 10 items the time of fill is: calculateFill: 0.481ms for 10 items the time of apply is: calculateApply: 0.016ms for 100000 items the time of fill is: calculateFill: 2.905ms for 100000 items the time of apply is: calculateApply: 1.942ms for 100000000 items the time of fill is: calculateFill: 6157.238ms for 100000000 items the time of apply is: /Users/n128852/Projects/pruebas/index.js:3 Array.apply(0, new Array(items)); ^ RangeError: Maximum call stack size exceeded ``` <https://www.ecma-international.org/ecma-262/6.0/#sec-function.prototype.apply> <https://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.fill> Here you have the information, like you can read, the apply function prepare params to be executed like a tail recursive method. fill, conversely, is iterative. Upvotes: 1
2018/03/15
640
2,882
<issue_start>username_0: Okay, I know the question may sound stupid. I’m building an app where there are pages that publish posts and users can subscribe/unsubscribe to those pages. The goal here is to find a way to send notifications whenever a new post is published but only to the subscribed users. I though that I can do this by sending a push notification to all the devices on my app whenever the “Posts” reference is updated on Firebase database, and then choose whether to show this notification or not if the user is subscribed (on client side) Is this a good idea? And if yes, how can I accomplish that?<issue_comment>username_1: You can push notification to only subscribed users if you are maintaining a list of subscribed users FCM token in your database Upvotes: 1 <issue_comment>username_2: > > Is this a good idea? > > > Yes, the idea is not bad. However, filtering notification to be shown in client side is done in many cases. > > And if yes, how can I accomplish that? > > > I hope you already have a login or authentication system using Firebase authentication or any other server side authentication. When you have this, you might have already considered sending a push registration id to your server or firebase when a user signs up in your application and save it in your firebase database. Now when its time to send a push notification, you are planning to send the push notification to all of your registered devices and you want to filter the notification will be shown or nor in the client side. This can be achieved by keeping a flag in the client side, for example a `SharedPreference` having the id or tag of the last post. If you have an incremental id for each post, then it will be a lot easier to implement. When a user launches your application, it pulls the posts from your firebase database as I can think of. Just save the latest id of the post in your `SharedPreference` and when a push is received, match the id of the post that came along with the push notification with the latest id stored locally. If the id received via push notification is greater than the id stored in your `SharedPreference`, you will show the notification in system tray and the notification will not be shown otherwise. Hope that helps. Upvotes: 3 [selected_answer]<issue_comment>username_3: Your approach is correct, what you would need to do is that maintain different database tables for all pages where users are inserted when they subscribe to that particular group/table. So, let's suppose when a person subscribes to the page containing information about Sports, you add him to that group. Later, when you are sending update/notifications related to 'Sports' you would only send those push notifications to the user-tokens in 'Sports' table. In this way, only relevant subscribers would receive those push notifications. Upvotes: 1
2018/03/15
1,556
5,128
<issue_start>username_0: I am using the below logic to download 3 file from the array at once, once all 3 completed only the next 3 files will be picked up. ``` parallel=3 downLoad() { while (( "$#" )); do for (( i=0; i<$parallel; i++ )); do echo "downloading ${1}..." curl -s -o ${filename}.tar.gz & shift done wait echo "#################################" done } downLoad ${layers[@]} ``` But how i am expecting is "at any point in time 3 downloads should run" - i mean suppose we sent 3 file-downloads to background and one among the 3 gets completed very soon because of very less size, i want another file from the queue should be send for download. COMPLETE SCRIPT: ``` #!/bin/bash set -eu reg="registry.hub.docker.com" repo="hjd48" image="redhat" name="${repo}/${image}" tag="latest" parallel=3 # Get auth token token=$( curl -s "https://auth.docker.io/token?service=registry.docker.io&scope=repository:${name}:pull" | jq -r .token ) # Get layers resp=$(curl -s -H "Authorization: Bearer $token" "https://${reg}/v2/${name}/manifests/${tag}" | jq -r .fsLayers[].blobSum ) layers=( $( echo $resp | tr ' ' '\n' | sort -u ) ) prun() { PIDS=() while (( "$#" )); do if ( kill -0 ${PIDS[@]} 2>/dev/null ; [[ $(( ${#PIDS[@]} - $? )) -lt $parallel ]]) then echo "Download: ${1}.tar.gz" curl -s -o $1.tar.gz -L -H "Authorization: Bearer $token" "https://${reg}/v2/${name}/blobs/${1}" & PIDS+=($!) shift fi done wait } prun ${layers[@]} ```<issue_comment>username_1: I would read all provided filenames into three variables, and then process each stream separately, e.g. ``` PARALLEL=3 COUNTER=1 for FILENAME in $# do eval FILESTREAM${COUNTER}="\$FILESTREAM${COUNTER} \${FILENAME}" COUNTER=`expr ${COUNTER} + 1` if [ ${COUNTER} -gt ${PARALLEL} ] then COUNTER=1 fi done ``` and now call the download function for each of the streams in parallel: ``` COUNTER=1 while [ ${COUNTER} -le ${PARALLEL} ] do eval "download \$FILESTREAM${COUNTER} &" COUNTER=`expr ${COUNTER} + 1` done ``` Upvotes: 0 <issue_comment>username_2: I've done just this by using `trap` to handle `SIGCHLD` and start another transfer when one ends. The difficult part is that once your script installs a `SIGCHLD` handler with that `trap` line, you can't create *any* child processes other than your transfer processes. For example, if your shell doesn't have a built-in `echo`, calling `echo` would spawn a child process that would cause you to start one more transfer when the `echo` process ends. I don't have a copy available, but it was something like this: ``` startDownload() { # only start another download if there are URLs left in # in the array that haven't been downloaded yet if [ ${ urls[ $fileno ] } ]; # start a curl download in the background and increment fileno # so the next call downloads the next URL in the array curl ... ${ urls[ $fileno ] } & fileno=$((fileno+1)) fi } trap startDownload SIGCHLD # start at file zero and set up an array # of URLs to download fileno=0 urls=... parallel=3 # start the initial parallel downloads # when one ends, the SIGCHLD will cause # another one to be started if there are # remaining URLs in the array for (( i=0; i<$parallel; i++ )); do startDownload done wait ``` That's not been tested at all, and probably has all kinds of errors. Upvotes: 1 <issue_comment>username_3: Besides implementing a parallel bash script from scratch, `GNU parallel` is an available tool to use which is quite suitable to perform these type of tasks. ``` parallel -j3 curl -s -o {}.tar.gz download_url ::: "${layers[@]}" ``` * `-j3` ensures a maximum of 3 jobs running at the same time * you can add an additional option `--dry-run` after `parallel` to make sure the built command is exactly as you want Upvotes: 0 <issue_comment>username_4: If you do not mind using `xargs` then you can: ``` xargs -I xxx -P 3 sleep xxx < sleep ``` and sleep is: ``` 1 2 3 4 5 6 7 8 9 ``` and if you watch the background with: ``` watch -n 1 -exec ps --forest -g -p your-Bash-pid ``` (**sleep** could be your array of link ) then you will see that **3** jobs are run in parallel and when one of these three is completed the next job is added. In fact always **3** jobs are running till the end of array. sample output of `watch(1)`: ``` 12260 pts/3 S+ 0:00 \_ xargs -I xxx -P 3 sleep xxx 12263 pts/3 S+ 0:00 \_ sleep 1 12265 pts/3 S+ 0:00 \_ sleep 2 12267 pts/3 S+ 0:00 \_ sleep 3 ``` `xargs` starts with **3** jobs and when one of them is finished it will add the next which bacomes: ``` 12260 pts/3 S+ 0:00 \_ xargs -I xxx -P 3 sleep xxx 12265 pts/3 S+ 0:00 \_ sleep 2 12267 pts/3 S+ 0:00 \_ sleep 3 12269 pts/3 S+ 0:00 \_ sleep 4 # this one was added ``` Upvotes: 3 [selected_answer]
2018/03/15
1,419
4,573
<issue_start>username_0: Is there a simple program which demonstrates how queues work in Go. I just need something like add number 1 to 10 in queue and pull those from the queue in parallel using another thread.<issue_comment>username_1: A queue that is safe for concurrent use is basically a language construct: [channel](https://golang.org/ref/spec#Channel_types). A channel–by design–is safe for concurrent [send](https://golang.org/ref/spec#Send_statements) and [receive](https://golang.org/ref/spec#Receive_operator). This is detaild here: [If I am using channels properly should I need to use mutexes?](https://stackoverflow.com/questions/34039229/if-i-am-using-channels-properly-should-i-need-to-use-mutexes/34039377#34039377) Values sent on it are received in the order they were sent. You can read more about channels here: [What are golang channels used for?](https://stackoverflow.com/questions/39826692/what-are-golang-channels-used-for/39826883#39826883) A very simple example: ``` c := make(chan int, 10) // buffer for 10 elements // Producer: send elements in a new goroutine go func() { for i := 0; i < 10; i++ { c <- i } close(c) }() // Consumer: receive all elements sent on it before it was closed: for v := range c { fmt.Println("Received:", v) } ``` Output (try it on the [Go Playground](https://play.golang.org/p/nYcOy7suyr1)): ``` Received: 0 Received: 1 Received: 2 Received: 3 Received: 4 Received: 5 Received: 6 Received: 7 Received: 8 Received: 9 ``` Note that the channel buffer (10 in this example) has nothing to do with the number of elements you want to send "through" it. The buffer tells how many elements the channel may "store", or in other words, how many elements you may send on it without blocking when there are nobody is receiving from it. When the channel's buffer is full, further sends will block until someone starts receiving values from it. Upvotes: 3 <issue_comment>username_2: You could use channel(safe for concurrent use) and wait group to read from queue concurrently ``` package main import ( "fmt" "sync" ) func main() { queue := make(chan int) wg := new(sync.WaitGroup) wg.Add(1) defer wg.Wait() go func(wg *sync.WaitGroup) { for { r, ok := <-queue if !ok { wg.Done() return } fmt.Println(r) } }(wg) for i := 1; i <= 10; i++ { queue <- i } close(queue) } ``` Playground link: <https://play.golang.org/p/A_Amqcf2gwU> Upvotes: 3 [selected_answer]<issue_comment>username_3: Another option is to create and implement a queue `interface`, with a backing type of a channel for concurrency. For convenience, I've made a [gist](https://gist.github.com/frankbryce/151f172270d600958740312f1cd31705). Here's how you can use it. ``` queue := GetIntConcurrentQueue() defer queue.Close() // queue.Enqueue(1) // myInt, errQueueClosed := queue.DequeueBlocking() // myInt, errIfNoInt := queue.DequeueNonBlocking() ``` Longer example here - <https://play.golang.org/p/npb2Uj9hGn1> Full implementation below, and again here's the [gist](https://gist.github.com/frankbryce/151f172270d600958740312f1cd31705) of it. ``` // Can be any backing type, even 'interface{}' if desired. // See stackoverflow.com/q/11403050/3960399 for type conversion instructions. type IntConcurrentQueue interface { // Inserts the int into the queue Enqueue(int) // Will return error if there is nothing in the queue or if Close() was already called DequeueNonBlocking() (int, error) // Will block until there is a value in the queue to return. // Will error if Close() was already called. DequeueBlocking() (int, error) // Close should be called with defer after initializing Close() } func GetIntConcurrentQueue() IntConcurrentQueue { return &intChannelQueue{c: make(chan int)} } type intChannelQueue struct { c chan int } func (q *intChannelQueue) Enqueue(i int) { q.c <- i } func (q *intChannelQueue) DequeueNonBlocking() (int, error) { select { case i, ok := <-q.c: if ok { return i, nil } else { return 0, fmt.Errorf("queue was closed") } default: return 0, fmt.Errorf("queue has no value") } } func (q *intChannelQueue) DequeueBlocking() (int, error) { i, ok := <-q.c if ok { return i, nil } return 0, fmt.Errorf("queue was closed") } func (q *intChannelQueue) Close() { close(q.c) } ``` Upvotes: 0
2018/03/15
728
3,061
<issue_start>username_0: I just wrote this code to test something for a better understanding of reflection. This is the ReflectionTestMain class: ``` import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class ReflectionTestMain { public static void main(String[] args) { try { ReflectionTest rt = new ReflectionTest(); Class c = ReflectionTest.class; Field f = c.getDeclaredField("value"); f.setAccessible(true); f.set(rt, "text"); Method m = c.getDeclaredMethod("getValue"); m.setAccessible(true); String value = (String) m.invoke(rt); System.out.println(value); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { e.printStackTrace(); } } } ``` And this is the ReflectionTest class. ``` public class ReflectionTest { private final String value = "test"; private String getValue() { return value; } } ``` This code prints test but I expected it prints text. What is the reason that this does not work and how can I fix that?<issue_comment>username_1: While the variable is properly updated, it isn't propagated to the `getValue()` method. The reason for this is that the compiler optimizes the program for you. Since the compiler knows that the variable `value` is not changed, it compiles it to inline access directly to the string pool, instead of going through the variable. This can be sees by running `java -p` on the class file This can be solved by using a initizer block or constructor for the string constant, or making the statement more complex to "fool" the compiler. ``` class ReflectionTest { // Use either private final String value; { value = "test"; } // Or private final String value; public ReflectionTest () { value = "test"; } // Or private final String value = Function.identity().apply("test"); // Or // Do not replace with + as the compiler is too smart private final String value = "test".concat(""); // Depending on your required performance/codestyling analyses private String getValue() { return value; } } ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: From javadoc on `Field.set(..)` ``` * If the underlying field is final, the method throws an \* {@code IllegalAccessException} unless {@code setAccessible(true)} \* has succeeded for this {@code Field} object \* and the field is non-static. Setting a final field in this way \* is meaningful only during deserialization or reconstruction of \* instances of classes with blank final fields, before they are \* made available for access by other parts of a program. Use in \* any other context may have unpredictable effects, including cases \* in which other parts of a program continue to use the original \* value of this field. ``` So you just use reflection in an incorrect way here. Upvotes: 1
2018/03/15
863
2,673
<issue_start>username_0: I want to implement in python a simple model for optical propagation. The rule is that if I chain three elements *m0 -> m1-> m2* what I would get as system is: * tau = tau0 \* tau1 \* tau2 * B = B2 + B1\*tau2 + B0\*tau2\*tau1 (tau is transmission, B is background). I wanted to implement overloading the `__gt__` operator such that I can declare: ``` m0 = Mirror(0.9, 10) m1 = Mirror(0.8, 11) m2 = Mirror(0.7, 12) x = m0 > m1 > m2 ``` So far I wrote this: ``` class OpticalElement: def __init__(self, trans, background): self.trans = trans self.background = background class Mirror(OpticalElement): def __gt__(self, other): if isinstance(other, Mirror): tau = self.trans * other.trans bkg = other.background + other.trans * self.background return Mirror(tau, bkg) else: return NotImplemented ``` However this code seems only to get the transmission and background of the rightmost elements: ``` x = m0 > m1 > m2 x.trans ``` Returns 0.56, while I am expecting 0.504. Background behaves the same, I am getting 19.7 instead of 25.3 (first element ignored). **Do you guys have any idea on how to implement several chained elements using the operator overloading?** (putting parenthesis works, but I wanted to have cleaner code). Thanks! Andreu<issue_comment>username_1: The way chained comparisons work is that `m0 > m1 > m2` is evaluated as `(m0 > m1) and (m1 > m2)`, which results in `m1 > m2`, as `x and y`returns `y` if `x` is truish. So this is the reason why your code seems only to get the rightmost comparison. Instead, you can do `x = (m0 > m1) > m2`. which evaluates both `>` operators in the given order. This results in ``` x = (m0 > m1) > m2 print(x.trans) # 0.504 ``` Upvotes: 1 <issue_comment>username_2: `m0 > m1 > m2` is equivalent to `(m0 > m1) and (m1 > m2)`. As `m0 > m1` will be considered `True`, `and` will test `m1 > m2` and return its value, which is the 0.56 you get. You could use the multiplication operator, which will work as expected: ``` class OpticalElement: def __init__(self, trans, background): self.trans = trans self.background = background class Mirror(OpticalElement): def __mul__(self, other): if isinstance(other, Mirror): tau = self.trans * other.trans bkg = other.background + other.trans * self.background return Mirror(tau, bkg) else: return NotImplemented m0 = Mirror(0.9, 10) m1 = Mirror(0.8, 11) m2 = Mirror(0.7, 12) x = m0 *m1 * m2 print(x.trans) #0.504 ``` Upvotes: 3 [selected_answer]
2018/03/15
853
3,292
<issue_start>username_0: [![enter image description here](https://i.stack.imgur.com/OKBbF.png)](https://i.stack.imgur.com/OKBbF.png) I have problem with activity navigation. I have 3 activities. 1) `ActivityA` is list of Invoice 2) `ActivityB` is list of Items of Invoice (invoice detail) 3) `ActivityC` is product list * When user click on Invoice item in `ActivityA`, then I start `ActivityB` and show Invoice detail. * When user click on PLUS button in `ActivityB`, I start `ActivityC` and user can select products into Invoice. * When user click on BACK button in `ActivityC`, then `ActivityC` finishes and user is in `ActivityB`. Ok, it is functional, but I need: When user click on PLUS button in `ActivityA`, then create Invoice and directly start `ActivityC` for product selection. OK, I start `ActivityC`, user can select product. But problem is, when user click on Back button in `ActivityC`, I need to navigate back to `ActivityB` (to invoice detail) not to `ActivityA`. How can I do this? What is the best solution for this problem?<issue_comment>username_1: In that case start Activity B from Activity C and finish Activity C. ``` void startActivityB(){ Intent starter = new Intent(this, ActivityB.class); startActivity(starter); this.finish(); } ``` And ActivityA still will be in stack. Upvotes: 0 <issue_comment>username_2: Here is a solution that i think might work for you. On back press in Activity C .. fire intent for starting activity B .. this might help you.. Let me know if this worked for you! Else you need to show the code snippet.. Upvotes: 0 <issue_comment>username_3: You just have to override the `onBackPressed` function in your `ActivityC` to handle the transition among your activities. Here's how you do it. While you are launching `ActivityC` from `ActivityB`, start the activity like this. ``` Intent intent = new Intent(this, ActivityC.class); intent.putExtra("CallingActivity", "ActivityB"); startActivity(intent); ``` And while launching `ActivityC` from your `ActivityA`, you need to do the following. ``` Intent intent = new Intent(this, ActivityC.class); intent.putExtra("CallingActivity", "ActivityA"); startActivity(intent); ``` Now in your `ActivityC` you need to check the value of the intent and save it somewhere. Then handle the `onBackPressed` function in your `ActivityC`. ``` String callingActivity = null; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_activity_c); Bundle bundle = getIntent().getExtras(); callingActivity = bundle.getString("CallingActivity", null); } @Override public void onBackPressed() { if(callingActivity != null && callingActivity.equals("ActivityB")) super.onBackPressed(); else { Intent intent = new Intent(this, ActivityB.class); startActivity(intent); } } ``` Hope that helps. Upvotes: 2 [selected_answer]<issue_comment>username_4: Override onBackpressed method in your activity c try this one ``` @Override public void onBackPressed() { //code any action you want at here Intent activityB= new Intent(ActivityC.this, ActivityB.class); startActivity(activityB);finish(); } ``` Hope this will work for you Upvotes: 0
2018/03/15
926
3,414
<issue_start>username_0: I have Services set up in Angular to fetch JSON data from REST webservices. Now I consume data from service in `OnInit` method and store in local made array. But when I access them it shows `undefined`. Services are working fine, checked that data is coming or not. Sorry for bad english, not native language. ``` constructor(private myService: MyService, private anotherService: AnotherService) {} arr: any[]; arr2: any[]; ngOnInit() { this.myservice.getData(12).subscribe((data) => { this.arr = data; }); for (let item of this.arr) { if (item.id == 5) { this.arr2.push(item); } } console.log('Data - ', this.arr2); // --> This shows undefined :( } ``` But this works when I call custom method from `OnInit` ``` constructor(private myService: MyService, private anotherService: AnotherService) {} arr: any[]; arr2: any[]; ngOnInit() { this.myservice.getData(12).subscribe((data) => { this.arr = data; this.stage(); }); } stage() { for (let item of this.arr) { if (item.id == 5) { this.arr2.push(item); } } console.log('Data - ', this.arr2); // --> This shows data :) } ``` Someone help understand why. thanks<issue_comment>username_1: In that case start Activity B from Activity C and finish Activity C. ``` void startActivityB(){ Intent starter = new Intent(this, ActivityB.class); startActivity(starter); this.finish(); } ``` And ActivityA still will be in stack. Upvotes: 0 <issue_comment>username_2: Here is a solution that i think might work for you. On back press in Activity C .. fire intent for starting activity B .. this might help you.. Let me know if this worked for you! Else you need to show the code snippet.. Upvotes: 0 <issue_comment>username_3: You just have to override the `onBackPressed` function in your `ActivityC` to handle the transition among your activities. Here's how you do it. While you are launching `ActivityC` from `ActivityB`, start the activity like this. ``` Intent intent = new Intent(this, ActivityC.class); intent.putExtra("CallingActivity", "ActivityB"); startActivity(intent); ``` And while launching `ActivityC` from your `ActivityA`, you need to do the following. ``` Intent intent = new Intent(this, ActivityC.class); intent.putExtra("CallingActivity", "ActivityA"); startActivity(intent); ``` Now in your `ActivityC` you need to check the value of the intent and save it somewhere. Then handle the `onBackPressed` function in your `ActivityC`. ``` String callingActivity = null; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_activity_c); Bundle bundle = getIntent().getExtras(); callingActivity = bundle.getString("CallingActivity", null); } @Override public void onBackPressed() { if(callingActivity != null && callingActivity.equals("ActivityB")) super.onBackPressed(); else { Intent intent = new Intent(this, ActivityB.class); startActivity(intent); } } ``` Hope that helps. Upvotes: 2 [selected_answer]<issue_comment>username_4: Override onBackpressed method in your activity c try this one ``` @Override public void onBackPressed() { //code any action you want at here Intent activityB= new Intent(ActivityC.this, ActivityB.class); startActivity(activityB);finish(); } ``` Hope this will work for you Upvotes: 0
2018/03/15
408
1,726
<issue_start>username_0: I have been into alexa development and recently I have encountered a never before situation. While trying to enable testing on a new skill, I am getting the following error on the **test** tab : > > There was a failure enabling your skill, please try again. > > > I know that this might happen if I do not complete the previous steps such skill information, interaction model, configuration etc. But the strange thing is that i have completed all of the above steps. My skill has : * A valid skill name * It has valid intents, slots and sample utterrances in my interaction model * I have successfully saved and built my interaction model * I have provided valid end-points ARN of my AWS lambda function, which has alexa-skill-kit enabled with the skill-id of my skill, in the configuration tab. I don't think I have missed any of the requirement as it shows green tick(successful completion) on all mentioned steps before testing. But I can not enable the test stimualtaor in the **test** tab. It throws the above mentioned error message. Any help will be highly appreciated. Thanks!!<issue_comment>username_1: Go to the "**build**" tab in your Alexa Skill page. On the right side, you will find "**Skill Builder Checklist**". Make sure that all steps in the checklist are completed. Thanks Upvotes: 2 <issue_comment>username_2: In EndPoint -> click Save Endpoints, if it successful then in Test, you can see Test is enabled for this skill ( in blue color). Upvotes: -1 <issue_comment>username_3: Visit the invocation tab in Alexa Skill Kit Developer console. All Skill builder checklist have to be complete to start the test. Don't forget to build your skill before run test. Upvotes: 2
2018/03/15
285
1,031
<issue_start>username_0: I'm working with opencv in my last study's project. I have python 2.7 x86 and opencv 3.4 already installed. I developed my python project in windows 8 64 bit and I converted my application from .py to .exe through Pyinstaller and it's working fine . But when I move my application to the industrial machine which is windows xp pack 3 32bit and i try to import cv2 I get the following error : > > ImportError: DLL load failed: The specified module could not be found. > > > Note that I have tried to install Microsoft visual c++ 2015 and didn't solve the problem and I try everything said about this problem on stackoverflow and didn't work with me . Can anyone help me here ?<issue_comment>username_1: You should copy opencv.dll to directory contains .exe. Upvotes: 1 <issue_comment>username_2: The latest supported version **opencv** for WindowsXP and with Python v3.4 support is '**3.2.0.8**' You can still install it by following command: ``` pip install opencv-python==3.2.0.8 ``` Upvotes: 0
2018/03/15
474
1,310
<issue_start>username_0: Hopefully this is quite straight forward. I am trying to convert a column to int so I can sum on it. ``` SELECT (cast(RTRIM(pricing_prices)as int)) FROM returnxx where RMAid= '5' ``` **errors** > > Conversion failed when converting the nvarchar value > '9.8000000000000007' to data type int. > > > If I try bigint I get another error > > Error converting data type nvarchar to bigint. > > ><issue_comment>username_1: First convert into `Numeric` and then `INT`. Try this: ``` DECLARE @Var varchar(100)='9.8000000000000007' SELECT CAST(CAST(@Var AS NUMERIC(35,16)) AS INT) ``` **Result:** ``` 9 ``` If you want `ROUND` value, just convert into Numeric: ``` SELECT CAST(@Var AS NUMERIC) ``` **Result:** ``` 10 ``` If you want `DECIMAL` value, just convert into Numeric: ``` SELECT CAST(@Var AS NUMERIC(8,2)) ``` **Result:** ``` 9.80 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: I have this problem in the past. i was able to resolve it by casting the column to decimal first then cast it to an Integer. You can cast it to any decimal of your choice ``` DECLARE @pricing_prices NVARCHAR(20)='9.8000000000000007' AS pricing_prices SELECT CAST(CAST(@pricing_prices AS DECIMAL(9,2)) AS INT) ``` Output ``` pricing_prices 9 ``` Upvotes: 1
2018/03/15
574
1,594
<issue_start>username_0: Is it possible to use varName1[varName2] to retrieve a value from an array. In the example below, .el is a select box, thisVal might = 2 and thisName = 'B' which should result in the answer 'U' in fact I am getting undefined ``` var A = ['B','B','Z','Z'] var B = ['C','O','U','C2','C3','D'] var C = ['D','Z','D','Z'] $('.el').on('change', function() { var thisVal = this.value var thisName = this.name var nextName = thisName[thisVal] alert( nextName ); }) ```<issue_comment>username_1: If you arrays are in the global scope, you can use. ``` window[thisName][thisVal] ``` Example ```js var A = ['B','B','Z','Z']; var B = ['C','O','U','C2','C3','D']; var C = ['D','Z','D','Z']; var thisVal = 2; var thisName = 'B'; console.log(window[thisName][thisVal]); ``` As an alternative you can use an object to store your arrays and instead of the `window` use your object. Example ```js const obj = { A: ['B','B','Z','Z'], B: ['C','O','U','C2','C3','D'], C: ['D','Z','D','Z'] } const thisVal = 2; const thisName = 'B'; console.log(obj[thisName][thisVal]); ``` Upvotes: 3 <issue_comment>username_2: > > which should result in the answer 'U' in fact I am getting undefined > > > That is not applicable for javascript and undefined is *exactly* what it should return You can use [javascript eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) for this purpose ``` var a = [1, 2, 3]; var x= 'a'; var y=2; console.log(x+'['+y+']') // "a[2]" console.log(eval(x+'['+y+']')) // 3 ``` Upvotes: 0
2018/03/15
520
1,434
<issue_start>username_0: I have an array $faecher to create an SELECT Field with options. My problem is that I want to pre-select an option which is saved in variable f\_name1. ``` php for ($i = 0; $i <= count($faecher); $i++) echo "<option" if ($faecher[$i] == f\_name1) echo 'selected="selected"'; "".$faecher[$i].""; ?> ```<issue_comment>username_1: If you arrays are in the global scope, you can use. ``` window[thisName][thisVal] ``` Example ```js var A = ['B','B','Z','Z']; var B = ['C','O','U','C2','C3','D']; var C = ['D','Z','D','Z']; var thisVal = 2; var thisName = 'B'; console.log(window[thisName][thisVal]); ``` As an alternative you can use an object to store your arrays and instead of the `window` use your object. Example ```js const obj = { A: ['B','B','Z','Z'], B: ['C','O','U','C2','C3','D'], C: ['D','Z','D','Z'] } const thisVal = 2; const thisName = 'B'; console.log(obj[thisName][thisVal]); ``` Upvotes: 3 <issue_comment>username_2: > > which should result in the answer 'U' in fact I am getting undefined > > > That is not applicable for javascript and undefined is *exactly* what it should return You can use [javascript eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) for this purpose ``` var a = [1, 2, 3]; var x= 'a'; var y=2; console.log(x+'['+y+']') // "a[2]" console.log(eval(x+'['+y+']')) // 3 ``` Upvotes: 0
2018/03/15
442
1,370
<issue_start>username_0: what's the most efficient way to do this in CSS??? Basically it looks like this: {F}IRST {L}ETTER, where the letters in the braces are a little bigger than the other ones but they all the letters are uppercase. Any suggestions?<issue_comment>username_1: Use [font-variant](https://www.w3schools.com/cssref/pr_font_font-variant.asp) property of CSS ```css h1 { font-variant: small-caps; } ``` ```html Main Heading ============ ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: ``` .simplyCapFirstBigger { font-variant: small-caps; } ``` Upvotes: 2 <issue_comment>username_3: Look if it is no dynamic data i have a good suggestion which is: wrap the letters you want it to be slightly bigger in a span and create a class for this span with font size bigger a than the h1 font size for example if h1 font size 16px make the span 18px ```css h1 { font-size: 16px; } span { font-size: 18px; } ``` ```html Main Heading ============ ``` simply this will solve your problem easily but using css font-variant doesn't take size. Upvotes: 0 <issue_comment>username_4: ```css p { text-transform: uppercase } p::first-letter { font-size: 200%; } ``` ```html Example text ``` [JS Bin](https://jsbin.com/ciyolulake/edit?html,css,output) [Browser support](https://caniuse.com/#feat=css-first-letter) Upvotes: 2
2018/03/15
1,228
3,821
<issue_start>username_0: I want to set different font sizes for iPhone 5, iPhone 6 Plus, iPhone 7 Plus and iPhone X using Xcode Storyboard. Can anyone offer any advice? [![Example is shown in the image where i was stuck.](https://i.stack.imgur.com/rqADm.png)](https://i.stack.imgur.com/rqADm.png)<issue_comment>username_1: You can't accomplish this in IB , you can detect the current device at runtime with it's size and set the font accordingly , if all elements have same font you can use .appearnce to set a global font There is no font variation for IPhone 6,7,X , it has to be in code not IB Upvotes: 2 <issue_comment>username_2: Use [Size-Class](https://developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/TheAdaptiveModel.html) and add size variation for fonts from `Attribute Inspector` of Label property. Here are different possible variations, you can set with Size class: [![enter image description here](https://i.stack.imgur.com/840pL.png)](https://i.stack.imgur.com/840pL.png) [![enter image description here](https://i.stack.imgur.com/uEHG9.png)](https://i.stack.imgur.com/uEHG9.png) Try this: [![enter image description here](https://i.stack.imgur.com/rthJM.png)](https://i.stack.imgur.com/rthJM.png) [![enter image description here](https://i.stack.imgur.com/HIi8O.png)](https://i.stack.imgur.com/HIi8O.png) Here is (result) preview of font-size variation, in iPhone and iPad [![enter image description here](https://i.stack.imgur.com/dYJYo.png)](https://i.stack.imgur.com/dYJYo.png) Update ====== The result you are expecting, may not be possible using IB (Storyboard) but you can try it with following programmatic solution: ``` extension UIDevice { enum DeviceType: String { case iPhone4_4S = "iPhone 4 or iPhone 4S" case iPhones_5_5s_5c_SE = "iPhone 5, iPhone 5s, iPhone 5c or iPhone SE" case iPhones_6_6s_7_8 = "iPhone 6, iPhone 6S, iPhone 7 or iPhone 8" case iPhones_6Plus_6sPlus_7Plus_8Plus = "iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus or iPhone 8 Plus" case iPhoneX = "iPhone X" case unknown = "iPadOrUnknown" } var deviceType: DeviceType { switch UIScreen.main.nativeBounds.height { case 960: return .iPhone4_4S case 1136: return .iPhones_5_5s_5c_SE case 1334: return .iPhones_6_6s_7_8 case 1920, 2208: return .iPhones_6Plus_6sPlus_7Plus_8Plus case 2436: return .iPhoneX default: return .unknown } } } // Get device type (with help of above extension) and assign font size accordingly. let label = UILabel() let deviceType = UIDevice.current.deviceType switch deviceType { case .iPhone4_4S: label.font = UIFont.systemFont(ofSize: 10) case .iPhones_5_5s_5c_SE: label.font = UIFont.systemFont(ofSize: 12) case .iPhones_6_6s_7_8: label.font = UIFont.systemFont(ofSize: 14) case .iPhones_6Plus_6sPlus_7Plus_8Plus: label.font = UIFont.systemFont(ofSize: 16) case .iPhoneX: label.font = UIFont.systemFont(ofSize: 18) default: print("iPad or Unkown device") label.font = UIFont.systemFont(ofSize: 20) } ``` Upvotes: 5 [selected_answer]<issue_comment>username_3: Note: This is not a straightforward answer. However, this can be achieved based on the constraints. If you are using autolayout, you can have the font scale automatically through storyboards. In the `Attributes` inspector for `UILabel`, there is an `Autoshrink` section where you can set the `Minimum Font Size` or `Minimum Font Scale`. So, as your label resizes itself through constraints, it will also scale down your fonts to fit.[![enter image description here](https://i.stack.imgur.com/Q85zq.png)](https://i.stack.imgur.com/Q85zq.png) Upvotes: 2
2018/03/15
343
1,268
<issue_start>username_0: I am using smartgit for accessing files from git. I tried PULL and FETCH option to update. But no change. I don't know what to do?<issue_comment>username_1: The problem of committing to the same branch (or branching from the same head) is that if there is a problem in one pull request, we cannot merge the pull requests after that since the commits exists in all the later pull requests. My suggestion is to create a branch for every new issue fix: To do so you should first set the upstream in your system (only once) ``` git remote add upstream ``` make sure your origin is set to your own fork:`git remote -v`. After that for each new fix do the following: ``` 1-git checkout -b 2- git fetch upstream 3- git reset --hard upstream/ 4- commit to origin 5- make pull request 6- go to 1 for the next issue to fix ``` This is just a suggestion. Upvotes: 1 [selected_answer]<issue_comment>username_2: Are you pushing your changes to your origin server? This is the only way you are going to get your changes to a remote server. [![Push button in SmartGit](https://i.stack.imgur.com/LwV73.png)](https://i.stack.imgur.com/LwV73.png) Upvotes: 1 <issue_comment>username_3: I get it. Its because of the extra -b in the command. Upvotes: 0
2018/03/15
585
2,388
<issue_start>username_0: I've found [this amazing site](http://skilltemplates.com) to generate my first Alexa skill. I've uploaded the standard template they have and it passes all the checks. [![enter image description here](https://i.stack.imgur.com/D6V2L.png)](https://i.stack.imgur.com/D6V2L.png) **Please note that this skill has not published yet** and When I say (to the device), `Alexa, open api starter`, Alexa (device) cannot find that. I have an echo dot 2nd gen. Do we need to publish a skill to be available for the Alexa device? In my test mode, I've already enabled the Test for this skill.<issue_comment>username_1: Yes, you can use the skill locally for development purposes. If you go to the username_2a apps you should see your app located in there and you can then install it. Once installed you can ask username_2a to open the app. Although, you can't use other peoples apps that are in development because the app is associated with the Amazon account. Upvotes: 3 [selected_answer]<issue_comment>username_2: You need to register your device to the development account that you are using. 1. Once logged in from your development account go [here](https://alexa.amazon.com/) (alexa.amazon.com) 2. Go to the settings tab and click set up a new device 3. You will be guided through simple instructions on how to connect your device. Once you successfully connected the device, you can use all skills from your developer account. Note: You can have more devices connected to the same developer account, but each device can be connected to just one developer account at a time. Upvotes: 2 <issue_comment>username_3: Unfortunately this doesn't work all the time - not sure if it's missing information (for instance on the Echo Screen you have to tap the serial number repeatedly to put the device into dev mode - there doesn't seem to be the same thing for the dot - and if there is it's not mentioned here.) It could also just be the sheer number of variables in both the alexa ecosystem, the app and what phone it is on and the network the device is connected to and the dec console. One set of instructions doesn't always cover all the possibilities.' Upvotes: 0 <issue_comment>username_4: I have found that when using the skill kit with vscode that I have to go into the web-based skill editor and do a build before it works with an echo device. Upvotes: 0
2018/03/15
294
1,149
<issue_start>username_0: I know that I can find the columns of any table in a microsoft sql server database using: ``` USE dbname; SELECT COLUMN_NAME AS 'ColumnName',TABLE_NAME AS 'TableName' FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME LIKE '%search-for%' ORDER BY TableName,ColumnName; ``` Is it possible to search all databases in an instance with one query?<issue_comment>username_1: ``` DECLARE @Results TABLE( TABLE_CATALOG VARCHAR(50), TABLE_SCHEMA VARCHAR(50), TABLE_NAME VARCHAR(50), COLUMN_NAME VARCHAR(100) ); INSERT INTO @Results EXEC sp_MSforeachdb @command1 = 'USE [?]; SELECT TABLE_CATALOG ,TABLE_SCHEMA ,TABLE_NAME ,COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME= ''YourColumnName'' ;'; SELECT * FROM @Results ``` Please refer to the comment from @Larnu. Upvotes: 0 <issue_comment>username_2: ``` sp_MSForEachDB @command1='USE ?; SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME like ''%ColumnNameHere%''' ``` Upvotes: 1
2018/03/15
1,008
3,338
<issue_start>username_0: I have two ajax calls i.e. ``` var ajax1 = $.ajax({ url: Url1 }); var ajax2 = $.ajax({ url: Url2 }); $.when(ajax1, ajax2).then(function (response1, response2) { }); ``` We want to conditionally handle the failure cases for these API deferred requests: 1. If ajax1 is success and ajax2 is success: Call `WinAjax1_WinAjax2();` 2. If ajax1 is success and ajax2 fails: Call `WinAjax1_LoseAjax2();` 3. If ajax1 fails and ajax2 is success: Call `LoseAjax1_WinAjax2();` 4. If ajax1 fails and ajax2 fails: Call `LoseAjax1_LoseAjax2();` If I put logic in `.fail` of respective ajax, I don't know what will the response of other ajax. If I put `.fail` in `.when`'s failure, I am not able to identify which failure it is. Could someone help how can I identify which ajax failed with multiple ajax requests once all the requests are completed?<issue_comment>username_1: You could explicitly call a function after either ajax call, which checks all ajax calls have succeeded. For example: ``` var ajax1_success = false, ajax1_called = false, ajax2_success = false, ajax2_called = false; var afterAjax = function () { if (!(ajax1_called && ajax2_called)) { return; } // add conditionals here }; var ajax1 = $.ajax({ url: Url1 }) .success(function() { ajax1_success = true; }).always(function() { ajax1_called = true; afterAjax(); }); var ajax2 = $.ajax({ url: Url2 }) .success(function() { ajax2_success = true; }).always(function() { ajax2_called = true; afterAjax(); }); ``` Upvotes: 0 <issue_comment>username_2: jQuery deferred object has a [state method](https://api.jquery.com/deferred.state/). So you can use `$.when` and in case of fail check every deferred object's state. ```js var d1 = jQuery.Deferred(); var d2 = jQuery.Deferred(); $.when(d1, d2).then(function(v1, v2) { // do something on succes }).fail(function() { console.log(d1.state()); // resolved console.log(d2.state()); // rejected }); d1.resolve( "Fish" ); d2.reject( "Pizza fail" ); ``` **EDIT:** It seems that I missed your main goal. If you need to wait until all request will be done (reolved or rejected). Then `$.when` will not help with this as it will be rejected as soon as any of request will be rejected not waiting for others. In this case I would recommend to count when all you request is finished. And then check their statuses. ```js var d1 = jQuery.Deferred(); var d2 = jQuery.Deferred(); var activeRequests = 2; function onComplete() { activeRequests--; if (!activeRequests) { // check deferred object states here console.log(d1.state()); console.log(d2.state()); } } d1.always(onComplete); d2.always(onComplete); d2.reject( "Pizza fail" ); d1.resolve( "Fish" ); ``` Upvotes: 1 <issue_comment>username_3: The answer is exactly the same as solution mentioned [here](https://stackoverflow.com/a/5825233/5285062). ``` var d1 = $.Deferred(); var d2 = $.Deferred(); var j1 = $.getJSON(...).complete(d1.resolve); var j2 = $.getJSON(...).complete(d2.resolve); $.when(d1,d2).done(function() { // will fire when j1 AND j2 are both resolved OR rejected // check j1.isResolved() and j2.isResolved() to find which failed }); ``` Upvotes: 2 [selected_answer]
2018/03/15
705
1,922
<issue_start>username_0: I want to add a closing bracket to the math expression within the string ``` var str = "solve this now Math.sqrt(345+6 is good but Math.sin(79 is better."; var patt1 = /\((d+)/g; var result = str.match(patt1); document.getElementById("demo").innerHTML = result; ``` The match patter displays (345 and (79. Without changing the content, how can I add a closing bracket so the string look like; ``` var str = " solve this now Math.sqrt(345)+6 is good but Math.sin(79) is better. ```<issue_comment>username_1: Use negative lookahead assertion. ```js var str = "solve this now Math.sqrt(345+6 is good but Math.sin(79 is better."; console.log(str.replace(/(\(\d+)\b(?!\))/g, "$1)")) ``` `(\(\d+)` capture `\(` and one or more digits `(?!\))` only if the match wasn't followed by closing brace `)` Upvotes: 1 <issue_comment>username_2: Check if the an opening brace if followed by numbers, but not by its closing brace after numbers ``` var str = "solve this now Math.sqrt(345+6 is good but Math.sin(79 is better."; var output = str.replace( /\([\d]+(?!=\))/g, r => r + ")"); ``` **Output** > > solve this now Math.sqrt(345)+6 is good but Math.sin(79) is better. > > > **Demo** ```js var str = "solve this now Math.sqrt(345+6 is good but Math.sin(79 is better."; var output = str.replace(/\([\d]+(?!=\))/g, r => r + ")"); console.log(output); ``` You can include `.` to allow decimals as well ``` var str = "solve this now Math.sqrt(345.5+6 is good but Math.sin(79.33 is better (232."; var output = str.replace( /\(\d+(\.(\d)+)?(?!=\))/g, r => r + ")"); ``` **Output** > > solve this now Math.sqrt(345.5)+6 is good but Math.sin(79.33) is better (232). > > > **Demo** ```js var str = "solve this now Math.sqrt(345.5+6 is good but Math.sin(79.33 is better (232."; var output = str.replace( /\(\d+(\.(\d)+)?(?!=\))/g, r => r + ")"); console.log(output); ``` Upvotes: 0
2018/03/15
833
1,955
<issue_start>username_0: I need to shape versions in a specific format. For instance: ``` V1=1.0.1 V2=4.0.1 V3=3.1.101 ... ``` Need to be pad with 0 as follow: ``` V1=001.000.001.000 V2=004.000.001.000 V3=003.001.101.000 ... ``` Any idea on how i can do that? EDIT: I succeed using printf as follow: ``` printf "%03d.%03d.%03d.000\n" $(echo $V3 | grep -o '[^-]*$' | cut -d. -f1) $(echo $V3 | grep -o '[^-]*$' | cut -d. -f2) $(echo $V3 | grep -o '[^-]*$' | cut -d. -f3) ``` output: ``` 003.001.101.000 ``` Any better suggestions ?<issue_comment>username_1: Use negative lookahead assertion. ```js var str = "solve this now Math.sqrt(345+6 is good but Math.sin(79 is better."; console.log(str.replace(/(\(\d+)\b(?!\))/g, "$1)")) ``` `(\(\d+)` capture `\(` and one or more digits `(?!\))` only if the match wasn't followed by closing brace `)` Upvotes: 1 <issue_comment>username_2: Check if the an opening brace if followed by numbers, but not by its closing brace after numbers ``` var str = "solve this now Math.sqrt(345+6 is good but Math.sin(79 is better."; var output = str.replace( /\([\d]+(?!=\))/g, r => r + ")"); ``` **Output** > > solve this now Math.sqrt(345)+6 is good but Math.sin(79) is better. > > > **Demo** ```js var str = "solve this now Math.sqrt(345+6 is good but Math.sin(79 is better."; var output = str.replace(/\([\d]+(?!=\))/g, r => r + ")"); console.log(output); ``` You can include `.` to allow decimals as well ``` var str = "solve this now Math.sqrt(345.5+6 is good but Math.sin(79.33 is better (232."; var output = str.replace( /\(\d+(\.(\d)+)?(?!=\))/g, r => r + ")"); ``` **Output** > > solve this now Math.sqrt(345.5)+6 is good but Math.sin(79.33) is better (232). > > > **Demo** ```js var str = "solve this now Math.sqrt(345.5+6 is good but Math.sin(79.33 is better (232."; var output = str.replace( /\(\d+(\.(\d)+)?(?!=\))/g, r => r + ")"); console.log(output); ``` Upvotes: 0
2018/03/15
585
1,614
<issue_start>username_0: How does rolling update work in kubernetes internally. Is it one pod after another. will the update get stuck or takes time if one of the pod goes to error state during the update<issue_comment>username_1: Use negative lookahead assertion. ```js var str = "solve this now Math.sqrt(345+6 is good but Math.sin(79 is better."; console.log(str.replace(/(\(\d+)\b(?!\))/g, "$1)")) ``` `(\(\d+)` capture `\(` and one or more digits `(?!\))` only if the match wasn't followed by closing brace `)` Upvotes: 1 <issue_comment>username_2: Check if the an opening brace if followed by numbers, but not by its closing brace after numbers ``` var str = "solve this now Math.sqrt(345+6 is good but Math.sin(79 is better."; var output = str.replace( /\([\d]+(?!=\))/g, r => r + ")"); ``` **Output** > > solve this now Math.sqrt(345)+6 is good but Math.sin(79) is better. > > > **Demo** ```js var str = "solve this now Math.sqrt(345+6 is good but Math.sin(79 is better."; var output = str.replace(/\([\d]+(?!=\))/g, r => r + ")"); console.log(output); ``` You can include `.` to allow decimals as well ``` var str = "solve this now Math.sqrt(345.5+6 is good but Math.sin(79.33 is better (232."; var output = str.replace( /\(\d+(\.(\d)+)?(?!=\))/g, r => r + ")"); ``` **Output** > > solve this now Math.sqrt(345.5)+6 is good but Math.sin(79.33) is better (232). > > > **Demo** ```js var str = "solve this now Math.sqrt(345.5+6 is good but Math.sin(79.33 is better (232."; var output = str.replace( /\(\d+(\.(\d)+)?(?!=\))/g, r => r + ")"); console.log(output); ``` Upvotes: 0
2018/03/15
758
2,702
<issue_start>username_0: Xamarin App Deployment failing with error "apksigner.BAT" exited with code 2 . JDK version 1.8.162<issue_comment>username_1: Try downgrading the JDK to 1.8.131. i faced the problems with 1.8.161 and 1.8.162. If u are using JDK 9, then downgrade to JDK-8 Upvotes: 3 [selected_answer]<issue_comment>username_2: Uninstalling JDK 9.x fixed it for me. That Android Settings were pointing a JDK 8.x made no difference. JDK 9.x had to be removed to fix the issue. Upvotes: 1 <issue_comment>username_3: I got the same error when building a Xamarin.Android app on Visual Studio. It was caused by having migrated my keystore from JKS to PKCS12 format because `keytool.exe -list -v -keystore` kept giving me the following `Warning: The JKS keystore uses a proprietary format. It is recommended to migrate to PKCS12 which is an industry standard format`. Bad idea to migrate, it appears `apksigner.BAT` requires the keystore be in the JKS format. I solved this issue by reverting back to my `debug.keystore.old` Upvotes: 0 <issue_comment>username_4: In addition to **JDK** related answers above which is correct, also try to check PATH variable. There have to be latest installed JDK version. Solved my problem after days of checking different IDE's, machines and devices. Upvotes: 0 <issue_comment>username_5: As others found, it's a conflict that occurs when you have a newer version of Java installed, such as JDK 9. This shouldn't really be necessary but here is a workaround: Create a new batch file with the below content (update paths as necessary). You want to set JAVA\_HOME so it points to the older version of Java. **Xamarin.bat:** ``` @echo off set JAVA_HOME=C:\Program Files (x86)\Java\jdk1.8.0_161 set PATH=%JAVA_HOME%\bin;%PATH% cd "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\" start devenv.exe ``` Upvotes: 0 <issue_comment>username_6: I recently get an old poject from a client. It was giving same `error` in `Visual Studio for Windows`. In `Visual Studio for Mac` it was giving 1 error `without displaying` any `Error Message`. The reason `behind` the `error` was that the client have specified a `signing key` which is `not available` on my `system`. On `Mac` I just have to `uncheck` the `apk signing` option. while on `Windows` I have to `edit` the `csproj` file to remove the `signing key`. Now the project builds successfully. Upvotes: 0 <issue_comment>username_7: For me worked removing (or renaming) apksigner.bat from my current build tools directory (...AppData\Local\Android\android-sdk\build-tools\28.0.0-rc1\apksigner.bat) After then, cleaned obj and Debug/Release directory->Rebuild->Deploy Upvotes: 0
2018/03/15
391
1,177
<issue_start>username_0: I have table with the fields `Amount, Condition1, Condition2`. Example: ``` Amount Condition1 Condition2 ---------------------------------- 123 Yes Yes 234 No Yes 900 Yes No ``` I want to calculate the 20% of the amount based on condition: If both `Condition1` and `Condition2` is Yes then calculate `20%` else `0`. **My try**: I tried with conditional custom column but unable to add `AND` in `IF` in the query editor.<issue_comment>username_1: Try to create a new calculated column. And Use below DAX query: ``` new_column = IF(Conditition1 = "Yes", IF(Condititon2 = "Yes",Amt * 0.2 ,0), 0) ``` Upvotes: 2 <issue_comment>username_2: You can write a conditional column like this: ``` = IF(AND(Table1[Condition1] = "Yes", Table1[Condition2] = "Yes"), 0.2 * Table1[Amount], 0) ``` Or you can use `&&` instead of the `AND` function: ``` = IF(Table1[Condition1] = "Yes" && Table1[Condition2] = "Yes", 0.2 * Table1[Amount], 0) ``` Or an even shorter version using concatenation: ``` = IF(Table1[Condition1] & Table1[Condition2] = "YesYes", 0.2 * Table1[Amount], 0) ``` Upvotes: 3 [selected_answer]
2018/03/15
203
668
<issue_start>username_0: How can I capitalize the first letter of a string using Angular or typescript?<issue_comment>username_1: ``` var str = 'santosh'; str = str ? str.charAt(0).toUpperCase() + str.substr(1).toLowerCase() : ''; ``` Upvotes: 2 <issue_comment>username_2: ``` let str:string = 'hello'; str = str[0].toUpperCase() + str.slice(1); ``` Upvotes: 4 <issue_comment>username_3: ```js function titleCaseWord(word: string) { if (!word) return word; return word[0].toUpperCase() + word.substr(1).toLowerCase(); } ``` You can also use in template **TitleCasePipe** Some component template: ```js {{value |titlecase}} ``` Upvotes: 8 [selected_answer]
2018/03/15
1,255
4,320
<issue_start>username_0: I try to receive token via POST json {"email":"<EMAIL>","password":"<PASSWORD>"}. In postman it works: [Postman request](https://i.stack.imgur.com/b6J3J.png). I try do the same in Android Studio. I create class Token: ``` public class Token { @SerializedName("token") @Expose public String token; } ``` And class APIclient ``` class APIClient { private static Retrofit retrofit = null; static Retrofit getClient() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build(); retrofit = new Retrofit.Builder() .baseUrl("http://mybaseurl.com/") .addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); return retrofit; } } ``` and interface APIInterface: ``` interface APIInterface { @POST("/authenticate") Call getLoginResponse(@Body AuthenticationRequest request); } ``` and class AuthenticationRequest: ``` public class AuthenticationRequest { String email; String password; } ``` In onCreate in MainActivity: ``` apiInterface = APIClient.getClient().create(APIInterface.class); authenticationRequest.email="<EMAIL>"; authenticationRequest.password="<PASSWORD>"; getTokenResponse(); ``` And here is my getTokenResponse method: ``` private void getTokenResponse() { Call call2 = apiInterface.getLoginResponse(authenticationRequest); call2.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { Token token = response.body(); } @Override public void onFailure(Call call, Throwable t) { call.cancel(); } }); } ``` And this is what I see in Logcat: ``` 03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: --> POST http://mybaseurl.com/authenticate http/1.1 03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: Content-Type: application/json; charset=UTF-8 03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: Content-Length: 46 03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: {"email":"<EMAIL>","password":"<PASSWORD>"} 03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: --> END POST (46-byte body) ``` Could you tell me what I'm doing wrong? I need to give token every time when I'd like to get information from server via GET method. How can I receive and save token in Android code?<issue_comment>username_1: you should add `application/json` to header ``` interface APIInterface { @Headers({"Content-Type: application/json", "Accept: application/json"}) @POST("/authenticate") Call getLoginResponse(@Body AuthenticationRequest request); } ``` Upvotes: 2 <issue_comment>username_2: Try this ``` interface APIInterface { @POST("/authenticate") Call getLoginResponse(@Header("Authorization") String token, @Body AuthenticationRequest request); } ``` `token` is the `Bearer token` Upvotes: 2 <issue_comment>username_3: To get access token from you need to get header from response and read values from headers. ``` Callback user = new Callback() { @Override public void success(User user, Response response) { List headerList = response.getHeaders(); //iterating list of header and printing key/value. for(Header header : headerList) { Log.d(TAG, header.getName() + " " + header.getValue()); } } } ``` After you get the value you need from header i.e. `AccessToken`, you can store that value in Storage. e.g. `SharedPreference` So next time when you need that value you can directly get that from Storage. e.g. `SharedPreference` Now when you pass request for any webservice either that is `GET` or `POST` or any other method. You have to pass that into header requests. ``` @GET("/tasks") Call> getTasks(@Header("Content-Range") String contentRange); ``` Or If you need to pass it every time, you can directly pass that from your `Retrofit` class. ``` Request request = original.newBuilder() .header("User-Agent", "Your-App-Name") .header("Accept", "application/vnd.yourapi.v1.full+json") .method(original.method(), original.body()) .build(); ``` Upvotes: 0
2018/03/15
615
2,291
<issue_start>username_0: I am using the SSIS package to read the data from the flat file and then push the data to the SQL Server db. But some of the incoming columns are containing the blank spaces and i would like to trim them. I am unable to understand how to perform this small task of column trimmming inside the data flow of the SSIS package. Please suggest how to make this change. SSIS Package version 2014 IDE :- VS.NET 2017 [![enter image description here](https://i.stack.imgur.com/WaraV.png)](https://i.stack.imgur.com/WaraV.png)<issue_comment>username_1: you should add `application/json` to header ``` interface APIInterface { @Headers({"Content-Type: application/json", "Accept: application/json"}) @POST("/authenticate") Call getLoginResponse(@Body AuthenticationRequest request); } ``` Upvotes: 2 <issue_comment>username_2: Try this ``` interface APIInterface { @POST("/authenticate") Call getLoginResponse(@Header("Authorization") String token, @Body AuthenticationRequest request); } ``` `token` is the `Bearer token` Upvotes: 2 <issue_comment>username_3: To get access token from you need to get header from response and read values from headers. ``` Callback user = new Callback() { @Override public void success(User user, Response response) { List headerList = response.getHeaders(); //iterating list of header and printing key/value. for(Header header : headerList) { Log.d(TAG, header.getName() + " " + header.getValue()); } } } ``` After you get the value you need from header i.e. `AccessToken`, you can store that value in Storage. e.g. `SharedPreference` So next time when you need that value you can directly get that from Storage. e.g. `SharedPreference` Now when you pass request for any webservice either that is `GET` or `POST` or any other method. You have to pass that into header requests. ``` @GET("/tasks") Call> getTasks(@Header("Content-Range") String contentRange); ``` Or If you need to pass it every time, you can directly pass that from your `Retrofit` class. ``` Request request = original.newBuilder() .header("User-Agent", "Your-App-Name") .header("Accept", "application/vnd.yourapi.v1.full+json") .method(original.method(), original.body()) .build(); ``` Upvotes: 0
2018/03/15
588
2,344
<issue_start>username_0: I have a dynamically created form with all inputs. I am subscribing for changes, but when a control is changed I get the values from all the controls, so I don't really know which one is changed. Is it possible to get the changed value only from the changed control with the valueChanges function? The form is pretty big, so subscribing every control to valueChanges is not an option. The function currently looks like this: ``` checkForValueChanges() { this.metadataForm.valueChanges.subscribe(controls => { // how to get the changed control form name here ? }); } ``` Since the project is really big, I just made a simple example to show my issue: [StackBlitz example](https://stackblitz.com/edit/angular-reactive-forms?embed=1&file=app/app.component.ts) You can see in console that the result I get is all of the controls instead of just the one it's changed.<issue_comment>username_1: The cleanest way I can imagine is to subscribe dynamicaly to all the form controls : ``` const subscriptions = []; for (const key of Object.keys(this.metadataForm.controls)) { const subscription = this.metadataForm.controls[key].valueChanges .subscribe(value => console.log('value :' + value[key] + ' and key : ' + key)); subscriptions.push(subscription); } ``` I added an array of subscriptions to handle the unsubscribe on destroy. Upvotes: 3 <issue_comment>username_2: ``` this.imagSub = this.imagingForm.valueChanges.pipe( pairwise(), map(([oldState, newState]) => { let changes = {}; for (const key in newState) { if (oldState[key] !== newState[key] && oldState[key] !== undefined) { changes[key] = newState[key]; } } return changes; }), filter(changes => Object.keys(changes).length !== 0 && !this.imagingForm.invalid) ).subscribe( value => { console.log("Form has changed:", value); } ); ``` That subscription became active on ngOnInit and download some data from API (and after that put them into a form field, so I don't need first value [and value == undefined], because of form setting fields by herself) For me, that solution works fine. But I guess if you have a form with "that has a huge amount of fields", this method will be even worse than saving subscriptions. Upvotes: 2
2018/03/15
382
1,297
<issue_start>username_0: I have a : ```css select:invalid { color: red; } ``` ```html - please choose - A B ``` Unfortunately the disabled select is not marked red. Any idea? It's not the option I like to style, I like to style the select! ----------------------------------------------------------------<issue_comment>username_1: Try to use `option:disabled`. ```css select option:disabled { color: red; } ``` ```html - please choose - A B ``` Upvotes: 1 <issue_comment>username_2: ```css .choose_elements{ background-color : red; } .elements{ background-color : white; } ``` ```html - please choose - A B ``` Upvotes: 0 <issue_comment>username_3: You need to specify **`value=""`** for the first option. Without `value=""`, the value of an option is implicitly equal to its *text content*, meaning it fulfils the `required` constraint. Demo: ```css select:invalid { color: red; } ``` ```html - please choose - A B ``` The above will make the **select + all options** red until a value has been chosen. If you want the **options** to *always* be black, just extend the CSS a little: ```css select:invalid { color: red; } select option { color: black; } ``` ```html - please choose - A B ``` Upvotes: 5 [selected_answer]
2018/03/15
1,332
5,192
<issue_start>username_0: I'm writing a basic application to test the Interactive Queries feature of Kafka Streams. Here is the code: ``` public static void main(String[] args) { StreamsBuilder builder = new StreamsBuilder(); KeyValueBytesStoreSupplier waypointsStoreSupplier = Stores.persistentKeyValueStore("test-store"); StoreBuilder waypointsStoreBuilder = Stores.keyValueStoreBuilder(waypointsStoreSupplier, Serdes.ByteArray(), Serdes.Integer()); final KStream waypointsStream = builder.stream("sample1"); final KStream waypointsDeserialized = waypointsStream .mapValues(CustomSerdes::deserializeTruckDriverWaypoint) .filter((k,v) -> v.isPresent()) .mapValues(Optional::get); waypointsDeserialized.groupByKey().aggregate( () -> 1, (aggKey, newWaypoint, aggValue) -> { aggValue = aggValue + 1; return aggValue; }, Materialized.>as("test-store").withKeySerde(Serdes.ByteArray()).withValueSerde(Serdes.Integer()) ); final KafkaStreams streams = new KafkaStreams(builder.build(), new StreamsConfig(createStreamsProperties())); streams.cleanUp(); streams.start(); ReadOnlyKeyValueStore keyValueStore = streams.store("test-store", QueryableStoreTypes.keyValueStore()); KeyValueIterator range = keyValueStore.all(); while (range.hasNext()) { KeyValue next = range.next(); System.out.println(next.value); } Runtime.getRuntime().addShutdownHook(new Thread(streams::close)); } protected static Properties createStreamsProperties() { final Properties streamsConfiguration = new Properties(); streamsConfiguration.put(StreamsConfig.APPLICATION\_ID\_CONFIG, "random167"); streamsConfiguration.put(StreamsConfig.CLIENT\_ID\_CONFIG, "client-id"); streamsConfiguration.put(StreamsConfig.BOOTSTRAP\_SERVERS\_CONFIG, "localhost:9092"); streamsConfiguration.put(ConsumerConfig.AUTO\_OFFSET\_RESET\_CONFIG, "earliest"); streamsConfiguration.put(ConsumerConfig.KEY\_DESERIALIZER\_CLASS\_CONFIG, Serdes.String().getClass().getName()); streamsConfiguration.put(ConsumerConfig.VALUE\_DESERIALIZER\_CLASS\_CONFIG, Serdes.Integer().getClass().getName()); //streamsConfiguration.put(StreamsConfig.COMMIT\_INTERVAL\_MS\_CONFIG, 10000); return streamsConfiguration; } ``` So my problem is, every time I run this I get this same error: > > Exception in thread "main" org.apache.kafka.streams.errors.InvalidStateStoreException: the state store, test-store, may have migrated to another instance. > > > I'm running only 1 instance of the application, and the topic I'm consuming from has only 1 partition. Any idea what I'm doing wrong ?<issue_comment>username_1: Looks like you have a race condition. From the kafka streams javadoc for `KafkaStreams::start()` it says: > > Start the KafkaStreams instance by starting all its threads. This function is expected to be called only once during the life cycle of the client. > Because threads are started in the background, this method does not block. > > > <https://kafka.apache.org/10/javadoc/index.html?org/apache/kafka/streams/KafkaStreams.html> You're calling `streams.store()` immediately after `streams.start()`, but I'd wager that you're in a state where it hasn't initialized fully yet. Since this is code appears to be just for testing, add a `Thread.sleep(5000)` or something in there and give it a go. (This is not a solution for production) Depending on your input rate into the topic, that'll probably give a bit of time for the store to start filling up with events so that your `KeyValueIterator` actually has something to process/print. Upvotes: 4 <issue_comment>username_2: Probably not applicable to OP but might help others: In trying to retrieve a KTable's store, make sure the the KTable's topic exists first or you'll get this exception. Upvotes: 2 <issue_comment>username_3: I failed to call `Storebuilder` before consuming the store. Upvotes: 0 <issue_comment>username_4: > > Typically this happens for two reasons: > > > The local KafkaStreams instance is not yet ready (i.e., not yet in > runtime state RUNNING, see Run-time Status Information) and thus its > local state stores cannot be queried yet. The local KafkaStreams > instance is ready (e.g. in runtime state RUNNING), but the particular > state store was just migrated to another instance behind the scenes. > This may notably happen during the startup phase of a distributed > application or when you are adding/removing application instances. > > > <https://docs.confluent.io/platform/current/streams/faq.html#handling-invalidstatestoreexception-the-state-store-may-have-migrated-to-another-instance> The simplest approach is to guard against InvalidStateStoreException when calling KafkaStreams#store(): ``` // Example: Wait until the store of type T is queryable. When it is, return a reference to the store. public static T waitUntilStoreIsQueryable(final String storeName, final QueryableStoreType queryableStoreType, final KafkaStreams streams) throws InterruptedException { while (true) { try { return streams.store(storeName, queryableStoreType); } catch (InvalidStateStoreException ignored) { // store not yet ready for querying Thread.sleep(100); } } } ``` Upvotes: 0
2018/03/15
963
3,342
<issue_start>username_0: **My Original URL** > > <http://www.mcoh.co.in/blog-single?category=Blog&id=Janurary%202018%20Product%20training%20Scores> > > > **and Expecting in:** > > <http://www.mcoh.co.in/mcohBlog/Janurary%202018%20Product%20training%20Scores> > > > But Am receiving same url as original. ``` ## hide .php extension # To externally redirect /dir/foo.php to /dir/foo RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC] RewriteRule ^ %1 [R,L,NC] ## To internally redirect /dir/foo to /dir/foo.php RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^ %{REQUEST_URI}.php [L] Options +FollowSymLinks -MultiViews RewriteEngine On RewriteRule ^mcoh([^/]*)/([^/]*)\$ /blog-single?category=$1&id=$2 [L] ```<issue_comment>username_1: Looks like you have a race condition. From the kafka streams javadoc for `KafkaStreams::start()` it says: > > Start the KafkaStreams instance by starting all its threads. This function is expected to be called only once during the life cycle of the client. > Because threads are started in the background, this method does not block. > > > <https://kafka.apache.org/10/javadoc/index.html?org/apache/kafka/streams/KafkaStreams.html> You're calling `streams.store()` immediately after `streams.start()`, but I'd wager that you're in a state where it hasn't initialized fully yet. Since this is code appears to be just for testing, add a `Thread.sleep(5000)` or something in there and give it a go. (This is not a solution for production) Depending on your input rate into the topic, that'll probably give a bit of time for the store to start filling up with events so that your `KeyValueIterator` actually has something to process/print. Upvotes: 4 <issue_comment>username_2: Probably not applicable to OP but might help others: In trying to retrieve a KTable's store, make sure the the KTable's topic exists first or you'll get this exception. Upvotes: 2 <issue_comment>username_3: I failed to call `Storebuilder` before consuming the store. Upvotes: 0 <issue_comment>username_4: > > Typically this happens for two reasons: > > > The local KafkaStreams instance is not yet ready (i.e., not yet in > runtime state RUNNING, see Run-time Status Information) and thus its > local state stores cannot be queried yet. The local KafkaStreams > instance is ready (e.g. in runtime state RUNNING), but the particular > state store was just migrated to another instance behind the scenes. > This may notably happen during the startup phase of a distributed > application or when you are adding/removing application instances. > > > <https://docs.confluent.io/platform/current/streams/faq.html#handling-invalidstatestoreexception-the-state-store-may-have-migrated-to-another-instance> The simplest approach is to guard against InvalidStateStoreException when calling KafkaStreams#store(): ``` // Example: Wait until the store of type T is queryable. When it is, return a reference to the store. public static T waitUntilStoreIsQueryable(final String storeName, final QueryableStoreType queryableStoreType, final KafkaStreams streams) throws InterruptedException { while (true) { try { return streams.store(storeName, queryableStoreType); } catch (InvalidStateStoreException ignored) { // store not yet ready for querying Thread.sleep(100); } } } ``` Upvotes: 0
2018/03/15
488
1,539
<issue_start>username_0: I have the following groovy dependency declared: ``` @GrabResolver(name='mymirror', root='http://myartifactory/public/') @Grab(group='groupid', module='artifactid', version='1.2.3') println //What should I write here to see: c:\Users....m2....artifactid.jar ``` How can I get the location of the downloaded resolved artifact in groovy?<issue_comment>username_1: By default, [Grape](http://docs.groovy-lang.org/latest/html/documentation/grape.html#Grape-Detail) stores a cache of the jars on `~/.groovy/grapes`. So, I think you can do something like this: ``` @GrabResolver(name='mymirror', root='http://myartifactory/public/') @Grab(group='groupid', module='artifactid', version='1.2.3') String grapeCacheDir = "${System.getProperty('user.home')}/.groovy/grapes" String group = 'groupid' String module = 'artifactid' String version = '1.2.3' File myJar = new File("$grapeCacheDir/$group/$module/jars/${module}-${version}.jar") println myJar.path ``` It's not a preety solution, but I can't think in any other options. Upvotes: 1 <issue_comment>username_2: ``` @Grab(group='net.sourceforge.plantuml', module='plantuml', version='8049') import groovy.grape.Grape def grape = Grape.getInstance() def r = grape.listDependencies(this.getClass().getClassLoader()) println r println grape.resolve(r[0]) ``` prints ``` [[group:net.sourceforge.plantuml, module:plantuml, version:8049]] [file:/C:/Users/dm/.groovy/grapes/net.sourceforge.plantuml/plantuml/jars/plantuml-8049.jar] ``` Upvotes: 3 [selected_answer]
2018/03/15
542
1,732
<issue_start>username_0: I have a R dataframe like this: ``` ID Event Out A 0 0 A 1 1 A 1 1 A 0 0 A 1 2 B 1 3 B 0 0 C 1 4 C 1 4 C 1 4 ``` I am trying to create the `out` field which is a sequential conditional (on event =1 or not) repeated index. The index needs to increment by 1 with every new group occurrence of the event but carrying on in the sequence from the previous group. Is there a `plyr` option for this. Thanks in advance.<issue_comment>username_1: By default, [Grape](http://docs.groovy-lang.org/latest/html/documentation/grape.html#Grape-Detail) stores a cache of the jars on `~/.groovy/grapes`. So, I think you can do something like this: ``` @GrabResolver(name='mymirror', root='http://myartifactory/public/') @Grab(group='groupid', module='artifactid', version='1.2.3') String grapeCacheDir = "${System.getProperty('user.home')}/.groovy/grapes" String group = 'groupid' String module = 'artifactid' String version = '1.2.3' File myJar = new File("$grapeCacheDir/$group/$module/jars/${module}-${version}.jar") println myJar.path ``` It's not a preety solution, but I can't think in any other options. Upvotes: 1 <issue_comment>username_2: ``` @Grab(group='net.sourceforge.plantuml', module='plantuml', version='8049') import groovy.grape.Grape def grape = Grape.getInstance() def r = grape.listDependencies(this.getClass().getClassLoader()) println r println grape.resolve(r[0]) ``` prints ``` [[group:net.sourceforge.plantuml, module:plantuml, version:8049]] [file:/C:/Users/dm/.groovy/grapes/net.sourceforge.plantuml/plantuml/jars/plantuml-8049.jar] ``` Upvotes: 3 [selected_answer]
2018/03/15
450
1,477
<issue_start>username_0: I would like to retrieve the names of people who didn't work on a project in PostgreSQL. I got a table named `employees` with their `names` and `ssn`. My second table is called `works_on` and includes `ssn` and `project_number` `ssn` here is a `foreign key` from `employees` Now I tried the following: ``` SELECT fname,lname FROM werknemer w JOIN werkt_aan wa ON (wa.ssn = w.ssn) WHERE wa.ssn <> w.ssn ``` But this returns nothing, but I need 1 name who is not working on a single project. Can someone explain to me how to do this? Thanks in advance.<issue_comment>username_1: This is usually solved using a `NOT EXISTS` query: ``` select e.* from employees e where not exists (select * from works_on wo where wo.ssn = e.ssn) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: try this ``` SELECT fname,lname FROM werknemer w WHere w.snn not in (Select wa.ssn from werkt_aan wa) ``` Upvotes: 1 <issue_comment>username_3: you'll need to use NOT IN and a subquery here Upvotes: 1 <issue_comment>username_4: This is easy with `NOT IN`: ``` select * from employees where ssn not in (select ssn from works_on) ``` Alternative with `LEFT JOIN`: ``` SELECT fname,lname FROM employee w LEFT JOIN works_on wa ON (wa.ssn = w.ssn) WHERE wa.ssn IS NULL ``` This alternative is useful as you sometimes have more complicated requirements that can't easily be expressed with `IN` or `EXISTS`. Upvotes: 2
2018/03/15
1,194
3,611
<issue_start>username_0: Is there any package in Python that provides a dictionary for vectorized access with NumPy arrays? I am looking for something like this: ``` >>> vector_dict = VectorizedDict({1: "One", ... 2: "Two", ... 3: "Three"}, ... dtype_key=int, dtype_val="U5") >>> a = np.array([1,2,3]), >>> b = vector_dict[a] >>> print(type(b)) np.ndarray >>> print(b) ["One", "Two", "Three"] ``` Although this result would also be possible to achieve by iterating over the array elements, the iteration approach would be rather inefficient for large arrays. EDIT: For small dictionaries I use the following approach: ``` for key, val in my_dict.items(): b[a == key] = val ``` Although the boolean masking is quite efficient when iterating over small dictionaries, it is time consuming for large dictionaries (thousands of key-value-paris).<issue_comment>username_1: [Pandas](https://pandas.pydata.org) data structures implement this functionality for 1D ([`pd.Series`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html)), 2D ([`pd.DataFrame`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html)) and 3D ([`pd.Panel`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Panel.html)) data: ``` import numpy as np import pandas as pd s = pd.Series(data=['One', 'Two', 'Three'], index=[1, 2, 3]) a = np.array([1, 2, 3]) b = s[a] print(b.values) ['One' 'Two' 'Three'] ``` For higher-dimensional structures, you have [xarray](https://xarray.pydata.org/). Upvotes: 3 <issue_comment>username_2: Here are two approaches - ``` def lookup_dict_app1(vector_dict, a): k = np.array(list(vector_dict.keys())) v = np.array(list(vector_dict.values())) sidx = k.argsort() return v[sidx[np.searchsorted(k,a,sorter=sidx)]].tolist() def lookup_dict_app2(vector_dict, a): k = np.array(list(vector_dict.keys())) v = vector_dict.values() sidx = k.argsort() indx = sidx[np.searchsorted(k,a,sorter=sidx)] out = [v[i] for i in indx] return out ``` If the keys obtained with `vector_dict.keys()` are already sorted, skip the `argsort()` and indexing with `sidx` steps. Or, we can do a simple check and get the modified versions, like so - ``` def lookup_dict_app1_mod(vector_dict, a): k = np.array(list(vector_dict.keys())) v = np.array(list(vector_dict.values())) if (k[1:] >= k[:-1]).all(): return v[np.searchsorted(k,a)].tolist() else: sidx = k.argsort() return v[sidx[np.searchsorted(k,a,sorter=sidx)]].tolist() def lookup_dict_app2_mod(vector_dict, a): k = np.array(list(vector_dict.keys())) v = vector_dict.values() if (k[1:] >= k[:-1]).all(): return [v[i] for i in np.searchsorted(k,a)] else: sidx = k.argsort() indx = sidx[np.searchsorted(k,a,sorter=sidx)] return [v[i] for i in indx] ``` Sample run - ``` In [166]: vector_dict = {1: 'One', 2: 'Two', 3: 'Three', 0:'Zero'} In [167]: a = np.array([1,2,3,2,3,1]) In [168]: lookup_dict_app1(vector_dict, a) Out[168]: ['One', 'Two', 'Three', 'Two', 'Three', 'One'] In [169]: lookup_dict_app2(vector_dict, a) Out[169]: ['One', 'Two', 'Three', 'Two', 'Three', 'One'] ``` Upvotes: 2 <issue_comment>username_3: I have written a vectorized python dictionary/set that efficiently stores data and uses numpy arrays. Most combinations of numpy datatypes are supported. You can find the project and documentation here: <https://github.com/atom-moyer/getpy> Upvotes: 3 [selected_answer]
2018/03/15
415
1,669
<issue_start>username_0: I have a cloud function that translates text using google translate api. It utilizes this piece of code: ``` const functions = require('firebase-functions'); function createTranslateUrl(lang, text) { return `https://www.googleapis.com/language/translate/v2?key=${functions.config().firebase.apiKey}&source=en⌖=${lang}&q=${text}`; } ``` The problem is in `functions.config().firebase.apiKey` part. For some time it worked fine but suddenly it started to return `undefined`. Here's how the config looks like now: ``` config { firebase: { projectId: 'projectname', databaseURL: 'https://projectname.firebaseio.com', storageBucket: 'projectname.appspot.com', credential: ApplicationDefaultCredential { credential_: MetadataServiceCredential {} } } } ``` I hardcoded the apiKey copying it from firebase console and it works fine for now. My questions are is it safe to use hardcoded api key? And what might cause `functions.config().firebase.apiKey` to return undefined?<issue_comment>username_1: Any luck with this? I'm having exact same issue where `functions.config().firebase.apiKey` is returning `undefined`. This started happening after my deployment yesterday. I did check [firebase release notes](https://firebase.google.com/support/releases) but nothing related to config there. UPDATE: It turns out there we were using old version of `firebase-functions`. Upgrading to latest version (`0.9.1`) fixed issues. Upvotes: 0 <issue_comment>username_2: `firebase.apiKey` was dropped from `functions.config()` See also this issue on github <https://github.com/firebase/firebase-functions/issues/196> Upvotes: 1
2018/03/15
3,453
7,329
<issue_start>username_0: I have an unknown number `n` of variables that can range from 0 to 1 with some known step `s`, with the condition that they sum up to 1. I want to create a matrix of all combinations. For example, if `n=3` and `s=0.33333` then the grid will be (The order is not important): ``` 0.00, 0.00, 1.00 0.00, 0.33, 0.67 0.00, 0.67, 0.33 0.00, 1.00, 0.00 0.33, 0.00, 0.67 0.33, 0.33, 0.33 0.33, 0.67, 0.00 0.67, 0.00, 0.33 0.67, 0.33, 0.00 1.00, 0.00, 0.00 ``` How can I do that for an arbitrary `n`?<issue_comment>username_1: *EDIT* Here is a better solution. It basically [partitions](https://en.wikipedia.org/wiki/Partition_(number_theory)) the number of steps into the amount of variables to generate all the valid combinations: ``` def partitions(n, k): if n < 0: return -partitions(-n, k) if k <= 0: raise ValueError('Number of partitions must be positive') if k == 1: return np.array([[n]]) ranges = np.array([np.arange(i + 1) for i in range(n + 1)]) parts = ranges[-1].reshape((-1, 1)) s = ranges[-1] for _ in range(1, k - 1): d = n - s new_col = np.concatenate(ranges[d]) parts = np.repeat(parts, d + 1, axis=0) s = np.repeat(s, d + 1) + new_col parts = np.append(parts, new_col.reshape((-1, 1)), axis=1) return np.append(parts, (n - s).reshape((-1, 1)), axis=1) def make_grid_part(n, step): num_steps = round(1.0 / step) return partitions(num_steps, n) / float(num_steps) print(make_grid_part(3, 0.33333)) ``` Output: ``` array([[ 0. , 0. , 1. ], [ 0. , 0.33333333, 0.66666667], [ 0. , 0.66666667, 0.33333333], [ 0. , 1. , 0. ], [ 0.33333333, 0. , 0.66666667], [ 0.33333333, 0.33333333, 0.33333333], [ 0.33333333, 0.66666667, 0. ], [ 0.66666667, 0. , 0.33333333], [ 0.66666667, 0.33333333, 0. ], [ 1. , 0. , 0. ]]) ``` For comparison: ``` %timeit make_grid_part(5, .1) >>> 338 µs ± 2.25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %timeit make_grid_simple(5, .1) >>> 26.4 ms ± 806 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) ``` `make_grid_simple` actually runs out of memory if you push it just a bit further. --- Here is one simple way: ``` def make_grid_simple(n, step): num_steps = round(1.0 / step) vs = np.meshgrid(*([np.linspace(0, 1, num_steps + 1)] * n)) all_combs = np.stack([v.flatten() for v in vs], axis=1) return all_combs[np.isclose(all_combs.sum(axis=1), 1)] print(make_grid_simple(3, 0.33333)) ``` Output: ``` [[ 0. 0. 1. ] [ 0.33333333 0. 0.66666667] [ 0.66666667 0. 0.33333333] [ 1. 0. 0. ] [ 0. 0.33333333 0.66666667] [ 0.33333333 0.33333333 0.33333333] [ 0.66666667 0.33333333 0. ] [ 0. 0.66666667 0.33333333] [ 0.33333333 0.66666667 0. ] [ 0. 1. 0. ]] ``` However, this is not the most efficient way to do it, since it is simply making all the possible combinations and then just picking the ones that add up to 1, instead of generating only the right ones in the first place. For small step sizes, it may incur in too high memory cost. Upvotes: 2 [selected_answer]<issue_comment>username_2: Assuming that they always add up to 1, as you said: ``` import itertools def make_grid(n): # setup all possible values in one position p = [(float(1)/n)*i for i in range(n+1)] # combine values, filter by sum()==1 return [x for x in itertools.product(p, repeat=n) if sum(x) == 1] print(make_grid(n=3)) #[(0.0, 0.0, 1.0), # (0.0, 0.3333333333333333, 0.6666666666666666), # (0.0, 0.6666666666666666, 0.3333333333333333), # (0.0, 1.0, 0.0), # (0.3333333333333333, 0.0, 0.6666666666666666), # (0.3333333333333333, 0.3333333333333333, 0.3333333333333333), # (0.3333333333333333, 0.6666666666666666, 0.0), # (0.6666666666666666, 0.0, 0.3333333333333333), # (0.6666666666666666, 0.3333333333333333, 0.0), # (1.0, 0.0, 0.0)] ``` Upvotes: 1 <issue_comment>username_3: We can think of this as a problem of dividing some fixed number of things (1/s in this case and represented using `sum_left` parameter) between some given number of bins (n in this case). The most efficient way I can think of doing this is using a recursion: ``` In [31]: arr = [] In [32]: def fun(n, sum_left, arr_till_now): ...: if n==1: ...: n_arr = list(arr_till_now) ...: n_arr.append(sum_left) ...: arr.append(n_arr) ...: else: ...: for i in range(sum_left+1): ...: n_arr = list(arr_till_now) ...: n_arr.append(i) ...: fun(n-1, sum_left-i, n_arr) ``` This would give an output like: ``` In [36]: fun(n, n, []) In [37]: arr Out[37]: [[0, 0, 3], [0, 1, 2], [0, 2, 1], [0, 3, 0], [1, 0, 2], [1, 1, 1], [1, 2, 0], [2, 0, 1], [2, 1, 0], [3, 0, 0]] ``` And now I can convert it to a numpy array to do an elementwise multiplication: ``` In [39]: s = 0.33 In [40]: arr_np = np.array(arr) In [41]: arr_np * s Out[41]: array([[ 0. , 0. , 0.99999999], [ 0. , 0.33333333, 0.66666666], [ 0. , 0.66666666, 0.33333333], [ 0. , 0.99999999, 0. ], [ 0.33333333, 0. , 0.66666666], [ 0.33333333, 0.33333333, 0.33333333], [ 0.33333333, 0.66666666, 0. ], [ 0.66666666, 0. , 0.33333333], [ 0.66666666, 0.33333333, 0. ], [ 0.99999999, 0. , 0. ]]) ``` Upvotes: 1 <issue_comment>username_4: Here is a direct method using `itertools.combinations`: ``` >>> import itertools as it >>> import numpy as np >>> >>> # k is 1/s >>> n, k = 3, 3 >>> >>> combs = np.array((*it.combinations(range(n+k-1), n-1),), int) >>> (np.diff(np.c_[np.full((len(combs),), -1), combs, np.full((len(combs),), n+k-1)]) - 1) / k array([[0. , 0. , 1. ], [0. , 0.33333333, 0.66666667], [0. , 0.66666667, 0.33333333], [0. , 1. , 0. ], [0.33333333, 0. , 0.66666667], [0.33333333, 0.33333333, 0.33333333], [0.33333333, 0.66666667, 0. ], [0.66666667, 0. , 0.33333333], [0.66666667, 0.33333333, 0. ], [1. , 0. , 0. ]]) ``` If speed is a concern, `itertools.combinations` can be replaced by a [numpy implementation](https://stackoverflow.com/a/42202157/7207392). Upvotes: 2 <issue_comment>username_5: This method will also work for an arbitrary sum (`total`): ``` import numpy as np import itertools as it import scipy.special n = 3 s = 1/3. total = 1.00 interval = int(total/s) n_combs = scipy.special.comb(n+interval-1, interval, exact=True) counts = np.zeros((n_combs, n), dtype=int) def count_elements(elements, n): count = np.zeros(n, dtype=int) for elem in elements: count[elem] += 1 return count for i, comb in enumerate(it.combinations_with_replacement(range(n), interval)): counts[i] = count_elements(comb, n) ratios = counts*s print(ratios) ``` Upvotes: 0
2018/03/15
1,076
3,807
<issue_start>username_0: I just started using Jena Apache, on their introduction they explain how to write out the created model. As input I'm using a Turtle syntax file containing some data about some OWL ontologies, and I'm using the @base directive to use relative URI's on the syntax: ``` @base . ``` And then writing my data as: ``` a sosa:Sensor ; rdfs:label "AD590 #1 temperatue sensor"@en ; sosa:observes ; ssn:implements . ``` Apache Jena is able to read that @base directive and expands the relative URI to its full version, but when I write it out Jena doesn't write the @base directive and the relative URI's. The output is shown as: ``` a sosa:Sensor ; rdfs:label "AD590 #1 temperatue sensor"@en ; sosa:observes ; ssn:implements . ``` My code is the following: ``` Model m = ModelFactory.createOntologyModel(); String base = "https://valbuena.com/ontology-test/"; InputStream in = FileManager.get().open("src/main/files/example.ttl"); if (in == null) { System.out.println("file error"); return; } else { m.read(in, null, "TURTLE"); } m.write(System.out, "TURTLE"); ``` There are multiple read and write commands that take as parameter the base: * On the read() I've found that if on the data file the @base isn't declared it must be done on the read command, othwerwise it can be set to null. * On the write() the base parameter is optional, it doesn't matter if I specify the base (even like null or an URI) or not, the output is always the same, the @base doesn't appear and all realtive URI's are full URI's. I'm not sure if this is a bug or it's just not possible.<issue_comment>username_1: First - consider using a prefix like ":" -- this is not the same as base but makes the output nice as well. You can configure the base with (current version of Jena): ``` RDFWriter.create() .source(model) .lang(Lang.TTL) .base("http://base/") .output(System.out); ``` Upvotes: 2 <issue_comment>username_2: It seems that the command used on the introduction tutorial of Jena RDF API is not updated and they show the reading method I showed before (FileManager) which now is replaced by RDFDataMgr. The FileManager way doesn't work with "base" directive well. After experimenting I've found that the base directive works well with: ``` Model model = ModelFactory.createDefaultModel(); RDFDataMgr.read(model,"src/main/files/example.ttl"); model.write(System.out, "TURTLE", base); ``` or ``` Model model = ModelFactory.createDefaultModel(); model.read("src/main/files/example.ttl"); model.write(System.out, "TURTLE", base); ``` Although the model.write() command is said to be legacy on [RDF output documentation](https://jena.apache.org/documentation/io/rdf-output.html#api) (whereas model.read() is considered common on [RDF input documentation](https://jena.apache.org/documentation/io/rdf-input.html#example-1-common-usage), don't understand why), it is the only one I have found that allows the "base" parameter (required to put the @base directive on the output again), RDFDataMgr write methods don't include it. Thanks to @username_1 for providing a simpler way to read the data, which led to fix the problem. Upvotes: 1 [selected_answer]<issue_comment>username_3: @username_1's answer allowed me to write relative URIs to the file, but did not include the base in use for RDFXML variations. To get the xml base directive added correctly, I had to use the following ``` RDFDataMgr.read(graph, is, Lang.RDFXML); Map properties = new HashMap<>(); properties.put("xmlbase", "http://example#"); Context cxt = new Context(); cxt.set(SysRIOT.sysRdfWriterProperties, properties); RDFWriter.create().source(graph).format(RDFFormat.RDFXML\_PLAIN).base("http://example#").context(cxt).output(os); ``` Upvotes: 0
2018/03/15
377
1,288
<issue_start>username_0: Having issues with merging some IFs and VLOOKUPs most probably. Basically, workflow would look like below and I don't quite know how to type it into one formula. 1. Look for value from **Values to look for** in the table on the right hand side. 2. If found in the **list** text string, return the corresponding value from **add/remove** column to B column. [Excel screenshot sample](https://i.stack.imgur.com/XNqKa.png)<issue_comment>username_1: The answer will only work if you make the name for the values unique. What I mean by this is, that you will need to change the name of value1 to value01 if you have more than 10 values. If you have more than 100 values, than you will need to change the name to value001 and so on. Then use this in `B2` and drag down as needed: ``` {=INDEX($D$3:$D$6,MATCH(TRUE,FIND(A2,$E$3:$E$6)>0,0))} ``` NOTE: you dont have to entere the brackets `{}`. These just indicate that this is an array-formula. This needs to be entered with CTRL + SHIFT + ENTER instead of the normal ENTER. Upvotes: 2 [selected_answer]<issue_comment>username_2: try this formula: =IF(IFERROR(SEARCH(A2,E2),"Not Found")="Not Found","Not Found",D2) also please see the screenshot attached [Example](https://i.stack.imgur.com/hKf69.png) Upvotes: 0
2018/03/15
482
1,526
<issue_start>username_0: I have two lists and I need to do a combination of strings from these lists, I have tried but I think it's not very efficient for larger lists. ``` data = ['keywords', 'testcases'] data_combination = ['data', 'index'] final_list = [] for val in data: for comb in range(len(data_combination)): if comb == 1: final_list.append([val] + data_combination) else: final_list.append([val, data_combination[comb]]) ``` My Output is: ``` [['keywords', 'data'], ['keywords', 'data', 'index'], ['testcases', 'data'], ['testcases', 'data', 'index']] ``` Is there any more pythonic way to achieve it?<issue_comment>username_1: A list comprehension is one way. "Pythonic" is subjective and I would not claim this is the most readable or desirable method. ``` data = ['keywords', 'testcases'] data_combination = ['data', 'index'] res = [[i] + data_combination[0:j] for i in data \ for j in range(1, len(data_combination)+1)] # [['keywords', 'data'], # ['keywords', 'data', 'index'], # ['testcases', 'data'], # ['testcases', 'data', 'index']] ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Possibly even more Pythonic: **Code** ``` data = ["keywords", "testcases"] data_combination = ["data", "index"] [[x] + data_combination[:i] for x in data for i, _ in enumerate(data_combination, 1)] ``` Output ``` [['keywords', 'data'], ['keywords', 'data', 'index'], ['testcases', 'data'], ['testcases', 'data', 'index']] ``` Upvotes: 1
2018/03/15
705
2,090
<issue_start>username_0: I wrote a shell script that calls the ffmpeg tool but when I run it, it says No such file or directory yet it does! Here is my script: ``` #!/bin/bash MAIN_DIR="/media/sf_data/pipeline" FFMPEG_DIR="/media/sf_data/livraison_transcripts/ffmpeg-git-20180208-64bit-static" for file in MAIN_DIR/audio_mp3/*.mp3; do cp -p file FFMPEG_DIR; done for file in FFMPEG_DIR/*.mp3; do ./ffmpeg -i ${file%.mp3}.ogg sox $file -t raw --channels=1 --bits=16 --rate=16000 --encoding=signed- integer --endian=little ${file%.ogg}.raw; done for file in FFMPEG_DIR/*.raw; do cp -p file MAIN_DIR/pipeline/audio_raw/; done ``` and here is the debug response: ``` cp: cannot stat ‘file’: No such file or directory ./essai.sh: line 14: ./ffmpeg: No such file or directory sox FAIL formats: can't open input file `FFMPEG_DIR/*.mp3': No such file or directory cp: cannot stat ‘file’: No such file or directory ``` FYI I'm running CentOS7 on VirtualBox Thank you<issue_comment>username_1: Hi You need couple of correction in your shell script see below. To get the actual value assigned to a variable you need to add `$` at the front of the variable in shell script. ``` for file in $"MAIN_DIR"/audio_mp3/*.mp3; do cp -p "$file" "$FFMPEG_DIR"; done for file in "$FFMPEG_DIR"/*.mp3; ./ffmpeg -i ${file%.mp3}.ogg #provide full path like /usr/bin/ffmpeg for file in "$FFMPEG_DIR"/*.raw; do cp -p "$file" "$MAIN_DIR"/pipeline/audio_raw/; done ``` Upvotes: 0 <issue_comment>username_2: Here's a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) (MCVE), a version of your script that removes everything not required to show the problem: ``` #!/bin/bash MAIN_DIR="/media/sf_data/pipeline" echo MAIN_DIR ``` Expected output: ``` /media/sf_data/pipeline ``` Actual output: ``` MAIN_DIR ``` This is because `bash` requires a `$` when expanding variables: ``` #!/bin/bash MAIN_DIR="/media/sf_data/pipeline" echo "$MAIN_DIR" ``` The quotes are not required to fix the issue, but prevent issues with whitespaces. Upvotes: 1
2018/03/15
543
1,940
<issue_start>username_0: The check() is called from the html, and the return value should be true/false. ``` ng-class="{'timeline-inverted: check(id)'}" ``` The `$scope.server.get()` get `result(r)` from the server script, and I need to return the `$scope.result` to the `check()` function. Here is my code in angular: ``` $scope.check = _.memoize(function(userId) { $scope.server.get({ action: 'checkif', userID: userId }).then(function successHandler(r) { $scope.result = r.data.result; }); return $scope.result; // $scope.result is undefined }); ```<issue_comment>username_1: Create a new Promise than you resolve once the HTTP call is successful. ``` $scope.check = _.memoize(function(userId) { return new Promise((resolve, reject) => { $scope.server.get({ action: 'checkif', userID: userId }).then(function successHandler(r) { resolve(r.data.result); }); }); }); ``` Upvotes: 1 <issue_comment>username_2: First, using [memoize](http://underscorejs.org/#memoize) is not a good deal here. memoized works perfectly fine as the argument has a primitive type. Since you call your API you cannot be sure that the same set of data is returned by the same `userId` & `action` params! I don't know why your `$http` call is binded to an `$scope`. Maybe it better to place such stuff in a service. Finally your application could look like this nice structured app: ``` var myApp = angular.module('myApp', []); myApp.controller('MyCtrl', function($scope, user) { $scope.userData = null; user.get('checkif', 2).then(function (result) { $scope.userData = result.data.result; }); }); myApp.service('user', function () { this.get = function (action, userId) { return $http({ url: 'http://your-api-endpoint/', method: 'GET', params: { action: action, userID: userId } }); } }); ``` Upvotes: 0
2018/03/15
1,376
2,752
<issue_start>username_0: FOR example here are two data files: file1: ``` target 1 6791340 10.9213 2 6934561 9.6791 3 6766224 9.5835 4 6753444 9.1097 5 6809077 8.7386 6 6818752 8.7172 ``` fil2: ``` 1 6766224 11.7845 2 6753444 9.6863 3 6809077 9.5252 4 6818752 9.3867 5 6791340 9.1914 6 6934561 9.1914 ``` file3(output): ``` target 1 6791340 10.9213 5 9.1914 2 6934561 9.6791 6 9.1914 3 6766224 9.5835 1 11.7845 4 6753444 9.1097 2 9.6863 5 6809077 8.7386 3 9.5252 6 6818752 8.7172 4 9.3867 ``` As you can see, the order of target column stayed exactly the same as file1. But, file2 follows the order of file1 based on target column and columns from file2 changed accordingly. the real files are big and "target" is written just for clarification. any guide, please? This is what I tried: ``` awk 'NR==FNR{ a[$2]=$1; next }{ print a[$1],$1,$2 }' file1 file2 > output ``` But this changes the order of target column.<issue_comment>username_1: Is the easiest way not to sort the two files on column two and then sort again on column 1? Be aware that you do buffer here and call various programs. A clean `awk` solution is given by [username_2](https://stackoverflow.com/a/49297358/8344060). ``` % join -j2 <(sort -g -k2 file1) <(sort -g -k2 file2) \ -o 1.1,1.2,1.3,2.1,2.3 | sort -g -k1 1 6791340 10.9213 5 9.1914 2 6934561 9.6791 6 9.1914 3 6766224 9.5835 1 11.7845 4 6753444 9.1097 2 9.6863 5 6809077 8.7386 3 9.5252 6 6818752 8.7172 4 9.3867 ``` The flag `-o 1.1,1.2,1.3,2.1,2.3` is the output option of `join`, it dictates to print column 1 of file 1 (`1.1`), followed by column 2 of file 1 (`1.2`), etc. > > **`man join`** : > `-o FORMAT` > obey `FORMAT` while constructing output line > > > `FORMAT` is one or more comma or blank separated specifications, each > being `FILENUM.FIELD` or `0`. Default `FORMAT` outputs the join field, the remaining fields from FILE1, the remaining fields from > FILE2, all separated by CHAR. If `FORMAT` is the keyword `auto`, then > the first line of each file > determines the number of fields output for each line. > > > Without this option, you would still have to swap column 1 and 2. ``` join -j2 <(sort -g -k2 file1) <(sort -g -k2 file2) | awk '{t=$2;$2=$1;$1=t}1' | sort -g -k1 ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Switch the order of file processing ``` $ awk 'NR==FNR{a[$2]=$1 OFS $3; next} ($2 in a){print $0, a[$2]}' f2 f1 1 6791340 10.9213 5 9.1914 2 6934561 9.6791 6 9.1914 3 6766224 9.5835 1 11.7845 4 6753444 9.1097 2 9.6863 5 6809077 8.7386 3 9.5252 6 6818752 8.7172 4 9.3867 ``` * `($2 in a)` can be removed if both second columns will surely match Upvotes: 2
2018/03/15
914
3,443
<issue_start>username_0: Hell I ma new in angular 5. I am create a login and auth service. But i cannot compile my code. Here is my code ``` // user.service.ts import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; @Injectable() export class UserService { private loggedIn = false; constructor(private http: Http) { // this.loggedIn = !!localStorage.getItem('auth_token'); } //authenticate user with dummy logic because i use a json-server authenticate(login:string, password:string) { console.log('Authenticate ....'); const credentials = {login:login, password:<PASSWORD>}; let headers = new Headers(); headers.append('Content-Type', 'application/json'); var result = this.http .get( '/users?login?'+JSON.stringify(login), { headers } ); if(result.password==password){ return true; } return false; } } ``` When i compile ( ng server ) i get the following error ``` ERROR in src/app/auth/user.services.ts(28,17): error TS2339: Property 'password' does not exist on type 'Observable'. ``` Line 28 is : `if(result.password==password){` I don't know what i am missing ?I try to understand the Observable concept. If you add an idea, it will help me. Thanks<issue_comment>username_1: You are trying to access the observable returned from the http call. To get the information in the observable you have to subscribe to it. For detailed information about hot to get remote data please read this: <https://angular.io/guide/http> NOTE: You should not use the deprecated angular/http. Use angular/common/http instead. Upvotes: 0 <issue_comment>username_2: `result` here is an observable, you need to subscribe to it to get response. Something like below: ``` var result = this.http.get( '/users?login?'+JSON.stringify(login), { headers } ); //result is an observer here, you have to subscribe to it result.subscribe((response) => { if(response.password==password){ return true; } return false; }); ``` You can check this awesome article: <https://gist.github.com/staltz/868e7e9bc2a7b8c1f754> Upvotes: 2 <issue_comment>username_3: 1. Use `Observables` properly 2. Use `HttpClient`, not old `Http` 3. You can also define a `User` class to make typing more strict. --- ``` // user.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; @Injectable() export class UserService { private loggedIn = false; constructor(private http: HttpClient) { // this.loggedIn = !!localStorage.getItem('auth_token'); } //authenticate user with dummy logic because i use a json-server authenticate(login:string, password:string) :Observable { return this.http .get('url/whatever') //returns a User object having password .map(user => user.password === password); // maps result to the desired true or false value } } ``` --- ``` // to consume the service from a component, for example this.userService.authenticate('myusername', 'mypassword') .subscribe(authenticated => { console.log('login status', authenticated) }) ``` Upvotes: 2 [selected_answer]
2018/03/15
386
1,366
<issue_start>username_0: I have the following list from my configuration: ``` val markets = Configuration.getStringList("markets"); ``` To create a sequence out of it I write this code: ``` JavaConverters.asScalaIteratorConverter(markets.iterator()).asScala.toSeq ``` **I wish I could do it in a less verbose way**, such as: ``` markets.toSeq ``` And then from that list I get the sequence. I will have more configuration in the near future; is there a solution that provides this kind of simplicity? I want a sequence **regardless of the configuration library I am using**. I don't want to have the stated verbose solution with the `JavaConverters`.<issue_comment>username_1: Yes. Just import implicit conversions: ``` import java.util import scala.collection.JavaConversions._ val jlist = new util.ArrayList[String]() jlist.toSeq ``` Upvotes: 1 <issue_comment>username_2: [`JavaConversions`](http://www.scala-lang.org/api/2.12.4/scala/collection/JavaConversions$.html) is deprecated since Scala 2.12.0. Use [`JavaConverters`](http://www.scala-lang.org/api/2.12.4/scala/collection/JavaConverters$.html); you can import `scala.collection.JavaConverters._` to make it less verbose: ``` import scala.collection.JavaConverters._ val javaList = java.util.Arrays.asList("one", "two") val scalaSeq = javaList.asScala.toSeq ``` Upvotes: 4 [selected_answer]
2018/03/15
392
1,282
<issue_start>username_0: I have been adding a bottom shadow to a `UIButton` this way: ``` class MyButton: UIButton { override func layoutSubviews() { super.layoutSubviews() self.layer.shadowOpacity = 0.33 self.layer.shadowRadius = 4.0 self.layer.shadowColor = UIColor.blue.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: 6.0) } } ``` The result I'm getting: [![enter image description here](https://i.stack.imgur.com/HWL25.png)](https://i.stack.imgur.com/HWL25.png) This works fine but I would like now to shrink the shadow width in order to have this rendering instead (picture from Sketch) : [![enter image description here](https://i.stack.imgur.com/cMsKa.png)](https://i.stack.imgur.com/cMsKa.png) Any idea of how to handle this? Thanks for your help!<issue_comment>username_1: If you do not find a more suitable answer, then try this: Add a UIView under the button with the desired size and it is for her to make a shadow. Upvotes: 0 <issue_comment>username_2: Use layer's shadowPath property. add below code to **layoutSubviews** method and try. ``` let path = UIBezierPath(roundedRect: bounds.insetBy(dx: 10, dy: 0), cornerRadius: 4.0) self.layer.shadowPath = path.cgPath ``` Upvotes: 2 [selected_answer]
2018/03/15
283
899
<issue_start>username_0: Let's say I have DB Tables like that: ``` Continent -> Countries -> Cities -> Lakes ``` Now i want to include them ``` _db.Continents .Include(p => p.Countries) .ThenInclude(c => c.Cities) .Include(p => p.Countries) .ThenInclude(p => p.Lakes) ``` Is this the only way (by including countries **twice**) or is there another way?<issue_comment>username_1: As said before EF Include countries only once. for better reading you can write it like that : ``` _db.Continents .Include(p => p.Countries.Select(s => s.Cities)) .ThenInclude(p => p.Countries.Select(s => s.Lakes)) ``` Upvotes: -1 <issue_comment>username_2: There is actually support for this as of EF Core 2.1. The pattern looks something like this: ``` _db.Continents.Include(p => p.Countries).ThenInclude(c => c.Cities).ThenInclude((Country p) => p.Lakes) ``` Upvotes: 2
2018/03/15
444
1,622
<issue_start>username_0: I prepare to perform a simple project and I don’t know what I should use to accomplish this. I need to receive a data entered by a user (via a webpage) and store them somewhere. I need them to be able to search and returned on the user request. I’m a little old-fashioned so I assumed that should be a file on ftp managed by some python or JS script? I really don’t know where to start so please advise. [project](https://i.stack.imgur.com/NSzHB.jpg)<issue_comment>username_1: Have you considered storing data in a database? You can use MySQL. It's quite simple after you understand how a database table works. Data are stored in a table. Table is a part of a database with other tables. Each table has columns you create. Data are added to the table in rows. For example, let's say a user sends you their name 'Brian'. You can have a table called 'users'. In that table, you can create a column 'id' of the user (read about it later, including auto incrementing), and 'name'. You insert the data into that table. Brian is now in a table with his own ID, like this: ``` id Name ---------------- 1 Brian ``` Check this out: [SQL tutorial](https://www.w3schools.com/sql/) Upvotes: 1 <issue_comment>username_2: Possible solution i would recommend: 1. create a mysql server 2. create a backend (links for Java) * rest-service <https://spring.io/guides/gs/rest-service/> * access DB <https://docs.spring.io/spring-data/jpa/docs/1.5.0.RELEASE/reference/html/repositories.html> * put the parts together 3. get/save the data on your webpage with xhr2. Upvotes: 0
2018/03/15
1,072
3,936
<issue_start>username_0: There's quite good doc of using \*ngIf in Angular: <https://angular.io/api/common/NgIf> But, is that possible to have \*ngIf async variable and multiple checks on that? Something like: ``` ... ``` Of course, it's possible to use nested \*ngIf, like: ``` ... ``` but it'd be really nice to use only one container, not two.<issue_comment>username_1: You can do this: ``` {{ user | json }} ``` Keep in mind that when using a subscription from a http-request, this would trigger the request twice. So you should use some state-management pattern or library, to not make that happen. Here is a [stackblitz](https://stackblitz.com/edit/obs-with-ngif-ngfor). Upvotes: 6 [selected_answer]<issue_comment>username_2: I hit the same issue of needing an \*ngIf + async variable with multiple checks. This ended up working well for me. ``` ... ``` or if you prefer ``` ... ``` **Explanation** Since the result of the if expression is assigned to the local variable you specify, simply ending your check with `... && (users$ | async) as users` allows you to specify multiple conditions *and* specify what value you want the local variable to hold when all your conditions succeed. **Note** I was initially worried that using multiple `async` pipes in the same expression may create multiple subscriptions, but after some light testing (I could be wrong) it seems like only one subscription is actually made. Upvotes: 5 <issue_comment>username_3: Here's the alternative version, with a little bit cleaner template: ``` {{ user | json }} No users found ``` Note that we use `users$ | async` 2 times. That will work if you add [`shareReplay()`](https://rxjs-dev.firebaseapp.com/api/operators/shareReplay) operator to `user$` Observable: ``` public users$: Observable = this.someService.getUsers() .pipe(shareReplay()); ``` That way, inner template will be able to access last value of the Observable and display the results. You can try it out on [stackblitz](https://stackblitz.com/edit/obs-with-ngif-ngfor-dex3sc). Upvotes: 3 <issue_comment>username_4: I see everyone using **\*ngFor and \*ngIf together** in one tag and similar work-arounds, but I think that is an **anti-pattern**. In most regular coding languages, you don't do an if statement and a for loop on the same line do you? IMHO if you have to work around because they specifically don't want you to, you're not supposed to do that. ***Don't practice what's not "best practice."*** **✅✅✅ Keep it simple, if you don't need to declare the $implicit value from `users$ | async` as users:** ``` ... ``` But if you do need to declare `as user`, wrap it. --- **✅ For Complex Use Case;** mind you, the generated markup will not even have an HTML tag, that's the beauty of ng-templates & ng-containers! *@username_1's accepted, edited answer works because \*ngFor with asterisk is a shorthand for ng-template with ngFor (no asterisk), not to mention the double async pipe* . The code really smells of inconsistency when you combine a no-asterisk ngFor with a \*ngIf; you get the gist. The \*ngIf takes precedence so why not just wrap it in a ng-container/ng-template? It won't wrap your inner elements using an HTML tag in the generated markup. ``` Loaded and inbound Loaded and out of bound Content to render when condition is false. ``` --- **❌ Don't do this** ``` ... ``` Pipes are a bit daunting after you know about their sensitivity to life cycles; they update like mad. That's why Angular do NOT have SortPipe nor FilterPipe. So, erm, don't do this; you're basically creating 2 Observables that sometimes update frantically and may cause long-term data mismatch in its children if I'm correct. Upvotes: 5 <issue_comment>username_5: ``` show all job applications ### You haven't applied to any jobs. ``` Upvotes: 2 <issue_comment>username_6: ``` ..... ..... ..... ..... ``` Upvotes: 0
2018/03/15
646
2,106
<issue_start>username_0: I need a SQL/Oracle function that compares two numbers if number are even like( 22,10,4,12,6..) true if are odd number like(3,7,13,5...) false. ``` CREATE OR REPLACE FUNCTION is_even(num_in NUMBER) RETURN BOOLEAN IS BEGIN IF MOD(num_in, 2) = 0 THEN RETURN TRUE; END IF; EXCEPTION WHEN OTHERS THEN RETURN FALSE; END is_even; / CREATE OR REPLACE FUNCTION is_odd(num_in NUMBER) RETURN BOOLEAN IS BEGIN RETURN MOD(num_in, 2) = 1; EXCEPTION WHEN OTHERS THEN RETURN FALSE; END is_odd; ```<issue_comment>username_1: I ready don't understand what is the difficulty here, as you yourself have provided the code for two functions above... Anyway here you go: ``` CREATE OR REPLACE FUNCTION is_even(num_in NUMBER) RETURN BOOLEAN IS BEGIN IF MOD(num_in, 2) = 0 THEN RETURN TRUE; else RETURN FALSE; END IF; END is_even; / ``` Upvotes: 0 <issue_comment>username_2: One point not addressed in the other answer, which I have already mentioned in the comments and you don't seem to have paid attention to is that Boolean values can only be used in PL/SQL code, not in Oracle SQL. This restricts you from calling your function through the most common method - to use it in a sql statement. If you try running this query with your function, it would fail. ``` select is_even(10) FROM DUAL; ``` > > ORA-06552: PL/SQL: Statement ignored > > > ORA-06553: PLS-382: expression is > of wrong type > > > You may call this function to set a Boolean PL/SQL variable, but it isn't very useful in a general scenario. ``` DECLARE v_even_odd BOOLEAN := is_even(3); ``` Alternatively, you could return a number or a string ( "TRUE" / "FALSE" ). ``` CREATE OR REPLACE FUNCTION is_even (num_in NUMBER) RETURN VARCHAR2 IS BEGIN IF MOD (num_in, 2) = 0 THEN RETURN 'TRUE'; ELSE RETURN 'FALSE'; END IF; END is_even; / ``` Which works fine while calling from sql. ``` select is_even(10) FROM DUAL; IS_EVEN(10) ---------------- TRUE ``` Upvotes: 1
2018/03/15
1,149
3,559
<issue_start>username_0: I have the output of a Markov transition table, which is a list of 59 lists each with 59 floats. I want to invert each of the non-0 floats, and then normalise the output so that again I have a list of probabilities which add up to 1. I have read the textbook on list comprehensions, and that seems relevant, but I can't for the life of me understand how to implement it. The list of lists is `m` ``` for i in range(59): [1/item for item in m[i] if item > 0.] i += 1 ``` This runs, but it doesn't change `m`. Am I wrong to be using `item` in this code? Should I be using some other reference?<issue_comment>username_1: You need to assign it back to `m[i]` in the loop: ``` for i in range(len(m)): m[i] = [1./item if item != 0. else item for item in m[i]] ``` And the `i+=1` is not needed because the `for` loop does that for you. In order to avoid the sublist being shorter than the original sublist, you need to move the if from the end of the list comprehension (which basically filters which items are processed) to the front (so the value itself is a [ternary expression](https://stackoverflow.com/a/394814/4042267) that evaluates to `1/item` or `item`, depending on the value of `item`). At this point you should probably watch the presentation [Loop like a Native](http://nedbatchelder.com/text/iter.html) and rewrite it for example as: ``` for i, x in enumerate(m): m[i] = [1./item if item != 0. else item for item in x] ``` Upvotes: 3 <issue_comment>username_2: `[1/item for item in m[i] if item > 0.]` alone on a line creates a throwaway object. Not really useful. My suggestion: rebuild your list of lists using a double comprehension: ``` m = [[1./item for item in sm if item > 0.] for sm in m] ``` this solution is Python 2/3 compliant in regards to floating point division whatever the list contains (integers or floats) EDIT: quoting the question: "I want to invert each of the non-0 floats", the formula is incorrect since it doesn't include the zeroes. So a more accurate version would be not to filter, but to test expression with a ternary so it keeps zeroes. ``` m = [[1./item if item else 0. for item in sm] for sm in m] ``` (`if item` is the shortcut to test item against 0) Upvotes: 3 <issue_comment>username_3: `[1/item for item in m[i] if item > 0.]` creates a new list. Then you do nothing with that list. What username_1 is telling you is that you need a reference to the newly created list: `m[i] =` will assign back to row `i` of your list of lists. Also, consider numpy for element-wise operations. Demo: ``` >>> import numpy as np >>> m = np.array([[1,2], [3, 0]]) >>> m = 1.0/m >>> m array([[ 1. , 0.5 ], [ 0.33333333, inf]]) >>> m[m == np.inf] = 0 >>> m array([[ 1. , 0.5 ], [ 0.33333333, 0. ]]) ``` Upvotes: 3 <issue_comment>username_4: I recommend you use, if possible, tools specifically designed for this purpose. In the below vectorised solution, inversion occurs *in place* via `numpy`, and [`sklearn.preprocessing.normalize`](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.normalize.html#sklearn.preprocessing.normalize) is used to normalize. ``` import numpy as np from sklearn.preprocessing import normalize arr = np.array([1, 2, 0, 1, 1, 0, 4, 0], dtype=float) def inv(A): m = (A != 0) A[m] = 1/A[m] return A res = normalize(inv(arr)) # [[ 0.54944226 0.27472113 0. 0.54944226 0.54944226 0. # 0.13736056 0. ]] ``` Upvotes: 2
2018/03/15
1,173
3,656
<issue_start>username_0: I'm writing Appium tests that runs against both Android and ioS. When I try to find a MobileElement that's not visable, the timeout takes more than the specified time. If I use a By.id, the timeout is correct. Timeouts after 45 s ``` @AndroidFindBy(id = "ok_button") private MobileElement okButton; driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); WebDriverWait wait = new WebDriverWait(driver, 5); wait.until(ExpectedConditions.elementToBeClickable(okButton)); ``` Timeouts after 5 s ``` driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); WebDriverWait wait = new WebDriverWait(driver, 5); wait.until(ExpectedConditions.elementToBeClickable(By.id("ok_button"))); ```<issue_comment>username_1: You need to assign it back to `m[i]` in the loop: ``` for i in range(len(m)): m[i] = [1./item if item != 0. else item for item in m[i]] ``` And the `i+=1` is not needed because the `for` loop does that for you. In order to avoid the sublist being shorter than the original sublist, you need to move the if from the end of the list comprehension (which basically filters which items are processed) to the front (so the value itself is a [ternary expression](https://stackoverflow.com/a/394814/4042267) that evaluates to `1/item` or `item`, depending on the value of `item`). At this point you should probably watch the presentation [Loop like a Native](http://nedbatchelder.com/text/iter.html) and rewrite it for example as: ``` for i, x in enumerate(m): m[i] = [1./item if item != 0. else item for item in x] ``` Upvotes: 3 <issue_comment>username_2: `[1/item for item in m[i] if item > 0.]` alone on a line creates a throwaway object. Not really useful. My suggestion: rebuild your list of lists using a double comprehension: ``` m = [[1./item for item in sm if item > 0.] for sm in m] ``` this solution is Python 2/3 compliant in regards to floating point division whatever the list contains (integers or floats) EDIT: quoting the question: "I want to invert each of the non-0 floats", the formula is incorrect since it doesn't include the zeroes. So a more accurate version would be not to filter, but to test expression with a ternary so it keeps zeroes. ``` m = [[1./item if item else 0. for item in sm] for sm in m] ``` (`if item` is the shortcut to test item against 0) Upvotes: 3 <issue_comment>username_3: `[1/item for item in m[i] if item > 0.]` creates a new list. Then you do nothing with that list. What username_1 is telling you is that you need a reference to the newly created list: `m[i] =` will assign back to row `i` of your list of lists. Also, consider numpy for element-wise operations. Demo: ``` >>> import numpy as np >>> m = np.array([[1,2], [3, 0]]) >>> m = 1.0/m >>> m array([[ 1. , 0.5 ], [ 0.33333333, inf]]) >>> m[m == np.inf] = 0 >>> m array([[ 1. , 0.5 ], [ 0.33333333, 0. ]]) ``` Upvotes: 3 <issue_comment>username_4: I recommend you use, if possible, tools specifically designed for this purpose. In the below vectorised solution, inversion occurs *in place* via `numpy`, and [`sklearn.preprocessing.normalize`](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.normalize.html#sklearn.preprocessing.normalize) is used to normalize. ``` import numpy as np from sklearn.preprocessing import normalize arr = np.array([1, 2, 0, 1, 1, 0, 4, 0], dtype=float) def inv(A): m = (A != 0) A[m] = 1/A[m] return A res = normalize(inv(arr)) # [[ 0.54944226 0.27472113 0. 0.54944226 0.54944226 0. # 0.13736056 0. ]] ``` Upvotes: 2
2018/03/15
487
1,495
<issue_start>username_0: I'm using sequelize with postgres, Is there a way to perform a "not contains" statement with sequelize? something like: ``` [Op.not]: { [Op.contains]: ['value1','value2'] } ``` which produces: ``` SELECT * FROM Table WHERE NOT ArrayColumn @>ARRAY['value1','value2']::VARCHAR(255)[] ```<issue_comment>username_1: You can use as ``` where: { $not: { $contains: ['value1','value2'] }, } ``` Upvotes: -1 <issue_comment>username_2: had the same issue had to go to rawish SQL ``` where[''][Op.and] = [Sequelize.literal(`'${JS\_VARIABLE\_ARRAY}' != all ()`)]; ``` I've built this helper function to construct the my where query ``` const buildWhereQuery = (query, columns) => { const parsedObject = {}; Object.keys(query).forEach((attr) => { if (columns.indexOf(attr) !== -1 && (query[attr] !== null || query[attr] !== undefined)) { parsedObject[attr] = query[attr]; } }); return parsedObject; }; const where = buildWhereQuery(query, columnsToQueryAgainst) ``` hope that's help. using: node: v10.14.2 sequelize@4.38.0 sequelize-cli@4.0.0 Upvotes: 0 <issue_comment>username_3: You can use `Op.not` which will negate the `Op.contains`. Here is the complete code: ``` const query = { where: { arrayColumn: { [Op.not]: { [Op.contains]: ["value1", "value2"], }, }, }, }; ``` This will produce ``` SELECT * FROM User WHERE NOT ArrayColumn @> ARRAY['value1','value2']::VARCHAR(255)[] ``` Upvotes: 0
2018/03/15
387
1,379
<issue_start>username_0: I am trying to POST to a google maps service. If you click on the URL you will see the JSON response that I am expecting to get ``` var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; var xhr = new XMLHttpRequest() var url = "https://maps.googleapis.com/maps/api/directions/json?origin=Exeter&destination=Deal&region=uk&mode=driving" xhr.open('POST', url, true) xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.onload = function() { // do something to response alert(this.responseText) } ``` However, this code gets stops after `xhr.onload = function()`. So I never get the response back. Is there an error in my code?<issue_comment>username_1: You forgot to send the request. ``` xhr.send("The string of application/x-www-form-urlencoded data you are POSTING goes here"); ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: ``` var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; var xhr = new XMLHttpRequest() var url = "https://maps.googleapis.com/maps/api/directions/json?origin=Exeter&destination=Deal&region=uk&mode=driving" xhr.open('POST', url, true) xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.onload = function() { // do something to response alert(this.responseText) } xhr.send("data to be send"); ``` Try this. Upvotes: -1
2018/03/15
497
1,390
<issue_start>username_0: I have a table like this ``` ID | UserID | Time | 3 9200 10/12/2016 2 9200 11/12/2016 1 9200 13/12/2016 4 1000 01/10/2017 5 1000 03/10/2017 ``` Now I want to select the minimum date for a user id i.e., ``` userID Time 9200 10/12/2016 1000 01/10/2017 ``` i am using this but it throws an "Not a group by expression " or "Not a single group expression" ``` select user_id, min(time) as earliest_date from table where doc_id in (select doc_id from docs where description='some doc') ``` Any work around? other than select where rownum=1<issue_comment>username_1: Just use `group by`: ``` select user_id, min(time) as earliest_date from table group by user_id; ``` If you want the entire rows with the minimum time, use an analytic function: ``` select t.* from (select t.*, min(time) over (partition by user_id) as mintime from t) t where time = mintime; ``` If you want the `min()` on each row: ``` select t.*, min(time) over (partition by user_id) from t; ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` select user_id, min(time) as earliest_date from table where doc_id in (select doc_id from docs where description='some doc') group by user_id ``` you have to use all the columns mentioned in SELECT statement in a group by except aggregated columns. Upvotes: 0
2018/03/15
1,096
3,746
<issue_start>username_0: I have the following statement: ``` Customer.where(city_id: cities) ``` which results in the following SQL statement: ``` SELECT customers.* FROM customers WHERE customers.city_id IN (SELECT cities.id FROM cities... ``` Is this intended behavior? Is it documented somewhere? I will not use the Rails code above and use one of the followings instead: ``` Customer.where(city_id: cities.pluck(:id)) ``` or ``` Customer.where(city: cities) ``` which results in the exact same SQL statement.<issue_comment>username_1: > > Why does it work? > > > Something deep in the ActiveRecord query builder is smart enough to see that if you pass an array or a query/criteria, it needs to build an `IN` clause. > > Is this documented anywhere? > > > Yes, <http://guides.rubyonrails.org/active_record_querying.html#hash-conditions> ### 2.3.3 Subset conditions > > If you want to find records using the IN expression you can pass an array to the conditions hash: > > > > ``` > Client.where(orders_count: [1,3,5]) > > ``` > > This code will generate SQL like this: > > > > ``` > SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5)) > > ``` > > Upvotes: 3 <issue_comment>username_2: The AREL querying library allows you to pass in ActiveRecord objects as a short-cut. It'll then pass their primary key attributes into the SQL it uses to contact the database. When looking for multiple objects, the AREL library will attempt to find the information in as few database round-trips as possible. It does this by holding the query you're making as a set of conditions, until it's time to retrieve the objects. This way would be inefficient: ``` users = User.where(age: 30).all # ^^^ get all these users from the database memberships = Membership.where(user_id: users) # ^^^^^ This will pass in each of the ids as a condition ``` Basically, this way would issue two SQL statements: ``` select * from users where age = 30; select * from memberships where user_id in (1, 2, 3); ``` Each of these involves a call on a network port between applications and the data to then be passsed back across that same port. --- This would be more efficient: ``` users = User.where(age: 30) # This is still a query object, it hasn't asked the database for the users yet. memberships = Membership.where(user_id: users) # Note: this line is the same, but users is an AREL query, not an array of users ``` It will instead build a single, nested query so it only has to make a round-trip to the database once. ``` select * from memberships where user_id in ( select id from users where age = 30 ); ``` So, yes, it's expected behaviour. It's a bit of Rails magic, it's designed to improve your application's performance without you having to know about how it works. --- There's also some cool optimisations, like if you call `first` or `last` instead of `all`, it will only retrieve one record. ``` User.where(name: 'bob').all # SELECT "USERS".* FROM "USERS" WHERE "USERS"."NAME" = 'bob' User.where(name: 'bob').first # SELECT "USERS".* FROM "USERS" WHERE "USERS"."NAME" = 'bob' AND ROWNUM <= 1 ``` Or if you set an order, and call last, it will reverse the order then only grab the last one in the list (instead of grabbing all the records and only giving you the last one). ``` User.where(name: 'bob').order(:login).first # SELECT * FROM (SELECT "USERS".* FROM "USERS" WHERE "USERS"."NAME" = 'bob' ORDER BY login) WHERE ROWNUM <= 1 User.where(name: 'bob').order(:login).first # SELECT * FROM (SELECT "USERS".* FROM "USERS" WHERE "USERS"."NAME" = 'bob' ORDER BY login DESC) WHERE ROWNUM <= 1 # Notice, login DESC ``` Upvotes: 3
2018/03/15
509
1,573
<issue_start>username_0: I'm connecting with Java to neo4j using the GraphDatabase.driver and I have this log4j.properties file which suppresses the output of HBase and MongoDB but doesn't work with neo4j: ``` log4j.rootLogger=OFF, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{2}: %m%n ``` The logging output that shows up in the client application looks like this: ``` Mär 15, 2018 11:20:03 AM org.neo4j.driver.internal.logging.JULogger info INFORMATION: Closing driver instance org.neo4j.driver.internal.InternalDriver@6743e411 Mär 15, 2018 11:20:03 AM org.neo4j.driver.internal.logging.JULogger info INFORMATION: Closing connection pool towards localhost:7687 Mär 15, 2018 11:20:05 AM org.neo4j.driver.internal.logging.JULogger info ``` How can this be disabled?<issue_comment>username_1: The JULogger of the neo4j GraphDatabase.driver can be disabled using the java.util.logging.LogManager ``` LogManager.getLogManager().reset(); ``` This will disable the logging, thus even suppress error messages. If just the INFO message shown in the example output should be suppressed then the log level has to be changed. ``` Logger rootLogger = LogManager.getLogManager().getLogger(""); rootLogger.setLevel(Level.SEVERE); for (Handler h : rootLogger.getHandlers()) h.setLevel(Level.SEVERE); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` ``` Upvotes: 0
2018/03/15
1,489
4,331
<issue_start>username_0: my project has multiple domains and I would like to redirect 100 pages for 1 of these domain. Now I found [this post](https://stackoverflow.com/questions/10232722/htaccess-rewrite-based-on-hostname-or-domain-name) on how to set up conditions for 1 domain. ``` RewriteCond %{HTTP_HOST} ^www\.site1\.com [NC] RewriteRule ^(.*)$ index.php?lang=it [NC,QSA] RewriteCond %{HTTP_HOST} ^www\.site2\.com [NC] RewriteRule ^(.*)$ index.php?lang=en [NC,QSA] ``` My question would be, how can I set this up for 100 pages? Do I have to duplicate the condition for each link? What I want to do is this ``` RewriteCond %{HTTP_HOST} ^www\.site1\.com [NC] RewriteRule ^some https://www.mypage.de/shop/some [R=301, L] RewriteRule ^page https://www.mypage.de/shop/page [R=301, L] RewriteRule ^settings https://www.mypage.de/shop/settings [R=301, L] ```<issue_comment>username_1: ``` RewriteRule ^(.*)$ https://www.mypage.de/shop/$1 [QSA] ``` This will redirect every single page. If you only want 100 specific pages you must add one by one. Like other answers were provided. Upvotes: 0 <issue_comment>username_2: Probably **Skip flag** will be the best aproach. It looks like this: ``` RewriteCond %{HTTP_HOST} !^www\.site1\.com [NC] RewriteRule .? - [S=100] RewriteRule ^some https://www.mypage.de/shop/some [R=301, L] RewriteRule ^page https://www.mypage.de/shop/page [R=301, L] RewriteRule ^settings https://www.mypage.de/shop/settings [R=301, L] ..... RewriteRule ^rule_for_100nd_page https://www.mypage.de/shop/settings [R=301, L] ``` How this works. 1. Test HOST if NOT skip 100 (S=100) the next RewriteRules if YES `RewriteRule .? - [S=100]` is ignored 2. Write your 100 rules for `www.site1.com` source domain and go on. Upvotes: 0 <issue_comment>username_3: Assuming your page names are same after redirect as you've shown in your question, you can use a single rule like this as your top most rule: ``` RewriteEngine On RewriteCond %{HTTP_HOST} ^www\.site1\.com$ [NC] RewriteRule .+ https://www.mypage.de/shop/$0 [R=301,NE,L] ``` Make sure to use a new browser for your testing. Upvotes: 0 <issue_comment>username_4: There are so many scenarios to do in this case , for example , you could redirect every page except specific page like this : ``` RewriteCond %{HTTP_HOST} ^(www\.)?site1\.com [NC] RewriteCond %{REQUEST_URI} !^/(page1|page2|page3|whatever) RewriteRule ^(.*)$ https://www.mypage.de/shop/$1 [R=301, L] ``` But , if the number of page who should be excluded is large , you could create directory , for example , `new` then move all files that have to be redirected at it , then make this rule ``` RewriteCond %{HTTP_HOST} ^(www\.)?site1\.com [NC] RewriteCond %{REQUEST_URI} !^/new/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{DOCUMENT_ROOT}/new%{REQUEST_URI} -f RewriteRule ^(.*)$ /new/$1 [L] ``` Then you could add this to redirect any URI contains `new` to that new location : ``` RewriteCond %{HTTP_HOST} ^(www\.)?site1\.com [NC] RewriteCond %{REQUEST_URI} ^/new/ RewriteRule ^(.*)$ https://www.mypage.de/shop/$1 [R=301, L] ``` So code should look like this : ``` RewriteCond %{HTTP_HOST} ^(www\.)?site1\.com [NC] RewriteCond %{REQUEST_URI} !^/new/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{DOCUMENT_ROOT}/new%{REQUEST_URI} -f RewriteRule ^(.*)$ /new/$1 [L] RewriteCond %{HTTP_HOST} ^(www\.)?site1\.com [NC] RewriteCond %{REQUEST_URI} ^/new/ RewriteRule ^(.*)$ https://www.mypage.de/shop/$1 [R=301, L] ``` Upvotes: 2 <issue_comment>username_5: So after testing some of the suggestions I ended up having to add the condition to each rule in order to make it work. So as far as I can tell you can't set conditions for more than one rule if the targets are to specific. So my solution for this issue looks like this. Thanks for all the suggestions. ``` RewriteCond %{HTTP_HOST} ^www\.site1\.com [NC] RewriteRule ^some https://www.site1.de/shop/some [R=301, L] RewriteCond %{HTTP_HOST} ^www\.site1\.com [NC] RewriteRule ^page https://www.site1.de/random/page [R=301, L] RewriteCond %{HTTP_HOST} ^www\.site1\.com [NC] RewriteRule ^settings https://www.site1.de/whatever/settings [R=301, L] ``` Upvotes: 0
2018/03/15
241
1,027
<issue_start>username_0: How can we schedule the orders to be exported into FTP for every 1 hour in the big commerce? I can export it manually but i need something to run automatically to export the orders data to FTP.Is it possible in BigCommerce? Thanks, Manoj<issue_comment>username_1: At this time you are not able to schedule downloads from the FTP. You can write your own program to do that. We also offer webhooks where you can get order notifications in almost real time. This will also require custom coding and if you need assistance we have a list of [partners](https://www.bigcommerce.com/partners/) who can help out. <https://developer.bigcommerce.com/api/#webhooks-overview> Upvotes: 0 <issue_comment>username_2: You could write a script to pull orders from the API on an hourly interval (or even better, respond to orders as they come in by using webhooks). If you needed to retrieve the orders from a folder in WebDAV, you could also automate the browser with Selenium to do regular order exports. Upvotes: 2
2018/03/15
429
1,768
<issue_start>username_0: I have created a memory allocation library that can't be collected by GC. (<https://github.com/10sa/Unmanaged-Memory>) The heap area allocated by this library is basically obtained by using the WinAPI GetProcessHeap() function. You can also create a heap area and assign it to it. However, the function used to create the heap area is the HeapCreate function. Question is, **1. Is this memory area (GetProcessHeap()) managed by GC?** **2. If you create a new heap area using the HeapCreate function, can the generated heap area be collected by the GC?** **3. If all of the above questions are true, How can I create a memory region in C # that is not collected without using Global Heap?**<issue_comment>username_1: 1. no; the clue is in the name ("unmanaged memory"), and in the fact that it is being allocated by the OS, not the CLR 2. no! 3. n/a What are you trying to do here? There are already extensive inbuilt mechanisms for allocating unmanaged memory through the CLR without needing an external tool. Additionally, in the examples: allocating 4 bytes in unmanaged memory is **terribly terribly** expensive and unnecessary. Usually when we talk about unmanaged memory we're talking about *slabs* of memory - huge chunks that we then sub-divide and partition internally via clever code. Upvotes: 4 [selected_answer]<issue_comment>username_2: In Win32/Win64 and C/C++ the Heap API were a godsend, allowing any amount of temporary allocation, with all allocations from the custom heap being freed in a single call. They are likely unnecessary in .NET. Allow me some skepticism for Microsoft's advice on good practices. I remember a division meeting where we were told that memory leaks are an inescapable fact of life. Upvotes: 0
2018/03/15
572
2,195
<issue_start>username_0: I have a question about calling MVC Controller and action method on button click. What I basically trying to achieve is pass some values as parameters to my action method. This is my button: ``` ``` I have my code wrapped up inside a document.ready function ``` $("#add").on("click", function () { var var1= $("textboxName")[0].value var var2= $("#textboxSurname")[0].value window.location.href = ('/Web/AddInformation?var1=' + var1 + '&var2=' + var2) }); ``` And this is my Action method: ``` public ActionResult AddInformation(string var1, string var2) { //code } ``` The point is to allow the user to add those variables as much as they want before the saved information is wrapped up in HTTP Post request. This is driving me crazy because I have the same button (different ID of course) and similar Jquery code that is doing the exact same thing and it work fine. However this button just refuse to work. Is this code correct? or did I missed something. NOTE: I am aware that there is very similar question: [Here](https://stackoverflow.com/questions/2503923/html-button-calling-an-mvc-controller-and-action-method) But didn't find an answer to my problem there.<issue_comment>username_1: Use below code to get the textbox values ``` var var1 = $("textboxName").val() var var2 = $("#textboxSurname").val() ``` Upvotes: 0 <issue_comment>username_2: i know the answer is set but its just to clear out the question in javascript we ussually use thing like ``` document.getElementsByName("fooName")[0].value; ``` what[0]--> suggests is that you are selecting the first element with that specific name,means the page may or may not contain more with the same name that meaans ``` textbox name=foo textbox name==foo ``` would be like ``` document.getElementsByName("foo")[0].value; document.getElementsByName("foo")[1].value; ``` where as in jquery you dont need that right now you tried to merge jquery functionality with javascript which sometimes work and sometimes may not when using jquery try to use standerd jquery chainnig instead of venilla javascript Upvotes: 2 [selected_answer]
2018/03/15
1,019
4,053
<issue_start>username_0: I have created a form in Angular 2 with which users can edit a `SearchProfile` which they can select from a list. Initially everything works fine but when i select a different item from the list of `SearchProfile`s I receive the following exception: `There is no FormControl instance attached to form control element with name: controlName`. The whole thing consists of 3 elements: 2 components `SelectProfileComponent`, `SearchProfileComponent` and a service `ProfileService`. `ProfileService` contains the `ActiveProfile` which is the selected `SearchProfile` for editing. `ProfileService` looks like this: ``` @Injectable() export class ProfileService { private activeProfileSource = new ReplaySubject(); activeProfile$ = this.activeProfileSource.asObservable(); constructor(private http: Http) { this.selectProfile(); } public getSearchProfile(profileId: number = null): Observable { let url = `?profileid=${profileId}`; this.http.get(url).map((result) => { return .result.json(); }); } public selectProfile(profileId: number = null) { this.getSearchProfile(profileId).subscribe((p) => { this.activeProfileSource.next(p); }); } } ``` `SelectProfileComponent` contains a list with profile which triggers a `change`-event when a `SearchProfile` is selected. ``` export class ProfileSelectionComponent implements OnInit { private profiles: ISearchProfile[] = null; constructor(private profileService: ProfileService) {} //get profiles logic public setActiveProfile(profileId: number): void { this.profileService.selectProfile(profileId); } } ``` The `SearchProfileComponent` has a `Subscription` to the `activeProfile` and should show the properties of the `activeProfile` so the user can edit them. `SearchProfileComponent` looks like this: ``` export class SearchProfileComponent implements OnInit { private isLoading: boolean = true; private activeProfileSubscription: Subscription; private searchProfile: ISearchProfile = null; public profileForm: FormGroup; constructor(private profilService: ProfileService private formBuilder: FormBuilder) { } ngOnInit() { this.activeProfileSubscription = this.profileService.activeProfile$.subscribe((profile: ISearchProfile) => { this.searchProfile = profile; this.createForm(); this.isLoading = false; }); } private createForm() { this.profileForm = this.formBuilder.group({ ["name"]: [this.searchProfile.name, null] }); } } ```<issue_comment>username_1: The creation of your `FormGroup` is a little bit wrong. You dont need to wrap the control name in brackets and double quotes. Read more about [reactive forms](https://angular.io/guide/reactive-forms) on official angular docs. Change your creation of FormGroup from this: ``` this.profileForm = this.formBuilder.group({ ["name"]: [this.searchProfile.name, null] }); ``` to this: ``` this.profileForm = this.formBuilder.group({ name: [this.searchProfile.name] }); ``` And you should make some changes in your html. Hint: If you are using reactive forms, you don't need `[(ngModel)]` on inputs, remove that. Here is right html for you input: ``` ``` Upvotes: 3 <issue_comment>username_2: I solved this in this way: Before: ``` formControlName="description" ``` After: ``` [formControl]="form.controls['description']" ``` Upvotes: 8 [selected_answer]<issue_comment>username_3: I solved this issue by initializing form once in the component constructor i.e. ``` constructor() { this.form = this.initForm(); } ``` OR ``` ngOnInit() { this.form = this.initForm(); } ``` and remove the re-initialization of the form in the component anywhere in the component without constructor i.e. ``` this.form = this.initForm(); ``` Upvotes: 3 <issue_comment>username_4: I found that using the `[formControl]="$form.something"` method worked well. Clunky, but that's Angular for you. Upvotes: -1
2018/03/15
484
1,589
<issue_start>username_0: I have a gitlab repo: <http://gitlabPerso/gitlab/PROJECTS/my-project.git> And I would like to add it to my current composer.json project. However it keeps saying me: > > * The requested package project/MyProjectBundle could not be found in any version, there may be a typo in the package name. > > > This is what I tried: ``` "repositories": [ { "type": "package", "package": { "name": "project/MyProjectBundle", "version": "dev-master", "type": "package", "source": { "url": "http://gitlabPerso/gitlab/PROJECTS/my-project.git", "type": "git", "reference": "master" } } } ], "require": { "project/MyProjectBundle": "*" } ``` And the composer.json in this project looks like this: ``` { "name" : "project/MyProjectBundle", "description" : "some description", "type" : "symfony-bundle", "license": [ "MIT" ], "require" : { "php" : ">=5.3.0" }, "minimum-stability": "dev", "prefer-stable": true } ``` I tried many other solutions I found on the net, I RTFM, but it still doesn't work.<issue_comment>username_1: Try with: ``` "repositories": [ { "type": "vcs", "url": "http://gitlabPerso/gitlab/PROJECTS/my-project.git" } ], "require": { "project/MyProjectBundle": "*" } ``` Upvotes: 1 <issue_comment>username_2: I finally find this solution: ``` "repositories": [ { "type": "git", "url": "repogit.git" } ], ``` Upvotes: 1 [selected_answer]
2018/03/15
375
1,346
<issue_start>username_0: I am trying to implement parallel running TestNG tests with selenium grid, where grid gets dynamic nodes attached. Based on the number of nodes in the grid I want to increase or decrease the number of threads in the TestNG. Is it possible if so How? I have tried following cases. ```java public class SuiteAlterer implements IAlterSuiteListener { @Override public void alter(List suites) { // TODO Auto-generated method stub System.err.println("\*\*Alter is invoked\*\*"); int count = NodeInfoFromGrid.getNumberOfNodes();//returns number of grid nodes that are free. if (count <= 0) { return; } for (XmlSuite suite : suites) { suite.setThreadCount(count); } } } ``` In the Listener `OnStart(ITestContext context)` added following statement: ```java context.getSuite().getXmlSuite().setThreadCount(NodeInfoFromGrid.getNumberOfNodes()); ``` But TestNG is not honoring above statement.<issue_comment>username_1: Try with: ``` "repositories": [ { "type": "vcs", "url": "http://gitlabPerso/gitlab/PROJECTS/my-project.git" } ], "require": { "project/MyProjectBundle": "*" } ``` Upvotes: 1 <issue_comment>username_2: I finally find this solution: ``` "repositories": [ { "type": "git", "url": "repogit.git" } ], ``` Upvotes: 1 [selected_answer]
2018/03/15
463
1,609
<issue_start>username_0: I need to write huge files ( more than 1 million lines) and send the file to a different machine where I need to read it with a Java `BufferedReader`, one line at a time. I was using indetned Json format but it turned out to be not very handy, it requires too much coding and that consumes extra RAM/CPU. I'm looking for something that looks like this: ``` client:id="1" name="jack" adress="House N°1\nCity N°3 \n Country 1" age="20" client:id="2" name="alice" adress="House N°2\nCity N°5 \n Country 2" age="30" vihecul:id="1" model="ford" hp="250" fuel="diesel" vihecul:id="2" model="nisan" hp="190" fuel="diesel" ``` This way I can read the objects one at a time. I know about url.encode & base64, but I'm trying to keep shorter readable lines. So any suggestions please!<issue_comment>username_1: What about reading/writing files in binary format using `DataInputStream` and `DataOutputStream`? Of course, your data must have fixed structure, but as a benefit you'll get smaller file sizes and faster reading/writing. Upvotes: 1 <issue_comment>username_2: With the huge files, any textual data formats, specially with the markup data like JSON, YAML or XML, is not a very nice solution. I can suggest to use a universal binary format, like [Google Protocol Buffers](https://developers.google.com/protocol-buffers/) or [ASN1](https://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One). The Google Protocol Buffers is much easy to get started. Of course if you just need a Java-To-Java data transferring, you can use java out of the box serialization. Upvotes: 2
2018/03/15
432
1,473
<issue_start>username_0: ``` router.post('/:token',(req,res)=>{ let language= req.query.l let name= req.query.n let param =[] if(req.path.length == 5){ param.push({ language=language },{ name=name }) ddp.person_connected(param,function(err,res){ if(err){ res.err=err }else{ res.sucess=true res.send(param).listen } }) res.sendStatus(200) }else{ res.sendStatus(401) } }) ``` I want to check if my path ( token ) is equal to the path length that's working, i can get all the data but i want to store it on my database, so i get the error > > TypeError: Cannot set property 'err' of undefined > > > Maybe i have to do a promise ?<issue_comment>username_1: What about reading/writing files in binary format using `DataInputStream` and `DataOutputStream`? Of course, your data must have fixed structure, but as a benefit you'll get smaller file sizes and faster reading/writing. Upvotes: 1 <issue_comment>username_2: With the huge files, any textual data formats, specially with the markup data like JSON, YAML or XML, is not a very nice solution. I can suggest to use a universal binary format, like [Google Protocol Buffers](https://developers.google.com/protocol-buffers/) or [ASN1](https://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One). The Google Protocol Buffers is much easy to get started. Of course if you just need a Java-To-Java data transferring, you can use java out of the box serialization. Upvotes: 2
2018/03/15
378
1,319
<issue_start>username_0: I have Solr 7.2.1 and in my managed-schema.xml file I have a field which represents date object of type "pDate". Now I need to index also the time of the day, but I saw I can't search for the time with "pDate" field type. If I query solr searching for `my_date_field:[2018-03-12T00:00:00.000Z TO *]` it works; instead if i search `[2018-03-12T12:00:00.000Z TO *]` I can't find any results. so, basically, what type is better to use to achieve that ? Is the field type the origin of the problem ?<issue_comment>username_1: What about reading/writing files in binary format using `DataInputStream` and `DataOutputStream`? Of course, your data must have fixed structure, but as a benefit you'll get smaller file sizes and faster reading/writing. Upvotes: 1 <issue_comment>username_2: With the huge files, any textual data formats, specially with the markup data like JSON, YAML or XML, is not a very nice solution. I can suggest to use a universal binary format, like [Google Protocol Buffers](https://developers.google.com/protocol-buffers/) or [ASN1](https://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One). The Google Protocol Buffers is much easy to get started. Of course if you just need a Java-To-Java data transferring, you can use java out of the box serialization. Upvotes: 2
2018/03/15
1,113
3,642
<issue_start>username_0: I have `JavaScript` tree data like this. ```js const tree = { children:[ {id: 10, children: [{id: 34, children:[]}, {id: 35, children:[]}, {id: 36, children:[]}]}, {id: 10, children: [ {id: 34, children:[ {id: 345, children:[]} ]}, {id: 35, children:[]}, {id: 36, children:[]} ] }, {id: 11, children: [{id: 30, children:[]}, {id: 33, children:[]}, {id: 3109, children:[]}]} ], id: 45 } const getByID = (tree, id) => { let result = null if (id === tree.id) { return tree } else { if(tree.children){ tree.children.forEach( node=> { result = getByID(node, id) }) } return result } } const find345 = getByID(tree, 345) console.log(find345) ``` I was try to find item by its id from this tree. im using recursive function to iterate the tree and its children, but it wont find the item as i expected. its always return null. expected to return `{id: 345, children:[]}`<issue_comment>username_1: You need to exit the loop by using a method which allows a short circuit on find. The problem with visiting nodes but already found the node, is the replacement of the result with a later wrong result. You need to exit early with a found node. [`Array#some`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) allows to iterate and to exit the loop if a truty value is returned. In this case the result is truthy on find. ```js const tree = { children: [{ id: 10, children: [{ id: 34, children: [] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 10, children: [{ id: 34, children: [{ id: 345, children: [] }] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 11, children: [{ id: 30, children: [] }, { id: 33, children: [] }, { id: 3109, children: [] }] }], id: 45 }; const getByID = (tree, id) => { let result = null if (id === tree.id) { return tree } else { if(tree.children){ tree.children.some(node => result = getByID(node, id)); // ^^^^ exit if found // ^^^^^^^^^^^^^^^^^^^^^^^^^^ return & assign } return result; } } const find345 = getByID(tree, 345) console.log(find345) ``` A bit shorter ```js var tree = { children: [{ id: 10, children: [{ id: 34, children: [] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 10, children: [{ id: 34, children: [{ id: 345, children: [] }] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 11, children: [{ id: 30, children: [] }, { id: 33, children: [] }, { id: 3109, children: [] }] }], id: 45 }, getByID = (tree, id) => { var temp; return tree.id === id ? tree : (tree.children || []).some(o => temp = getByID(o, id)) && temp; }; console.log(getByID(tree, 345)); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: We can also use reduce method for recursive function ``` function findAllByKey(obj, keyToFind) { return Object.entries(obj) .reduce((acc, [key, value]) => (key === keyToFind) ? acc.concat(value) : (typeof value === 'object' && value) ? acc.concat(findAllByKey(value, keyToFind)) : acc , []) || []; } ``` Upvotes: -1
2018/03/15
930
3,273
<issue_start>username_0: hay.. i have function delete on my controller .. in client side when i am delete catagories is work.. but, when i check oh phpmyadmin. the categories still has not been deleted.. this is my categoriesController for delete.. ``` ......... public function destroy(Request $request,$id) { try { DB::beginTransaction(); $category = Category::find($id); $category->delete(); $request->session()->flash('alert-success','Data successfully deleted'); DB::commit(); return redirect(route('categories.index')); } catch (Exception $e) { return Redirect::back()->with('error_message', $e->getMessage())->withInput(); } } ``` please help.. thanks<issue_comment>username_1: You need to exit the loop by using a method which allows a short circuit on find. The problem with visiting nodes but already found the node, is the replacement of the result with a later wrong result. You need to exit early with a found node. [`Array#some`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) allows to iterate and to exit the loop if a truty value is returned. In this case the result is truthy on find. ```js const tree = { children: [{ id: 10, children: [{ id: 34, children: [] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 10, children: [{ id: 34, children: [{ id: 345, children: [] }] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 11, children: [{ id: 30, children: [] }, { id: 33, children: [] }, { id: 3109, children: [] }] }], id: 45 }; const getByID = (tree, id) => { let result = null if (id === tree.id) { return tree } else { if(tree.children){ tree.children.some(node => result = getByID(node, id)); // ^^^^ exit if found // ^^^^^^^^^^^^^^^^^^^^^^^^^^ return & assign } return result; } } const find345 = getByID(tree, 345) console.log(find345) ``` A bit shorter ```js var tree = { children: [{ id: 10, children: [{ id: 34, children: [] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 10, children: [{ id: 34, children: [{ id: 345, children: [] }] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 11, children: [{ id: 30, children: [] }, { id: 33, children: [] }, { id: 3109, children: [] }] }], id: 45 }, getByID = (tree, id) => { var temp; return tree.id === id ? tree : (tree.children || []).some(o => temp = getByID(o, id)) && temp; }; console.log(getByID(tree, 345)); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: We can also use reduce method for recursive function ``` function findAllByKey(obj, keyToFind) { return Object.entries(obj) .reduce((acc, [key, value]) => (key === keyToFind) ? acc.concat(value) : (typeof value === 'object' && value) ? acc.concat(findAllByKey(value, keyToFind)) : acc , []) || []; } ``` Upvotes: -1