text:
Q: g++ does not compile on Mac OS X Mavericks I've got a little problem with my new MacBook and Mac OS X Mavericks.
On my Linux Machine my code compiles without problems, but on my Mac I get cryptic error messages I do not understand.
For example something like this:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/list:240:62: error:
  invalid use of non-static data member '__ptr_'
explicit __list_iterator(__node_pointer __p) _NOEXCEPT : __ptr_(__p) {}

Can someone please help me? I have really no idea what to do...
EDIT:
So... Here is more from the error log. It's the first part. The full log is too long...
g++ SpinDerivatorController.cpp functions.cpp globalVariables.cpp main.cpp mathFunctions.cpp svd.cpp -o testCompile
In file included from SpinDerivatorController.cpp:8:
In file included from ./SpinDerivatorController.h:11:
In file included from ./SpinOperators.h:11:
In file included from ./SpinStateTemplate.h:11:
In file included from ./StateTemplateSimple.h:19:
./SeriesTemplate.h:217:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
 ./SeriesTemplate.h:314:4: note: in instantiation of member function      'SeriesTemplate<std::__1::complex<double>,
  ExponentsTemplate<int> >::operator*=' requested here
    s3*=s2;
      ^
./StateTemplateSimple.h:444:25: note: in instantiation of function template specialization
  'operator*<std::__1::complex<double>, ExponentsTemplate<int> >' requested here
                                    x += (it1->second) * (it2->second);
                                                       ^
 SpinDerivatorController.cpp:127:24: note: in instantiation of function template specialization
  'operator*<SeriesTemplate<std::__1::complex<double>, ExponentsTemplate<int> > >' requested here
                    b[k]=(inputStates[j]*outputStates[i]).real();
                                        ^
1 warning generated.
In file included from functions.cpp:8:
In file included from ./functions.h:15:
In file included from ./StateTemplateSimple.h:12:
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/list:240:62: error:
  invalid use of non-static data member '__ptr_'
explicit __list_iterator(__node_pointer __p) _NOEXCEPT : __ptr_(__p) {}
                                                         ^~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/list:240:69: error:
  use of undeclared identifier '__p'
explicit __list_iterator(__node_pointer __p) _NOEXCEPT : __ptr_(__p) {}
                                                                ^
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/list:240:60: error:
  C++ requires a type specifier for all declarations
explicit __list_iterator(__node_pointer __p) _NOEXCEPT : __ptr_(__p) {}
                                                       ^
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/list:245:21: error:
  expected member name or ';' after declaration specifiers
template<class, class> friend class list;
                ^
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/list:245:21: error:
  C++ requires a type specifier for all declarations
template<class, class> friend class list;
                ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/list:245:20: error:
  expected ';' at end of declaration list
template<class, class> friend class list;
               ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/list:263:5: error:
  expected member name or ';' after declaration specifiers
{
^
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/list:240:50: error:
  expected expression
explicit __list_iterator(__node_pointer __p) _NOEXCEPT : __ptr_(__p) {}
                                             ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__config:289:21: note:
  expanded from macro '_NOEXCEPT'
#  define _NOEXCEPT throw()
                ^
./nr3.h:71:59: note: expanded from macro 'throw'
 {printf("ERROR: %s\n     in file %s at line %d\n", message,__FILE__,__LINE__); throw(1);}

A: You define a macro named throw in nr3.h on line 71. This clashes with the use of the throw keyword in the c++ standart library.
An easy solution would be to name the macro something else, like MY_PROJECT_THROW.
It is anyway a good practice to prefix all macros you define with a uniqe string to prevent such name clashes.


text:
Q: Размещение названий выбранных ListBoxItem-ов в string[] Как поместить названия выбранных элементов ListBox-а в строковой массив?

A: Выбранные элементы ListBox
В общем случае:
'ListBox_name'.SelectedItems.Cast<'Model_name'>().Select(x => x.'propertyName');

Например:
SomeListBox.SelectedItems.Cast<MyModel>().Select(x => x.Name);

Если Вы используете MVVM с соответствующим биндингом ListBox.ItemsSource, то нужно в классе модели описать свойство IsSelected , сделать Биндинг далее во ViewModel выполнить:
ListOfItems.Where(x => x.IsSelected).Select(x => x.Name);

redpajama_set_name: RedPajamaStackExchange


text:
Q: All probability values are less than 0.5 on unseen data I have 15 features with a binary response variable and I am interested in predicting probabilities than 0 or 1 class labels. When I trained and tested the RF model with 500 trees, CV, balanced class weight, and balanced samples in the data frame, I achieved a good amount of accuracy and also good Brier score. As you can see in the image, the predicted probabilities values of class 1 on test data are in between 0 to 1.
Here is the Histogram of predicted probabilities on test data:

with majority values at 0 - 0.2 and 0.9 to 1, which is much accurate.
But when I try to predict the probability values for unseen data or let's say all data points for which value of 0 or 1 is unknown, the predicted probabilities values are between 0 to 0.5 only for class 1. Why is that so? Aren't the values should be from 0.5 to 1?
Here is the histogram of predicted probabilities on unseen data:

I am using sklearn RandomforestClassifier in python. The code is below:
#Read the CSV
df=pd.read_csv('path/df_all.csv')

#Change the type of the variable as needed
df=df.astype({'probabilities': 'int32', 'CPZ_CI_new.tif' : 'category'})

#Response variable is between 0 and 1 having actual probabilities values
y = df['probabilities']

# Separate majority and minority classes
df_majority = df[y == 0]
df_minority = df[y == 1]

# Upsample minority class
df_minority_upsampled = resample(df_minority,
                                 replace=True,  # sample with replacement
                                 n_samples=100387,  # to match majority class
                                 random_state=42)  # reproducible results

# Combine majority class with upsampled minority class
df1 = pd.concat([df_majority, df_minority_upsampled])

y = df1['probabilities']
X = df1.iloc[:,1:138]

#Change interfere values to category
y_01=y.astype('category')

#Split training and testing
X_train, X_valid, y_train, y_valid = train_test_split(X, y_01, test_size = 0.30, random_state = 42,stratify=y)

#Model

model=RandomForestClassifier(n_estimators = 500,
                           max_features= 'sqrt',
                           n_jobs = -1,
                           oob_score = True,
                           bootstrap = True,
                           random_state=0,class_weight='balanced',)
#I had 137 variable, to select the optimum one, I used RFECV
rfecv = RFECV(model, step=1, min_features_to_select=1, cv=10, scoring='neg_brier_score')
rfecv.fit(X_train, y_train)

#Retrained the model with only 15 variables selected
rf=RandomForestClassifier(n_estimators = 500,
                           max_features= 'sqrt',
                           n_jobs = -1,
                           oob_score = True,
                           bootstrap = True,
                           random_state=0,class_weight='balanced',)

#X1_train is same dataframe with but with only 15 varible
rf.fit(X1_train,y_train)

#Printed ROC metric
print('roc_auc_score_testing:', metrics.roc_auc_score(y_valid,rf.predict(X1_valid)))

#Predicted probabilties on test data
predv=rf.predict_proba(X1_valid)
predv = predv[:, 1]
print('brier_score_training:', metrics.brier_score_loss(y_train, predt))
print('brier_score_testing:', metrics.brier_score_loss(y_valid, predv))

#Output is,
roc_auc_score_testing: 0.9832652130944419
brier_score_training: 0.002380976369884945
brier_score_testing: 0.01669848089917487

#Later, I have images of that 15 variables, I created a data frame out(sample_img) of it and use the same function to predict probabilities.

IMG_pred=rf.predict_proba(sample_img)
IMG_pred=IMG_pred[:,1]

A: The results shown for your test data are not valid; you perform a mistaken procedure that has two serious consequences, which invalidate them.
The mistake here is that you perform the minority class upsampling before splitting to train & test sets, which should not be the case; you should first split into training and test sets, and then perform the upsampling only to the training data and not to the test ones.
The first reason why such a procedure is invalid is that, this way, some of the duplicates due to upsampling will end up both to the training and the test splits; the result being that the algorithm is tested with some samples that have already been seen during training, which invalidates the very fundamental requirement of a test set. For more details, see own answer in Process for oversampling data for imbalanced binary classification; quoting from there:

I once witnessed a case where the modeller was struggling to understand why he was getting a ~ 100% test accuracy, much higher than his training one; turned out his initial dataset was full of duplicates -no class imbalance here, but the idea is similar- and several of these duplicates naturally ended up in his test set after the split, without of course being new or unseen data...

The second reason is that this procedure shows biased performance measures in a test set that is no longer representative of reality: remember, we want our test set to be representative of the real unseen data, which of course will be imbalanced; artificially balancing our test set and claiming that it has X% accuracy when a great part of this accuracy will be due to the artificially upsampled minority class makes no sense, and gives misleading impressions. For details, see own answer in Balance classes in cross validation (the rationale is identical for the case of train-test split, as here).
The second reason is why your procedure would still be wrong even if you had not performed the first mistake, and you had proceeded to upsample the training and test sets separately after splitting.
I short, you should remedy the procedure, so that you first split into training & test sets, and then upsample your training set only.


text:
Q: When is an equation independent of a certain variable? Consider an algebraic equation, whose sides are constituted only by products of functions of single variables.
$$f(x)g(y)h(z) = i(x)j(y)k(z)$$
$f,g,h,i,j,k$ are complex functions of real variable and so $x,y,z \in \mathbb{R}$. If $y$ is the variable to be considered, it is possible to isolate in both sides a factor which is function of just $y$ by hypothesis.
In this kind of problems, what can be a general condition for the equation to be independent from $y$? That is: the equation must be the same for all the real values of $y$, $\forall y \in \mathbb{R}$.
I roughly would answer that the condition is $g(y) = j(y)$, so that they simplify in the above expression: but is it rigorous enough? For example, when $y$ is such that $g(y) = h(y) = 0$, if I simplify $g(y)$ and $h(y)$ I am dividing by $0$.
A function is said independent from a certain variable if its (partial) derivative with respect to that variable is $0$. But what about a whole equation? When it can be said independent from a certain variable?

Note: even if slightly different, this question is related to my previous one.

A: If $g(y)=j(y)=0$, then your equation
$$\operatorname{eqn}:\:\mathbb{R}^3\mapsto\{\bot,\top\},\;\;\operatorname{eqn}(x,y,z):=f(x)g(y)h(z)=i(x)j(y)k(z)\tag1\label{1}$$
becomes $0=0$, i.e.
$$\operatorname{eqn}:\:\mathbb{R}^3\mapsto\{\top\},\;\;\operatorname{eqn}(x,y,z):=\top,\tag2\label{2}$$
and it is independent of $y$, because for each $(x,z)$ in $\mathbb{R}^2$ for which we have $\eqref{1}$ (that is, any $(x,z)$ in $\mathbb{R}^2)$, we also have $\eqref{2}$ (because we always have $\eqref{2}$), so $g(y)=j(y)=0$ is not really a problem, as in that case you do not need to divide by anything in the first place (notice that \eqref{2} is actually independent of any variables).
To answer the question, $g(y)=j(y)$ certainly works, but is an overkill. You actually just only need both $g$, $j$ to be constant, and not necessarily equal to each other.


text:
Q: getting runtime exception while running a jar I created a jar file which contains a main class and its dependent jar.
I wrote my own manifest so that I can also include the dependencies.
The problem comes when I try to run the jar file; it gives me the following:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook

here is the folder structure
ExcelCopy.jar
|
|-com/utility/ExcelFormat.java
|
|-lib/poi-3.9.jar
|
|-META-INF/Manifest.mf

Manifest.mf content
Manifest-Version: 1.0
Class-Path: lib/poi-3.9jar
Created-By: 1.7.0_25 (Oracle Corporation)
Main-Class: com.utility.ExcelFormat

A: You don't need to bundle lib/poi-3.9.jar within your ExcelCopy.jar. Remove it from the JAR, then you will have:
ExcelCopy.jar
|
|-com/utility/ExcelFormat.java
|-META-INF/Manifest.mf

Then you have:
ExcelCopy.jar
lib/poi-3.9jar

Running "java -jar ExcelCopy.jar" shall work.

A: Thanx @shuang. I tried simple logic and it worked
I extracted the required classes from poi-3.9.jar so now I have a folder call org in which all the required classes are.
ExcelCopy.jar
|
|----com/utility/ExcelFormat.java
|
|----org/apache(long dir structure)
|
|----META-INF/Manifest.mf

and content of Manifest.mf
Manifest-Version: 1.0
Class-Path: org
Main-Class: com.utility.ExcelFormat

Now my jar is running. :D


text:
Q: How can I setup simulations of an equation with constraints? I have data on 4 items for 100 people. It is setup as follows:
#Initial Data (Items) and Weights. Shares is the final results.
items <- data.frame(Names = c("Sarah", "John", "Tom"), Phones = c(1,2,1), Cars = c(2,1,1), Boxes = c(9,14,12), Cats = c(1,2,3))
weights <- c(.5,.3,.15,.05,.95)
shares <- data.frame(Names = items[,1], Shares = 0, Rank = 0)
#Testing Weights and Calculating Rank
shares[,2] <- round((weights[1]*items[,2] + weights[2]*items[,3] + weights[3]*items[,4]+weights[4]*items[,5])^weights[5],3)
shares[,3] <- order(shares[,2], decreasing=T)

My goal is to run simulations for different weights under the following constraints:
The first weight (Phones) weights[1] >= .5
The 2nd weight (Cars)    .25 <= weights[2] <= .35
The 3rd weight (Boxes) weights[3] <= .15
The 4th weight (Cats) weights[4] = .05
Sum(weights[1:4]) = 1
weights[5] >= .95
To simulate different weights test steps of 0.01, i.e. one scenario weights <- c(.51,.3,.14,.05,.95) and these would change to test all possible values under the constraints.
I want to run simulations under these scenarios, my step could be 0.01, and track how an individual does in terms of their rank, i.e. if I care about Tom I want to follow his rank across different simulations. Rank is what matters. I can organize the data when I get it but how can I setup the simulations under this scenario?


text:
Q: Using IMPORTXML in Google Sheets to scrape data from Transfermarkt I'm trying to see if it's possible to scrape data from Transfermarkt.com to import into a Google Sheets doc.
Currently, I'm trying to import the team data from a player's profile page (see example URL here: https://www.transfermarkt.co.uk/joao-palhinha/profil/spieler/257455) but in future may want to import other data as well.
I wonder if it's possible to scrape data in this way from Transfermarkt, but if it is, any advice on what I'm doing wrong would be very much appreciated!
Right now I'm using, =IMPORTXML(B1,"/html/body/div[3]/main/header/div[4]/div/span[1]/a") where the URL is in B1. I copied the Full XPath from the HTML, but have also tried this by copying just the XPath too.
It says Loading for a few seconds before returning N/A, with an error message 'Resource at URL not found'.
I'm expecting the result in this instance to be Fulham.
Thanks


text:
Q: syntax error, unexpected '$post_id' (T_VARIABLE) in Laravel I have a problem with my function in laravel
I am trying to execute the following code:
public static function likePost($value)
{
   $post_id = $value['post_id'];
   $user_id = $value['user_id'];
   if($value['liked'] == "1")
   {
      $model = new Like;
      $model->fill($value);
      $model->created = time();
      if($model->save())
      {
        $post = Post::with('user')->where('id', '=', $value['post_id'])->get()->first();
        $text = $post['user']['name']." ".Notification::TEXT_LIKE_POST;
        Push::push($text, $value['post_id']);
      }
   }
   else
   {
      Like::where('user_id', '=', $user_id)->where('post_id', '=' $post_id)->get()->first()->delete();
   }
}

But I'm getting the following error: syntax error, unexpected '$post_id' (T_VARIABLE)
What is wrong with this function? Inside of the if the $post_id work fine, but in the else it don't work.

A: As @andrewsi said you have missing comma after '='. Also you can just use this code which will do the same job:
Like::where('user_id', $user_id)->where('post_id', $post_id)->delete();

A: you are missing a , in

Like::where('user_id', '=', $user_id)->where('post_id', '=' $post_id)->get()->first()->delete();

it should be

Like::where('user_id', '=', $user_id)->where('post_id', '=', $post_id)->get()->first()->delete();

or

Like::where('user_id', '=', $user_id)->where('post_id', $post_id)->get()->first()->delete();


text:
Q: Line break in SSRS expression I'm having trouble adding a line break in SSRS 2008.
I've tried all of these different ways but nothing is doing it.
"+ chr(10) +" , "& chr(10) &" , "& chr(13) & chr(10) &" , "& vbcrlf &" , "+ vbcrlf +" , "Environment.NewLine"
Here's my textbox expression:
=IIF(First(Fields!VCHTYPE.Value, "Dataset1")="C","This is a huge paragrpah of text." +
vbcrlf + "separated by line feeds at each paragraph." +
vbcrlf + vbcrlf + "I want to separate the paragraphs." +
vbcrlf + vbcrlf + "Its not working though."
, "This is the second huge paragraph of text." +
vbcrlf + "separated by line feeds at each paragraph." +
vbcrlf + vbcrlf + "I want to separate the paragraphs." +
vbcrlf + vbcrlf + "Its not working though." )

A: UseEnvironment.NewLine instead of vbcrlf

A: In Order to implement Line Break in SSRS, there are 2 ways

*

*Setting HTML Markup Type
Update the Markup Type of the placeholder to HTML and then make use of
 tag to introduce line break within the expression

="first line of text. Param1 value: " & Parameters!Param1.Value & "
" & Parameters!Param1.Value

*Using Newline function
Make use of Environment.NewLine() function to add line break within the expression.

="first line of text. Param1 value: " & Parameters!Param1.Value & Environment.NewLine()
 & Parameters!Param1.Value
Note:- Always remember to leave a space after every "&" (ampersand) in order to evaluate the expression properly

A: You should NOT quote your Environment.NewLine man. Try "Your Text" & Environment.NewLine.

A: Use the vbcrlf for new line in SSSR. e.g.
= First(Fields!SAPName.Value, "DataSet1") & vbcrlf & First(Fields!SAPStreet.Value, "DataSet1") & vbcrlf & First(Fields!SAPCityPostal.Value, "DataSet1") & vbcrlf & First(Fields!SAPCountry.Value, "DataSet1")

A: I've always had luck with the Chr(10) & Chr(13) - I have provided a sample below.  This is an expression for an address text box I have in a report.
=Iif(Fields!GUAR_STREET_2.Value <> "",Fields!GUAR_STREET.Value & Chr(10) & Chr(13) & LTrim(Fields!GUAR_STREET_2.Value),Fields!GUAR_STREET.Value)

Also, if you are building a string you need to concatenate stuff together with an & not a +  Here is what I think your example should look like
    =IIF(First(Fields!VCHTYPE.Value, "Dataset1")="C","This is a huge paragrpah of text." &
Chr(10) & Chr(13) & "separated by line feeds at each paragraph." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "I want to separate the paragraphs." &
Chr(10) & Chr(13) &  Chr(10) & Chr(13) & "Its not working though."
, "This is the second huge paragraph of text." &
Chr(10) & Chr(13) & "separated by line feeds at each paragraph." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "I want to separate the paragraphs." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "Its not working though." )

A: If your placeholder is in html enabled mode then "
" will work as a newline

A: It wasn't working for me either.  vbcrlf and Environment.Newline() both had no effect.  My problem was that the Placeholder Properties had a Markup type of HTML.  When I changed it to None, it worked like a champ!

A: This works for me:
(In Visual Studio)

*

*Open the .rdl file in Designer (right-click on file in Solution
Explorer > View Designer)

*Right-click on the Textbox you are working with, choose Expression

*In the Set expression for: Value box enter your expression like:
="first line of text. Param1 value: " & Parameters!Param1.Value & Environment.NewLine()
& "second line of text. Field value: " & Fields!Field1.Value & Environment.NewLine()
& "third line of text."

A: You Can Use This One
="Line 1" & "
" & "Line 2"

A: In my case, Environment.NewLine was working fine while previewing the report in Visual Studio.  But when I tried to publish the rdl to Dynamics 365 CE, I received the error "The report server has RDLSandboxing enabled and the Value expression for the text box 'Textbox10' contains a reference to a type, namespace, or member 'Environment' that is not allowed."
So I had to replace Environment.NewLine with vbcrlf.


text:
Q: R shiny strange behaviour of caching I am using R shiny and ggplot2.
My project layout looks like this:
global.R
server.R
ui.R
visualization.R

My visualization.R
image <- png::readPNG(source = '/path/mypng.png', native = FALSE)
ggplot(data = data) +
background_image(image)

Once I changed image path, image was changed as I was expected. When I am running visualization.R as a desktop app from R studio it works fine. But, when I am running Shiny's server.R file image is not updated. It always read same image, while image path is updated. I do not understand why.
In R studio, I also ran script rm(list = ls())
Any ideas ?
Thanks !


text:
Q: Download via FTP com JavaScript Gostaria de saber como posso estar colocando em minha página a opção do usuário fazer o download via FTP. Não quero que o usuário digite as informações para acesso ao FTP e também que ele não veja os dados do FTP que está acessando para fazer o download.
Isso é possível? Se sim como posso proceder ?

A: Até é possível fazer, mas nos browsers mais atuais você recebe uma tela de confirmação informando que pode ser uma possível fraude.

Segue o trecho:
var username = 'user';
var password = 'pass';
var server = 'toSomeServer';
window.open("ftp://" + username + ":" +
      password + "@" + server, '_blank',
      'toolbar=no,location=no,status=no,' +
      'scrollbars=auto,copyhistory=no,menubar=no,width='
      + ((screen.AvailWidth/2)-12) + ',height='
      + (screen.AvailHeight-124) +',left=' + ((screen.AvailWidth/2))
      + '),top=0,resizable=yes');

Creio que não seja a solução mais elegante para isso.
Uma boa alternativa seria você tratar isso no serverside.
No site da Wc3 tem um exemplo de conexão com PHP.
Espero ter ajudado.


text:
Q: Disable Button on Page Load I have a web page which is loading a list of items to select from and add to a list. What I would like to do is have it so that when the user searches for an item and clicks search, any items that load and are already in the users list of selected items will have their buttons disabled. I am able to disable the buttons when the user clicks the item, however if they search for the same item, the button will be clickable again
Code for button in body.component.html:
<button type="submit" *ngIf="!checkNominations(mov)" (click)="nominate(mov, $event)">Nominate</button>

Code for checking/disabling button in body.component.ts:
  nominate(mov: string, event:any){
    this.nominations.push(mov);
    event.target.disabled = true;
  }

  checkNominations(mov: Object){
    return this.nominations.indexOf(mov) !== -1;
  }

A: Managed to solve it in a different way, if anyone knows how to make this more efficient I would greatly appreciate it!
Code for button in body.component.html:
<button type="submit" *ngIf="!checkNominations(mov)" (click)="nominate(mov)">Nominate</button>
        <button type="submit" *ngIf="checkNominations(mov)" disabled="True">Nominated!</button>

Code for checking/disabling button in body.component.ts:
checkNominations(mov: Object){
    let arr = [];
    arr.push(mov);
    var isInArray = this.nominations.find(e => e.Title === arr[0].Title) !== undefined;
    return isInArray;
  }


text:
Q: How do I load multiple JSONs file into a single DataFrames in Julia? using JSON3
using DataFrames
ls = ["j1.json",j2.json","j3.json"]
df = JSON3.read.(eachline(ls)) |> DataFrame

How would I do this when I have several json files?.
Can i merge all the json files
into a single data-frame without using any loops in Julia

A: You can try
using JSON3
using DataFrames
ls = filter(endswith("json"),readdir("."))
df = JSON3.read.(read.(ls,String)) |> DataFrame


text:
Q: Ban/mark/decorate external links requiring paid membership or even "free registration" This for example:
SQL Replace ASCII With Loop
There is a link in that comment to http://www.sqlservercentral.com/articles/T-SQL/62867/
I was looking forward to reading up on some good technique, and the pop-over the page was truly obnoxious.  I am fundamentally against requiring capturing of my details (even if bogus) just to read some article.
I guess the sentiments will be same as Jeff's here
Ban URL shortening services

To me, this is the same as trying to ban curse words -- it's a fundamentally broken and bad idea.

But this is easier right? There are only so many "free registration" sites that are easily identifiable.  Maybe we can decorate them with tags next to them like "registration required" or "membership" or some such.

A: Just vote such posts down if you don't like them. And say why.
I'm with you on the matter, but this should be a matter of grass roots activism, not policy.

A: Do you really want to put up another blacklist?
If you feel strongly about it, I think an appropriate response would be a comment on the answer to the effect of:

Thank you for this answer, but it is
  behind a registration page, and I find
  that really obnoxious.

There is nothing the OP can do about that, of course.
Users are generally encouraged to put a summary in their answer describing what the link content is about, since it helps with link rot, and reduces the problem of registration pages since the link may no longer need to be followed.  You can also mention this in a comment.
I have a throwaway Yahoo email account that I use to register these kinds of pages so I can read their content.  Kinda like a giant bit bucket.  Interestingly, the messages I get in there (although I seldom read them) have a much higher signal-to-noise ratio than my spam folder.


text:
Q: How do I use Read-Only properties defined in partial (Entity Framework) classes over ADO.Net Data Services I have objects that are defined by the Entity Framework that I have then added additional methods and properties to via partial classes.  I think I understand most of the limitations around doing this, but wanted to confirm something I am seeing (or hopefully learn what I need to do to make this work).
I have a partial class that then has a read-only property that uses a couple of the items to create a calculated field that is read-only.  It was curious to see that read-only property did not come back via the ADO.Net Data Services as I was hoping/expecting.  i.e. I was expecting to see the properties on the entity framework and the property being definied in code via the partial class come via the Data Service call.
Is this the case?  Are the partial classes completely ignored when ADO.Net Data Services is querying for data?  If so what is the best practice for getting a read-only type property onto an entity (as I would like to avoid having the same partial classes with different namespaces being cut and pasted into both the client side and server side code bases).

A: From a Microsoft Forums Post: (see full post here)

"I think you are asking "How to add a
  read-only property to an existing
  entity that is exposed by the EF
  provider"? In V1, there is no good way
  to do this. For EF, we load the
  metadata using the EF metadata api's
  and hence we don't do any reflection.
  Hence additional properties that you
  might have added via a partial class
  will get ignored.
Astoria doesn't yet have a concept of
  read-only properties. So if we expose
  any other properties that is not part
  of the model, we don't know how to
  deal with them in updates. We don't
  want to lose data siliently in the
  server also."

So it looks like this is functionality that is not able to be exposed via ADO.Net Data Services.

A: There are two separate concerns here - the base model (EF), and the WCF/mex layer. Your additional properties will not be part of the edmx model, but I wonder if the issue isn't more related to the WCF/mex aspect.
However, even if it worked, ADO.NET Data Services transfers data, not logic. So relying on calculated properties isn't a safe option : the client won't have the formulae - just the original values.
To find out which it is, try making the property read/write (even if the write doesn't do anything useful), and ensure the value has a [DataMember] attribute, etc.

A: I think the problem is that with XML serialization, it only serializes properties with get and set methods. Otherwise it couldn't de-serialize. Add an empty set method to your property and see how you go.
Rob


text:
Q: Как отображать, скачивать и сохранять изображения в память телефона? Моя задача: спарсить JSON из интернета, положить их в SQLite (это я сделал), но я сохранил только пути к изображению, но не сами изображения.
Мне нужно скачать изображения из интернета, и при последующем запуске приложения загружать все эти картинки из памяти телефона. Как это сделать новичку? Может быть есть какие-то готовые библиотеки для такого рода задач? Подскажите пожалуйста
Я использую: Retrofit 2, Active Android, SQlite.

A: Да, есть библиотеки и да, лучше всего использовать их. Вот пример предварительной загрузки изображений в кэш по ссылке либой Glide:
Glide.with(context)
        .load("IMAGE_URL")
        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
        .listener(new RequestListener<String, GlideDrawable>() {
            @Override
            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                Log.e("TAG", "error while preload image by Glide");
                return false;
            }

            @Override
            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                  Log.d("onResourceReady: " + resource.getIntrinsicWidth() + "/" + resource.getIntrinsicHeight());
                return false;
            }
        })
        .preload();

После этого отображать её так (изображение возьмётся из кэша):
Glide.with(context)
        .load("IMAGE_URL")
        .into(imageView);

A:
Как это сделать новичку? Может быть есть какие-то готовые библиотеки
  для такого рода задач?

Попробуйте использовать библиотеку Glide для загрузки и кеширования изображений


text:
Q: Spring Boot H2 create log table with many-to-many relationship to other table Let's say I have a table Account, which contains info about clients accounts. I want to create a log table (containing sender and recipient fields), and every time when a request is sent to server (e.g. there was a transfer between two accounts) I want to insert info about this operation to this table.
So I supose I need to create many-to-many relationship between Account and Log table. But what joins do I need then? The sender and recipient fields in Log table have to be objects of Account class. How can I map them with Spring JPA annotations?

A: You can create the follow code to solve your problem.
Firstly, you must define the Account class in this way:
@Entity
public class Account{
   @GeneratedValue
   @Id
   private long id;
   //others fields bellow
}

and then you can create a new Log class who it has two field with the recipient and sender and both has @ManyToOne relationship like this:
@Entity
public class LogAccountTransference{
    @GenerateValue
    @Id
    private long id;
    @ManyToOne
    private Account recipient;
    @ManyToOne
    private Account sender;
    //others field about Log Table

}

If you still will have some question just tell me.


text:
Q: Mac won't boot; get the Apple logo then it becomes a prohibitory symbol I start up my early 2011 MacBook Pro, and it gives me the login screen, I enter my password, and then booting starts as normal, but about halfway through the progress bar, it stops booting entirely and comes up with this symbol.

I'm really not sure what to do. In recovery mode I'm unable to access the partition that holds the Mac OS (it's grayed out) and when I try to mount the Mac OS partition through terminal, it instead tells me that it's a FileVault or Fusion Drive - it's neither, to the best of my knowledge - and that it must be unlocked prior to mounting. So, U found the logical volume and unlocked it using diskutil corestorage command that actually unlocked volumes, and then it ended up as /dev/disk16, and I was still unable to mount /dev/disk0s2, or disk16. Trying to remove the empty Windows partition through DiskUtility results in failure because it's locked. Any and all help is greatly appreciated, as I desperately need this computer for study, and losing files on it is a non-option.

A: This means that the Mac can't find a valid startup folder to boot from.
The solution to this is to reinstall OS X – power up your Mac while holding down Cmd-R, then select Reinstall OS X (or Utilities -> Reinstall OS X).
Depending on what version of Mac OS X, you will want to select "Archive and Install" if you want to preserve your files. Follow the onscreen prompts to reinstall Mac OS X.
If you have a backup disk for your Mac, that's a bonus just in case the installation goes wrong.


text:
Q: Using a cte to retrieve a random record I found the following code, which works fine. Could someone suggest a way how I can integrate the locations table into the cte so that I get a random location_id with every row. I suspect I need another union all but I'm unsure how to get the random location_id
In this example the locations table is consecutively ordered for ease of posting but that will not be the case all the time.
 CREATE TABLE schedule_hdr AS
SELECT level AS schedule_id,
   'Schedule ' || level AS schedule_name

 FROM   dual
CONNECT BY level <= 2;

CREATE TABLE locations AS
 SELECT level AS location_id,
   'Door ' || level AS location_name,

CASE round(dbms_random.value(1,3))
        WHEN 1 THEN 'A'
        WHEN 2 THEN 'T'
        WHEN 3 THEN 'G'
     END AS location_type

FROM   dual
CONNECT BY level <= 25;

 ALTER TABLE locations
     ADD ( CONSTRAINT location_id_pk
   PRIMARY KEY (location_id));

WITH random_times (     schedule_id,    datetime, lvl ) AS (
 SELECT schedule_id,
      TRUNC(sysdate)
      +
 NUMTODSINTERVAL( FLOOR(DBMS_RANDOM.VALUE(0,23*60)), 'MINUTE' ),
     1
FROM   schedule_hdr
 UNION ALL
SELECT schedule_id,
     datetime + NUMTODSINTERVAL(FLOOR(DBMS_RANDOM.VALUE(6,11)), 'MINUTE'),
     lvl + 1
FROM   random_times
WHERE  lvl < 5
)
SELECT schedule_id,
   datetime
FROM   random_times
ORDER BY schedule_id, datetime;

A: Here's what you want:
WITH random_times (     schedule_id,    datetime, lvl ) AS (
 SELECT schedule_id,
      TRUNC(sysdate)
      +
 NUMTODSINTERVAL( FLOOR(DBMS_RANDOM.VALUE(0,23*60)), 'MINUTE' ),
     1
FROM   schedule_hdr
 UNION ALL
SELECT schedule_id,
     datetime + NUMTODSINTERVAL(FLOOR(DBMS_RANDOM.VALUE(6,11)), 'MINUTE'),
     lvl + 1
FROM   random_times
WHERE  lvl < 5
)
SELECT
   schedule_id,
   datetime,
   loc.*
FROM   random_times
      ,locations loc
where loc.location_id = (
          select location_id
          from locations
          -- you need this predicate to disable subquery caching:
          where location_id*0 = schedule_id*0+lvl*0
          order by dbms_random.value()
          fetch first 1 row only
       )
ORDER BY schedule_id, datetime;

A: It's kinda hard to know what is going on from this code snippet, but if you're aiming to seed new tables with data in a random order from base tables that have data, you could consider generating random values, then row_number ordering by them to give yourself a pseudo primary key (integer, incrementing):
SELECT
  t.*,
  row_number() over(order by dbms_random.value(1,10)) as pseudopk
FROM
  table

For example you have base data tables (or cte) like:
BasePerson
Name, Age
--------
John, 20
Mary, 30

BaseAddress
City
----
New York
Paris
Berlin

INSERT INTO RealAddress(ID, City)
SELECT * FROM
(
  SELECT row_number() over(order by dbms_random.value(1,10)) pk, a.City
  FROM BaseAddress
)
WHERE pk < 3 --2 people need 2 address

INSERT INTO RealPerson(ID, Name, Age, AddressID)
SELECT pk, Name, Age, pk
FROM(
  SELECT
    row_number() over(order by dbms_random.value(1,10)) pk,
    a.Name,
    a.Age
  FROM BasePerson
)

It doesn't really matter that we reuse the number for both the person ID and their addressID, because the address data was randomised when it was inserted, so this is "people in a random order relative to their pk, linked to addresses in a random order relative to address's pk"


text:
Q: Very slow Insert and update on 20 core 250 Gb RAM dedicated MYSQL 5.5 server on Ubuntu Most of the data is in tbl_user_ads. Its a huge table.
Many concurrent processes (over 1000) try to select, insert or update this table.
The CPU utilization is just around 2%.
As I increase the number of processes which access this table the performance drops further.
I am getting lots of deadlocks.
Thanks for your time and help.
innodb status
my.cnf customizations:
innodb_buffer_pool_size=220G
innodb_buffer_pool_instances = 4
innodb_flush_log_at_trx_commit = 0
innodb_log_buffer_size=2048M
innodb_log_file_size = 1024M
innodb_flush_method = O_DIRECT
innodb_write_io_threads = 16
innodb_read_io_threads = 16
innodb_locks_unsafe_for_binlog = 1
innodb_lock_wait_timeout = 100

A: EDIT: after reading threw it, I noticed that your limiting it to 16 threads?
"innodb_read_io_threads = 16"
your server has 20 cores of cpu, and therefor you will only use a very small amount of CPU, try adding more threads and report back if it makes any difference,other then that i can't think of any thing else!
it may be due to server load, the fact that you have 20 cores may be useless, if the program can't multithread, whats your specs and general overall server load? other then that, I can't really think of any thing else that may be causing this.

A: You can set innodb_buffer_pool_instances by the liux command numactl --hardware. It gives no. of nodes. set this value to it. For more read here
You can set innodb_flush_log_at_trx_commit = 2 if: it is blog/stats/e-commerce (with ~100x shop in day), etc.
innodb_flush_log_at_trx_commit = 1 if: you have a lot of customers or you need to work with money transaction like bank. so this time you should split your dataflow between several servers to have speed & safety.
You can set it to 2, because it has ~75x faster write speed and it fails ONLY if hardware fails. But it have its own impact. Read this-

The innodb_flush_log_at_trx_commit is used with the purpose as ..
If the value of innodb_flush_log_at_trx_commit is 0, the log buffer is
  written out to the log file once per second and the flush to disk
  operation is performed on the log file, but nothing is done at a
  transaction commit.
When the value is 1 (the default), the log buffer is written out to
  the log file at each transaction commit and the flush to disk
  operation is performed on the log file.
When the value is 2, the log buffer is written out to the file at each
  commit, but the flush to disk operation is not performed on it.
  However, the flushing on the log file takes place once per second also
  when the value is 2. Note that the once-per-second flushing is not
  100% guaranteed to happen every second, due to process scheduling
  issues.
The default value of 1 is required for full ACID compliance. You can
  achieve better performance by setting the value different from 1, but
  then you can lose up to one second worth of transactions in a crash.
  With a value of 0, any mysqld process crash can erase the last second
  of transactions. With a value of 2, only an operating system crash or
  a power outage can erase the last second of transactions. InnoDB's
  crash recovery works regardless of the value.
In My opinion using innodb_flush_log_at_trx_commit to 2 should not be
  an issue.But to use 1 is the safest.

A: *

*Batch INSERTs, if practical.  That is use the multi-row insert syntax.

*(as mentioned) innodb_flush_log_at_trx_commit = 2 is better than 1, but it should not be better than the '0' you have.

*All well-tuned dataset won't use many CPUs.

*innodb_io_threads has to do with I/O; the number of cores is not very relevant.

*I doubt if there are 1000 simultaneous threads -- Check Threads_running or SHOW PROCESSLIST to see how much concurrency there really is.

*What's your QPS (Questions / Uptime)?

*Are they all hitting the same table?  Let's see SHOW CREATE TABLE and some sample statements.  Let's see SHOW ENGINE INNODB STATUS to see one of the deadlocks.

*How big is the table(s)?  Has the system been running long enough for the table(s) to be fully cached now?  (It takes a long time to fill 220GB.)  Are you using SSDs?

*Lots of writes?  Is the Query cache on?  The processlist may say "waiting for query cache lock".  Turn it off: both query_cache_type = OFF and query_cache_size = 0.


text:
Q: How to upload a zip file on fbapp I was trying to upload a game to
My fb developer but an error occur saying,the game must reference our support SDK and CDN please help
I have try to upload another file but the same error occur


text:
Q: Why is there multiple indentical entries in a legend when plotting with matplotlib? I try to plot a list a of values with respect to time and I have two examples: one where Im plotting angular velocities and the other where Im plotting linear accelerations. For both graphs the code for plotting is the same but in the linear accelerations graph there are multiple identical entries in the legend which I did not intend. Can you help me find the mistake?
kampai, ax = plt.subplots()
kampai.subplots_adjust(hspace=1, wspace=1)

ax.plot(time, xkampai, '-r', label='$\omega$$_x$, s$^{-1}$')
ax.set_xlim(1, 80)
ax.set_ylim(0, 0.5)

ax2 = ax.twinx()
ax3 = ax.twinx()

ax3.spines['right'].set_position(('axes', 1.2))

ax2.plot(time, ykampai, '-g', label='$\omega$$_y$, s$^{-1}$')
ax2.set_ylim(0, 0.5)

ax3.plot(time, zkampai, '-b', label='$\omega$$_z$, s$^{-1}$')
ax3.set_ylim(0, 0.5)

ax.set_xlabel('t, s')
ax.set_xlim(xmin=5, xmax=80)
ax.legend(loc='upper left', bbox_to_anchor=(0, 1))
ax2.legend(loc='upper left', bbox_to_anchor=(0, 0.9))
ax3.legend(loc='upper left', bbox_to_anchor=(0, 0.8))

pagreiciukai, bx = plt.subplots()
pagreiciukai.subplots_adjust(hspace=1, wspace=1)

bx.plot(time, pagreitisx, '-r', label='a$_x$, m $\cdot$ s$^{-2}$')

bx2 = bx.twinx()
bx3 = bx.twinx()

bx3.spines['right'].set_position(('axes', 1.2))

#bx2.plot(time, pagreitisy, '-g', label='a$_y$, m $\cdot$ s$^{-2}$')

#bx3.plot(time, pagreitisz, '-b', label='a$_z$, m $\cdot$ s$^{-2}$')

bx.set_xlabel('t, s')
bx.set_xlim(xmin=5, xmax=80)
bx.legend(loc='upper left', bbox_to_anchor=(0, 1))
#bx2.legend(loc='upper left', bbox_to_anchor=(0, 0.9))
#bx3.legend(loc='upper left', bbox_to_anchor=(0, 0.8))

plt.show()

A: I would recommend to provide a minimal working example of you issue (data that you use for plotting) to be able to reproduce it if you want your problem to be solved.
However, my guess would be that the issue is with the dimensions of the data array that you use for Figure 2. What happens is that you plot several identical lines each of which has the same line properties and label which results in a multiple identical entries in legend.
Minimal working example:
x = np.linspace(0, 1, 100)
y = x[:,None] + np.ones((100,10))

fig, ax = plt.subplots()
ax.plot(x, y, '-r', label='$y(x)$')
ax.legend(loc='upper left')
plt.show()

It produces the following figure
Multiple entries in legend
Fix:
y = x + np.ones((100))


text:
Q: how to by pass following error in Firefox extension "server does not support RFC 5746" I am developing a FireFox extension
when I do xhr to the Secure server , particularly POST a data
it gives a status 500, and following mesage:

onsip.highrisehq.com : server does not
  support RFC 5746, see CVE-2009-3555

How can I by pass by It? I assume that this is because of the Server misconfiguration, but I can't wait till someone from 37 signal will fix it. thanks for your help

A: Well - "see CVE-2009-3555". Basically it's a server side vulnerability which might allow to compromise a TLS/SSL session.
I'm not sure there's anything you can do on the client side to resolve this, until 37signals update their servers.

A: This is sort of a hack, but another option (instead of the XHR request) is a "hidden" (1px by 1px) IFRAME.  It's not pretty, but I've used it in situations where I had (different) problems with the XHR route (and there might even be a way to hide it entirely, but the 1px/1px works for me so I've never bothered to try anything else).
Just change the frame's src attribute to "make a request", then view it's document to read the "response".


text:
Q: How to find the pair of rows where the difference of columns value is maximum group by some column value I've a table similar to the following,

I want to find the pair of centers whose Performance difference is maximum for every session. So, I want a table like the following,

I'm struggling to form the correct query for h2 database.

A: You could self-join the table and use a correlated subquery for filtering:
select
    t1.session,
    t1.center center1,
    t2.center center2,
    t1.performance - t2.performance performance
from mytable t1
inner join mytable t2 on t1.session = t2.session
where t1.performance - t2.performance = (
    select max(t11.performance - t22.performance)
    from mytable t11
    inner join mytable t22 on t11.session = t22.session
    where t11.session = t1.session
)

Or you can use window functions:
select *
from (
    select
        t1.session,
        t1.center center1,
        t2.center center2,
        t1.performance - t2.performance performance,
        rank() over(partition by t1.session order by t1.performance - t2.performance desc)rn
    from mytable t1
    inner join mytable t2 on t1.session = t2.session
) t
where rn = 1

A: H2 can be a bit tricky.  I think this does what you want:
select t.session,
       max(case when performance = min_performance then center end) as center_1,
       max(case when performance = max_performance then center end) as center_2,
       (max_performance - min_performance) as performance_difference
from (select t.*
             min(performance) over (partition by session) as min_performance,
             max(performance) over (partition by session) as max_performance
      from t
     ) t
group by t.session, min_performance, max_performance;


text:
Q: CMake: Link a library to library I have a problem with cmake. I have, lets say, CMakeLists1 which has a subdirectory where CMakeLists2 is.
In CMakeLists2 my target is a static library. And I want to link it to external library.
I've made it just like that:
link_directories ("path_to_library")
add_library (project2 ${sources})
target_link_libraries (project2 "name_of_external_lib")

Then, I want to use a class from this project2 in my project1. I've made it that way:
add_executable (project1 ${sources})
target_link_libraries (project1 project2)

But that doesn't work at all. First of all, project2 didn't link to external library. Just for checking, I've added this library through vs10 project properties, and the sizes were different. And the second thing, somehow project1 sees that external library (it is in library dependencies of this project) and of course can't find it.
What is the problem?

A: I'm guessing the trouble will likely be that *name_of_external_lib* is not correct so it can't find it.
I would go with:
find_library(
    LIB_I_NEED name_of_external_lib
    HINTS "path_to_library"
)

if(${LIB_I_NEED} STREQUAL "LIB_I_NEED-NOTFOUND")
    message(FATAL_ERROR "Couldn't find the 'external_lib' library)
endif()

message(STATUS "Found 'external_lib' at: ${LIB_I_NEED}")

add_library (project2 ${sources})
target_link_libraries (project2 ${LIB_I_NEED})

If that doesn't help, have a quick read of the example in the cmake docs:
http://www.cmake.org/cmake/help/v2.8.8/cmake.html#command:target_link_libraries
One thing it mentions in there is:

While one repetition is usually sufficient, pathological object file
  and symbol arrangements can require more. One may handle such cases by
  manually repeating the component in the last target_link_libraries
  call

So I would say the other thing to try might be in project2:
set(PROJECT_2_LIBS project2 "name_of_external_lib" PARENT_SCOPE)

then in the exe:
target_link_libraries (project1 ${PROJECT_2_LIBS})

That will have the 'external_lib' linkage repeated in the two places and give you more chance of it working ;)

A: I think it's CMake's default behavior to not link project2 to the external library,
but to link both libraries to the executable.
From the book "Mastering CMake".

Since static libraries do not link to the libraries on which they depend, it is
important for CMake to keep track of the libraries so they can be specified on the
link line of the executable being created.

You could try to use an absolute path in your CMakeLists2:
add_library (project2 ${sources})
target_link_libraries (project2 "path to ext lib"/"name of ext lib")

or you could add
link_directories ("path_to_library")

to the CMakeLists file of project1.
If you really want to do something like in Visual Studio, you could probably use the command given in this answer to build a custom_command in CMake.
It probably would look something like this (I didn't test it).
set(EXT_LIB "path_to_library/name_of_external_lib")
set(BIG_LIB "path_to_big_lib/name_of_big_lib")
add_library (project2 ${sources})
get_property(PROJ2_LOC TARGET project2 PROPERTY LOCATION)

add_custom_command(OUTPUT ${BIG_LIB}
                   DEPENDS ${EXT_LIB} project2
                   COMMAND "lib.exe /OUT:${BIG_LIB} ${EXT_LIB} ${PROJ2_LOC} )

Then you could link your executable with ${BIG_LIB}.
Some things you have to consider:

*

*Maybe you have to use LOCATION_CONFIG (CMake docs, I found the get_property command in this answer )

*link.exe has to be in your path

*watch the scope of the BIG_LIB variable if you want to use it in an other CMakeLists.txt


text:
Q: ogr2ogr convert WFS data, when WFS has password and username I am trying to use ogr2ogr on a WFS with username and password.
I tried to follow this answer here
Import data from password protected WFS using OGR2OGR
Does anyone have some examples of doing this?
https://services.datafordeler.dk/GeoDanmarkVektor/GeoDanmark60_NOHIST_GML3/1.0.0/WFS?username=XXXX&password=XXXX

A: I tried this XML file "wfstest.xml"
<OGRWFSDataSource>
<URL>https://services.datafordeler.dk/GeoDanmarkVektor/GeoDanmark60_NOHIST_GML3/1.0.0/WFS?</URL>
<UserPwd>USERNAME:PASSWORD</UserPwd>
<HttpAuth>BASIC</HttpAuth>
<Version>1.0.0</Version>
</OGRWFSDataSource>

I tested the XML file with ogrinfo
ogrinfo wfstest.xml --debug on
...
WFS: https://services.datafordeler.dk/GeoDanmarkVektor/GeoDanmark60_NOHIST_GML3/1.0.0/WFS?SERVICE=WFS&REQUEST=GetCapabilities
HTTP: Fetch(https://services.datafordeler.dk/GeoDanmarkVektor/GeoDanmark60_NOHIST_GML3/1.0.0/WFS?SERVICE=WFS&REQUEST=GetCapabilities)
HTTP: libcurl/7.79.1-DEV OpenSSL/1.1.1l zlib/1.2.11
ERROR 1: Failed to connect to services.datafordeler.dk port 443 after 2222 ms: Connection refused
ERROR 1: Error returned by server : Failed to connect to services.datafordeler.dk port 443 after 2222 ms: Connection refused (7)

At least GDAL tries to connect the right address and makes a reasonable WFS request. Please try with your credentials.


text:
Q: Update parent from most recent child with Process Builder I have a master-detail relationship between two custom objects: Case__c [parent], Case_Followup__c [child]
The parent object has a text field representing the last known intention for the case [Last_Known_Intention__c]. Multiple follow-up communications related to the case will take place over time. The child object has a picklist field with a list of intentions: Leaving, Undecided, Staying, Not Applicable [Intention__c]
When a new Case_Followup__c record is created OR when any existing Case_Followup__c record is edited AND Intention__c is set to either Leaving, Undecided, or Staying, I need Case__c.Last_Known_Intention__c to update with the text value from Case_Followup__c.Intention__c for the Case_Followup__c record with the most recent CreatedDate.
I think this sort of thing is usually done with a trigger, but I saw in another post that this can be done using the Process Builder (link), which is what I would prefer. However, I have not been able to do it on my own or find documentation for it.
In short, is it truly possible to use the Process Builder to isolate the picklist value on the most recently created child record and push that to the parent record, and if so how exactly?


text:
Q: I want to solve the intersections of two circles using matrices. The equations of the circles are
$(x-h_1)^2+(y-y_1)^2=r_1^2$
and
$(x-h_2)^2+(y-y_2)^2=r_2^2$
If I can use matrices to solve for $(x,y)$, how? Also, I know there will be two answers. The one I am looking for is the one with the greater $y$ value, if that helps any.

CONTEXT: I am trying to bilaterate (altered version of triangulation) and that is basically how. I am also programming this and have already found a working method. However, this program does not calculate decimals accurately. I am hoping that solving this problem with matrices will allow me to calculate decimals with accuracy (hopefully to the thousandths or ten thousandths).


text:
Q: Is there a search utility which can binary split search a large sorted (sequential) text file? Yes, I know it sounds odd. Sequential and Binary-splits don't mix.. That is unless the sequence is the byte offset within the file itself...
I've scrambled together a binary split search in bash script, using dd. It has Search-and-Find times of 3-9 seconds for an 8 GB file.. so it works (but slower than I know it can be)...  I'd really prefer to not have to polish this wheel; It just took my fancy to do it as an exercise in bash (having a project is the best way to learn a language, etc).  I think this would be pretty straight forward in C/++, etc... I'm curious to see some other examples (particularly bash ones.

A: All the basic text processing utilities are meant to act as filters, and most are meant to process their input as a stream (i.e. read a little input, process it, write the corresponding output, repeat). dd is a little unusual, both by its syntax and by the options it offers. dd is the only shell interface to lseek, and as you've noticed it's clumsy. When you reach this point, it's time to switch to a more powerful scripting language such as Perl or Python.


text:
Q: predefined but empty multidimensional array in javascript I'm trying to create a multidimensional array to hold a generated grid.
The problem is I'm used to doing this in java, but doing it in javascript is deceptively harder. I know there are arrays of arrays rather than the standard java style and this is what is causing the confusion.
So in Java I'd expect to do this:
private static int[][] anyGrid(int rows, int cols) {
    int[][] grid = new int[rows][cols];
    return grid;
}

Say rows and cols were variables of 3. What would happen, is that would create something like this:
grid is:
[0,0][0,1][0,2]
[1,0][1,1][1,2]
[2,0][2,1][2,2]

But the actual entries would be empty.
So if I wanted to access the first entry I'd do:
grid[0][0], except this would be empty, unless I went grid[0][0] = 1; for example.
However doing this in javascript I'm at a loss.
var grid = new Array(new Array(cols));

Simply produces an array:
grid[0][0]-grid[0][5].
So one array with an internal array of length 6.
Which is.. not quite what I'm after.
How would I make it so that it is empty, but multidimensional beyond the first row?
Thank you

A: You can try this:
var grid = [], cols = 3, rows = 4
for (i = 0; i < cols; i++)
    grid.push(new Array(rows))

Or swap the cols with rows.


text:
Q: Three.js export SkinnedMesh with position I'm trying to export a model from a Three.js scene using https://github.com/mrdoob/three.js/blob/master/examples/jsm/exporters/OBJExporter.js
Some mesh are base meshes and some other are SkinnedMesh, so I've edited line 250 from
if ( child instanceof Mesh ) {

to
if ( child instanceof Mesh || child instanceof SkinnedMesh ) {

and I can see all the meshes in the exported file, but the SkinnedMeshes are in the origin with wrong position and orientation.
How can I edit the exporter to also get the SkinnedMeshes right, and why is this happening?
EDIT:
I tried with the STL exporter proposed in the answers, but it still fails to export the pose because the three properties that it checks:
if(typeof object.obj.geometry.attributes.skinIndex !== 'undefined' && typeof object.obj.geometry.attributes.skinWeight !== 'undefined' && typeof object.obj.skeleton !== 'undefined')

are all undefined except for "object.obj.skeleton".
The properties that I can see in the SkinnedMesh objects are "instanceIndex", "normal", "position" and "uv"
EDIT 2:
Sorry for the confusion, but I misread the output log. There are some meshes with quite-said properties, meaning that the actual names are "skinWeight0" and "skinIndex0".
I tried to change the name to that in the code and I can succesfully print those arrays, but the exported model is a total mess:

A: That's happening since the transformation of skinned meshes does not only depend on Object3D.position, Object3D.rotation and Object3D.scale and its position in the object hierarchy. It also depends on its skeleton.
The change you have made so far is not sufficient to honor skeleton information. If you want to ensure that the export actually reflects the transformation and shape of the skinned mesh, you need similar code like from this PR:
https://github.com/mrdoob/three.js/pull/16942
So the idea is to actually take the bone transformation into account when computing the final position of vertices (which are going to be defined in the OBJ file).


text:
Q: React Native (Expo managed) - Asset.LocalUri returns null in Android production I would like to allow users to share an image (local asset, known at build time) using expo-sharing library. For this, I follow this approach:
/** Typing for local assets in components/icons/index.ts file */
export const icons = {
   badges: {
      badge: require('./badge.png')
   }
}

/**
 * Load asset. In original code, I have multiple badges,
 * so I use 'useAssets' from 'expo-asset' library to load them all at once
*/
const [assets, assetError] = useAssets(icons.badges.badge)

/** Share badge using social platforms */
const shareBadge = async () => {
   const badge = assets[0];
   const loadedBadge = await badge.downloadAsync() // I only added this line to try to solve the issue as written in documentation, but it didn't help
   await Sharing.shareAsync( loadedBadge.localUri, {
      UTI: 'public.png',
      mimeType: 'image/png',
      dialogTitle: 'Share Badge',
   }
}

Provided code is tested and works on following environments: Expo Go iOS, Expo Go Android, Web (dev env), Production iOS. Production Android is the only environment that is not working (which makes it extremely hard to fix this, as I need to build the app and upload it to the phone to replicate).
Using Sentry, I was able to catch exception thrown in shareBadge method:
Error: Only local file URLs are supported (expected scheme to be 'file', got 'null'.

From caught exception, I assume that the problem is that badge.localUri returns null instead of file://path/to/file.png. This is strange for two reasons:

*

*I am using these files in other part of code as props in <Image src={imageAsset} /> without any problem

*It works in iOS builds (even in production) and Expo Go Android
So I assume the code can't be completely wrong.

I am on Expo 46, using EAS build

A: In the expo docs they verify the asset exist before using it:
const [assets, error] = useAssets([
  require('path/to/asset.jpg'),
  require('path/to/other.png')
]);
return assets ? <Image source={assets[0]} /> : null;

I think your issue is that you aren't checking to verify that the assets are loaded. This should be causing issues on all platforms; but its likely that the all devices you are testing on except Android are loading the assets faster than you can call the shareBadge. You could do something like this:
const shareBadge = async () => {
   if(!assets || assetError){
     return
   }
   const badge = assets[0];

   const loadedBadge = await badge.downloadAsync() // I only added this line to try to solve the issue as written in documentation, but it didn't help
   await Sharing.shareAsync( loadedBadge.localUri, {
      UTI: 'public.png',
      mimeType: 'image/png',
      dialogTitle: 'Share Badge',
   }
}

but it would be awkward to have a ShareBadge button that could possibly do nothing, so I'd suggest having a state variable tied to whether the assets are loaded:
const [assets, assetError] = useAssets(icons.badges.badge);
const [assetsIsLoaded, setAssetsIsLoaded = useState(false);

// listen for assets changes, or assetError
useEffect(()=>{
  if(assetError){
    // log error or something
  }
  else
    setAssetsIsLoaded(assets && assets.length > 0)
},[assets,assetError])

With a state variable tied to the assets status you have more UI options, such as disabling the Share Badge button until assets is loaded, or maybe having a loading animation.


text:
Q: excel VBA convert to CSV in the SaveAs method I am trying to improve below VBA I found in this thread. Would it be possible to have this code in the form of Application.Dialogs(xlDialogSaveAs).Show(Arg2:=xlCSV) method, so I can choose where to save the CSV file?
Option Explicit

Sub CSV_Makerr()
   Dim r As Range
   Dim sOut As String, k As Long, M As Long
   Dim N As Long, nFirstRow As Long, nLastRow As Long
   Dim MyFilePath As String, MyFileName As String
   Dim fs, a, mm As Long
   Dim separator As String

   ActiveSheet.UsedRange
   Set r = ActiveSheet.UsedRange
   nLastRow = r.Rows.Count + r.Row - 1
   nFirstRow = r.Row
   separator = ","

   MyFilePath = "C:\TestFolder\"
   MyFileName = "whatever"
   Set fs = CreateObject("Scripting.FileSystemObject")
   Set a = fs.CreateTextFile(MyFilePath & MyFileName & ".csv", True)

   For N = nFirstRow To nLastRow
       k = Application.WorksheetFunction.CountA(Cells(N, 1).EntireRow)
       sOut = ""
       If k = 0 Then

       Else
           M = Cells(N, Columns.Count).End(xlToLeft).Column
           For mm = 1 To M
               sOut = sOut & Cells(N, mm).Text & separator
           Next mm
           sOut = Left(sOut, Len(sOut) - 1)
           a.writeline (sOut)
       End If
   Next

   a.Close
End Sub

The idea is to remove the commas from the CSV or blank column that is persistently exist even after I delete it several times. Above code works, but without the liberty to choose the location path for different end users or PC. Kindly let me know if it's possible.

A: Something like this?
Sub CSV_Makerr()
   Dim r As Range
   Dim sOut As String, k As Long, M As Long
   Dim N As Long, nFirstRow As Long, nLastRow As Long
   Dim MyFilePath As String, MyFileName As String
   Dim fs, a, mm As Long
   Dim separator As String

   ActiveSheet.UsedRange
   Set r = ActiveSheet.UsedRange
   nLastRow = r.Rows.Count + r.Row - 1
   nFirstRow = r.Row
   separator = ","

   MyFilePath = Application.GetSaveAsFilename(fileFilter:="CSV Files (*.csv), *.csv")
   If MyFilePath <> "" Then
       Set fs = CreateObject("Scripting.FileSystemObject")
       Set a = fs.CreateTextFile(MyFilePath, True)

       For N = nFirstRow To nLastRow
           k = Application.WorksheetFunction.CountA(Cells(N, 1).EntireRow)
           sOut = ""
           If k = 0 Then

           Else
               M = Cells(N, Columns.Count).End(xlToLeft).Column
               For mm = 1 To M
                   sOut = sOut & Cells(N, mm).Text & separator
               Next mm
               sOut = Left(sOut, Len(sOut) - 1)
               a.writeline (sOut)
           End If
       Next
       a.Close
   End If
End Sub


text:
Q: Using the "in" operator in pandas.DataFrame without getting "ambiguous error I have a pd.DataFrame
import pandas as pd
country = ['US', 'US', 'US', 'UK', 'UK', 'UK']
year = ['1990', '1991', '2020', '1990', '1991', '2020']
people = [20, 34, 456, 5, 7, 300]

df = pd.DataFrame(zip(country, year, people), columns = ['country', 'year', 'people'])

country year    people
0   US  1990    20
1   US  1991    34
2   US  2020    456
3   UK  1990    5
4   UK  1991    7
5   UK  2020    300

I wish to locate year '2020' and '1990'.
I understand that this can be achieved with:
df.loc[(df.year == '2020') | (df.year == '1990')]

or
df.query('year == [\'2020\', \'1990\']')

to get the output:
country year    people
0   US  1990    20
2   US  2020    456
3   UK  1990    5
5   UK  2020    300

However, I'd like to perform this 'query' with the in operator.
Trying:
df.loc[df['year'] in ['2020', '1990']]

which raises the error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I expect to use the in operator in my pandas.DataFrame subsetting, as it requires the least amount of typing.
What is the best way to mitigate this error raised by the in operator?

A: df[df['year'].isin(['1990','2020'])]

or
df.loc[df['year'].isin(['1990','2020'])]

A: Use the .isin() function.
df.loc[df['year'].isin(['1990','2020'])]
You input a list of options that you want 'year' to be, and pandas will return a series of boolean values. That series will in turn be interpreted by the .loc() to return only the rows where df['year'] == the desired values.


text:
Q: How to get video src attribute I need to get the src attribute of a video tag, but something is wrong:
<video id="vdisk" controls poster="placeh/02.jpg">
    <source src="placeh/01.mp4" type="video/mp4">
</video>

JavaScript
var a = $("#vdisk").attr("src");
console.log(a); // undefined

A: Use this.
document.getElementById("vdisk").getElementsByTagName("source")[SourceIndex].src

Where SourceIndex is the index of the source tag in case of multple source elements.

A: As source is descendant of #vdisk, try this :-
var a = $("#vdisk source").attr("src");
console.log(a);

Reference

A: The currentSrc property will get the src of whichever <source> is used for the video.
In your case, there's only one <source>, so "placeh/01.mp4" is the only possible value of the video's currentSrc (unless there's some other issue).
Note that this isn't a jQuery property. You have to convert the jQuery object to a DOM element in order to use it.
var a = $("#vdisk").get(0).currentSrc;
console.log(a); // "placeh/01.mp4"

A:

var a = $("#vdisk").find('source').attr("src");
console.log(a); // undefined
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video id="vdisk" controls poster="placeh/02.jpg">
  <source src="placeh/01.mp4" type="video/mp4">
</video>
js

Use .find()

Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

A: That's not an attribute of #vdisk.  You have to access the inner element like this: $("#vdisk").children("source").attr("src")

A: you have to get the element "source" ,which have attribute "src"

A: How about $.each($("#id").get,function(){})

$.each($('#vdisk').get(),function(index, element)
{
  console.log(element.paused)
  //if(!element.paused) console.log(element.attr("src")) or something...
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<video id="vdisk" controls poster="http://www.freedigitalphotos.net/images/img/homepage/87357.jpg">
  <source src="http://texasmotherfriendly.org/video/Childrens_Courtyard_640x360.mp4" type="video/mp4">
</video>

A: Here is the solution ..
$("#vdisk source").attr("src")


text:
Q: antivirus popup while using c++ I am new to C++.I am following freeCodeCamp.org tutorial on C++.
The program looks like this-
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
  int luckyNums[] = {4,8,15,16,23,42};
  cout << luckyNums[2];

  return 0;
}

since I had VS code already installed I did not install code blocks.
Every time I run the above program I get an error "Access is denied". Also at the same time McAfee pops up saying "we just stopped a virus". I couldn't find a solution to this on Google anywhere.
When I was trying to do something with the code, in line 6 I did
cout << luckyNums[2] << endl;

and it worked and returned 15 but now the problem was I didn't understand why it worked because Mike got the result without doing this in code blocks.
Mike is the person giving the tutorial on freeCodeCamp.org


text:
Q: Question about Criteria.createCriteria in Hibernate API So I'm still trying to get myself acquainted with the Hibernate Criteria API, and I have this piece of Java code which I would like to seek clarification over.
Criteria c = super.getSession().createCriteria(PpNnCtDetail.class);
c.add(Restrictions.between("commencementDate", fromDate, toDate);

This part I understand what's happening - putting it in terms of SQL it would be something like - correct me if I'm wrong,
SELECT * FROM PpNnCtDetail WHERE commencementDate >= fromDate AND commencementDate <= toDate;

The problem comes with the code following the two lines above.
c = c.createCriteria("nnContractTbl");
c.createCriteria("progCategory").add(Restrictions.in("progCategoryId", allProgCat));
c.createCriteria("acadOrgTbl");
c.createCriteria("serviceType");
c.createCriteria("campusTbl");
return c.list();

What is the first line trying to accomplish? Is that assignment back to c redundant?
In fact, what are the lines c.createCriteria trying to achieve? What would an equivalent SQL query look like? More importantly, what would c.list() return?

A: The assignament on c = c.createCriteria("nnContractTbl"); is redundant, createCriteria and almost all Criteria methods modify the instance they're invoked on, and return the instance itself for method chanining. So you can chain calls like this:
return super.getSession().createCriteria(PpNnCtDetail.class)
    .add(Restrictions.between("commencementDate", fromDate, toDate)
    .createCriteria("nnContractTbl")
    .createCriteria("progCategory").add(Restrictions.in("progCategoryId", allProgCat))
    .createCriteria("acadOrgTbl")
    .createCriteria("serviceType")
    .createCriteria("campusTbl")
    .list();

And about the result of that sequence, Criteria.createCriteria(association) will result in an inner join between the data already in the criteria and the table designed in the association modelled by the attribute association. It will also "root" (as they state in the Javadocs) the Criteria at the association entity, so that in further calls to createCriteria(association), association refers to an association attribute declared on the last "rooted" entity.
It's a shorthand for Criteria.createCriteria(association, joinType) with joinType CriteriaSpecification.INNER_JOIN.

A: Those createCriteria as specified above are basically equivalent to an INNER JOIN to the entity passed.
The best way to find answers to your questions (and also learn hibernate in the meantime) is to turn SQL logging on in your hibernate configuration file, and inspect the generated SQL.


text:
Q: Python Class creation to attach mathematical model and play with variables I am trying to create a software with interface, but first I need to create the backend. As pyomo or other library can construct models,
I want to do it in my class. So the main idea is to first 1): create the object; 2):declare my variables and parameters within the object;
3): add ordinary differential equations to my object; 4) add optional equations to my object.
As pyomo, for example, to add an equation you can use a method for example, called Constraint, where it works as follows, e.g.: model.C1 = Constraint(expr = (a*x**2 == 3)).
Also in pyomo for you to create a parameter and put into the model you use for example: model.P = Param(initialize=value). A variable is created as model.variable = Var(bounds=(0, None)).
I just need to understand these basic things, I mean, how to create methods in a class to do the same. Just these basic. To clarify what I want to do, here is a
reverse engineering, my main script is:
model = my_class()

#DECLARING PARAMETERS

model.parameter(P1)
model.parameter(P2)
model.parameter(P3)
model.parameter(P4)
model.parameter(P5)

#DECLARING VARIABLES

model.variable(X[0])  # declaring X and W as variables, obs.: the argument is an object to the class and other methods inside this class?

model.variable(X[1])

model.variable(W[0])

model.variable(W[1])

#PROCESS MODEL CONSTRUCTION:

#use model.ODE to add an ODE to the model

model.ODE( expr= (  Y[0] ==  P1*X[0] - P2*X[1] + P3*W[1] )    ) # Y[0] is related as being the derivative

model.ODE( expr= ( Y[1] ==  P4*W[1] - P5*X[0] )    ) # Y[1] is related as being the derivative

model.solve() # << ignore this line, since I still will create the method

THE MOST important thing is that "expr" must be an argument for other future method creations inside the class! So the python must recognize it as being an argument
output as well, so I can insert them into other methods. Once the user declare these expressions I can play with other methods...


text:
Q: Stored generated column without limitation Let's say I have a table containing four columns in Postgres --  ID (int), Year (int), Product (str), and Revenue (int). I would like to store a calculated column to the table that is based on retrieving the previous year's data:

It seems the stored generated columns have a lot of limitations, notably:

The generation expression can only use immutable functions and cannot use subqueries or reference anything other than the current row in any way.

What would be the preferred way to do the above? It seems like the only way to do this without creating a materialized view (which would needlessly copy all the data, which I don't want), is to do an alter table and add a new column. For example:
create table sales (id int, year int, product varchar(40), revenue int);
insert into sales VALUES (1,1996, 'car', 12);
insert into sales VALUES (2,1996, 'phone', 7);
insert into sales VALUES (3,1997, 'car', 13);
insert into sales VALUES (4,1997, 'phone', 11);
------------------------------------------------------------
alter table sales add last_revenue INT
    DEFAULT LAG(Revenue) OVER (PARTITION by Product ORDER BY year);
    -- window function will be rejected in alter table,
    -- but using this to show what I want to achieve

A: use view. If you want materialize then use materialzied view
CREATE VIEW include_previous_year AS (
    SELECT
        *,
        LAG(Revenue) OVER (PARTITION BY Product ORDER BY year)
    FROM sales)

A: You could update the existing data with the following UPDATE:
START TRANSACTION;
ALTER TABLE sales ADD revenue_last INT DEFAULT NULL;
UPDATE sales JOIN (
    SELECT
      id,
      LAG(revenue) OVER (PARTITION BY product ORDER BY year) revenue_last
    FROM sales) sales_calc USING (id)
SET sales.revenue_last=sales_calc.revenue_last;
COMMIT;

If you want to also update and data coming in, you can add in a trigger.


text:
Q: Socket IO keeps (re?)connecting, even after establishing a websocket I'm trying to implement websockets. It manages to make a connection and prints Backend, connected! and Frontend, connected!, but when I type text into the input and press send, it just prints Frontend, connected! a bunch more times and nothing happens. What am I doing wrong here?
Here's what I have:
// server.js
const express = require("express");

const app = express();

app.use("/api/messages", require("./routes/api/messages"));

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Listening on port ${PORT}`));

// routes/api/messages.js
const express = require("express");

const router = express.Router();

const server = require("http").createServer();

const io = require("socket.io")(server, {
  path: "/socket",
  serveClient: false,
  pingInterval: 10000,
  pingTimeout: 5000,
  cookie: false
});

io.on("connection", () => {
  console.log("Backend, connected!");
});

io.on("msg", function(msg) {
  console.log("entered!"); // <--- never prints!
  console.log("message: " + msg);
});

server.listen(5001);

router.post(...)

router.get(...)

module.exports = router;

And on my React Native front end, in one of my screens in React Navigation:
const Conversation = ({
  navigation,
  auth: { user },
  sendMessage
}) => {
  const [replyText, setReplyText] = useState("");

  const socket = io("http://192.168.112.110:5001", {
    path: "/socket",
    transports: ["websocket"],
    jsonp: false
  });

  useEffect(() => {
    socket.connect();

    socket.on("connect", () => {
      console.log("Frontend, connected!");
    });

    socket.on("works?", () => {
      console.log("omg");
    });

    socket.on("connect_error", err => {
      console.log("error", err);
    });
  }, []);

  const handleSendReply = () => {
    if (validateLength(replyText) === 0) {
      setReplyTooShort(true);

      return;
    }

    sendMessage(
      replyText,
      user.username
    );

    console.log("replyText", replyText); // prints

    socket.emit("msg", replyText);

    setReplyText("");
  };

return <View>
        <Input
        label="reply"
        value={replyText}
        onChangeText={e => setReplyText(e)}
        />
        <View style={{ alignItems: "flex-end" }}>
        <Icon
            name="md-send"
            type="ionicon"
            iconStyle={{ paddingLeft: 20, paddingRight: 20, paddingTop: 10 }}
            onPress={() => handleSendReply()}
        />
        </View>
    </View>
}

"socket.io": "^2.3.0" // server
"socket.io-client": "^2.3.0" // client

Edit:
(The yellow warning should be ignored as per this comment)

A: Socket server listens on connection event.

When connection is successful a new socket object is created with a unique id.

This Socket object handles sending and receiving of events/data.

io.on("connection", (socket) => {
  // console.log("Backend, connected!"); // user or client is connected.
  console.log("User connected with a unique socketId ", socket.id);
    socket.on("msg", function (msg) {
        console.log("entered!"); // <--- It will print now !
        console.log("message: " + msg);
    });

});

Socket-io docs


text:
Q: Git Flow should the release to production be done from release branch or Main/trunk branch We use Git Flow when deploying to production environment do we deploy from release branch or main/trunk branch.
The reason for asking is if we merge to trunk and deploy to production how do we ensure that the merge is done properly. It looks like merges code is deployed to production without testing is this correct? How do we ensure what has been merged to Main branch is correct?

A: As illustrated in Release Branch, if there have not been any modification on the master branch (and it should have been no new commit), the merge (from release to master) should be a trivial one:

But you should still run your tests from that 1.0 release commit before the actual deployment.


text:
Q: Maxima: Is there any way to make functions defined within the main function be local, in a similar way to local variables? I wonder if there is any way to make functions defined within the main function be local, in a similar way to local variables. For example, in this function that calculates the gradient of a scalar function,
grad(var,f) := block([aux],
    aux : [gradient, DfDx[i]],
    gradient : [],
    DfDx[i] := diff(f(x_1,x_2,x_3),var[i],1),
    for i in [1,2,3] do (
        gradient : append(gradient, [DfDx[i]])
    ),
    return(gradient)
)$

The variable gradient that has been defined inside the main function grad(var,f) has no effect outside the main function, as it is inside the aux list. However, I have observed that the function DfDx, despite being inside the aux list, does have an effect outside the main function.
Is there any way to make the sub-functions defined inside the main function to be local only, in a similar way to what can be made with local variables? (I know that one can kill them once they have been used, but perhaps there is a more elegant way)

A: To address the problem you are needing to solve here, another way to compute the gradient is to say
grad(var, e) := makelist(diff(e, var1), var1, var);

and then you can say for example
grad([x, y, z], sin(x)*y/z);

to get
             cos(x) y  sin(x)    sin(x) y
            [--------, ------, - --------]
                z        z           2
                                    z

(There isn't a built-in gradient function; this is an oversight.)
About local functions, bear in mind that all function definitions are global. However you can approximate a local function definition via local, which saves and restores all properties of a symbol. Since the function definition is a property, local has the effect of temporarily wiping out an existing function definition and later restoring it. In between you can create a temporary function definition. E.g.
foo(x) := 2*x;

bar(y) := block(local(foo), foo(x) := x - 1, foo(y));

bar(100); /* output is 99 */

foo(100); /* output is 200 */

However, I don't this you need to use local -- just makelist plus diff is enough to compute the gradient.
There is more to say about Maxima's scope rules, named and unnamed functions, etc. I'll try to come back to this question tomorrow.

A: To compute the gradient, my advice is to call makelist and diff as shown in my first answer. Let me take this opportunity to address some related topics.
I'll paste the definition of grad shown in the problem statement and use that to make some comments.
grad(var,f) := block([aux],
    aux : [gradient, DfDx[i]],
    gradient : [],
    DfDx[i] := diff(f(x_1,x_2,x_3),var[i],1),
    for i in [1,2,3] do (
        gradient : append(gradient, [DfDx[i]])
    ),
    return(gradient)
)$

(1) Maxima works mostly with expressions as opposed to functions. That's not causing a problem here, I just want to make it clear. E.g. in general one has to say diff(f(x), x) when f is a function, instead of diff(f, x), likewise integrate(f(x), ...) instead of integrate(f, ...).
(2) When gradient and Dfdx are to be the local variables, you have to name them in the list of variables for block. E.g. block([gradient, Dfdx], ...) -- Maxima won't understand block([aux], aux: ...).
(3) Note that a function defined with square brackets instead of parentheses, e.g. f[x] := ... instead of f(x) := ..., is a so-called array function in Maxima. An array function is a memoizing function, i.e. if f[x] is called two or more times, the return value is only computed once, and then returned every time thereafter. Sometimes that's a useful optimization when the domain of the function comprises a finite set.
(4) Bear in mind that x_1, x_2, x_3, are distinct symbols, not related to each other, and not related to x[1], x[2], x[3], even if they are displayed the same. My advice is to work with subscripted symbols x[i] when i is a variable.
(5) About building up return values, try to arrange to compute the whole thing at one go, instead of growing the result incrementally. In this case, makelist is preferable to for plus append.
(6) The return function in Maxima acts differently than in other programming languages; it's a little hard to explain. A function returns the value of the last expression which was evaluated, so if gradient is that last expression, you can just write grad(var, f) := block(..., gradient).
Hope this helps, I know it's obscure and complex. The Maxima programming language was not designed before being implemented, and some of the decisions are clearly questionable at the long interval of more than 50 years (!) later. That's okay, they were figuring it out as they went along. There was not a body of established results which could provide a point of reference; the original authors were contributing to what's considered common knowledge today.


text:
Q: Is it possible to cache a specific value on mysql? Is it possible to temporarily cache a specific value in a query to mysql with over 1000 results and different values, although some repeated?...
Here I show you an idea:
SELECT
    members.name,
    members.lastname,
    use_cache_if_it_was_consulted(SELECT countries.name FROM countries WHERE countries.id = members.country LIMIT 1) AS 'country'
FROM members
WHERE
    members.enable = 1
    AND members.gender = "M"
    AND members.country IN( 1, 2, 3 , 4 , 5 , 9 , 15 , 2342 , 234 )

Many "members" are from the U.S., other than Canada, and many others, from other countries.
The idea is that MySQL does not overload with subqueries, since I have a table ("members") with more than three million rows.

A: My answer is not about caching a value in MySQL but to give other ideas and it is too big to put into a comment :
If you are using a subquery , you can use Join instead .
SELECT
    members.name,
    members.lastname,
    countries.name
FROM
    members
    LEFT OUTER JOIN countries ON countries.id = members.country
WHERE
        members.enable = 1
    AND members.gender = 'M'
    AND members.country IN( 1, 2, 3 , 4 , 5 , 9 , 15 , 2342 , 234 )

Considering country names are not something that usually change , you could also use a PHP array to store the Country Names with Country Id as key . Ex. $countryNames .
In which case , in the SQL you would retrieve country id :
SELECT
    members.name,
    members.lastname,
    members.country

When using it , you would use it as $countryNames[id] .
You can still have the countries table in the database . It is because there could be times that joining country table might be more appropriate . If you go this path , you would need to consider one as master and sync the other when there are any additions/modifications .
Hope this is useful .


text:
Q: JPA, @ManyToMany, Pageable and performance concerns I have two entities linked by a @ManyToMany association. Let's say Text and Country. So in my Text entity, I have:
@ManyToMany(fetch = FetchType.LAZY)
private Set<Country> countries = new HashSet<>();

I want to perform a paginated query that returns texts, so in a JPA repository, I write:
Page<Text> findAll(Pageable pageable);

This works. The problem is that as countries are lazy loaded, hibernate executes an extra select query for each country to load.
So I can use @EntityGraph to fetch countries:
@EntityGraph("countries")
Page<Text> findAll(Pageable pageable);

It works, I have only one query, but it is wayyyyyyyyyy much longer (about 12x). I seems that it fetches the countries for all the texts (I have a lot of texts) before applying the pagination. This is confirmed by the Spring data team: https://github.com/spring-projects/spring-data-jpa/issues/1976
So is there a way to perform an optimized paginated query, without N+1 select and without loading the entire table ?
Thank you very much


text:
Q: Switching between arrays with ng-repeat Right now I have 3 arrays I want to toggle between with my ng-repeat:
$scope.fooDataObj = {
array1:[{name:'john', id:'1'},{name:'jerry', id:'2'}],
array2[{name:'bill', id:'1'},{name:'tom', id:'2'}],
array3:[]
}

and my ng-repeat:

So all I want to do is dynamically switch between my arrays of data within my object in the most performant way.
So basically when some clicks <button></button>it will change from using array1 in the ng-repeat to array2.
I've accomplished this by setting ng-repeat="data in fooData" then on click triggering $scope.fooData = fooDataObj.array1. But this is not very performant. Especially when switching between the populated arrays to the empty array.

A: You could just switch the key and use bracket notation in the ng-repeat source.

and on button click set vm.source to text array1, array2, array3. If you want to make it dynamic derived keyname instead of hardcoding then just get the keys from the object as Object.keys(fooDataObj)


text:
Q: Populate String Array With For Loop and String Combintion in C# I have a string array defined as String[] sEmails; that I am trying to populate with 10 different (but similar) strings (email addresses in this case).
Here is the code I'm trying to use to populate the array.
public void populateEmailArray()
    {
        for (int x = 0; x < 10; x++)
        {
            switch(x)
            {
                case 1:
                    sEmails[x] = sRepStuff + "1" + sGmail;
                break;
                case 2:
                    sEmails[x] = sRepStuff + "2" + sGmail;
                break;
                case 3:
                    sEmails[x] = sRepStuff + "3" + sGmail;
                break;
                case 4:
                    sEmails[x] = sRepStuff + "4" + sGmail;
                break;
                case 5:
                    sEmails[x] = sRepStuff + "5" + sGmail;
                break;
                case 6:
                    sEmails[x] = sRepStuff + "6" + sGmail;
                break;
                case 7:
                    sEmails[x] = sRepStuff + "7" + sGmail;
                break;
                case 8:
                    sEmails[x] = sRepStuff + "8" + sGmail;
                break;
                case 9:
                    sEmails[x] = sRepStuff + "9" + sGmail;
                break;
            }
        }
    }

The end result I want to be something like this
sEmails['repstuff1@gmail.com','repstuff2@gmail.com','repstuff3@gmail.com'] and so and and so forth to repstuff9@gmail.com
But on the first try of trying to set an sEmails[x] it gives me an error of "NullReferenceException was unhandled.  Object reference not set to an instance of an object."
I have no idea what I'm doing wrong here because the code seems sound in my mind.  Any help on this would be greatly appreciated.

A: Try instantiating your array with
String[] sEmails = new String[10];

You can also make that loop far more succinct:
public void populateEmailArray()
{
    for (int x = 0; x < 10; x++)
    {

        sEmails[x] = sRepStuff + x + sGmail;
    }
}

A: Arrays start indexing at 0, not 1, and so you aren't giving sEmails[0] a value. Shift all your values down by 1. Then when you access sEmails[0], it will still be null. You should also make sure that your sEmails array has been instantiated:
sEmails = new String[10];

This should work:
public void populateEmailArray()
{
       sEmails = new String[10];
        for (int x = 0; x < 10; x++)
        {
            switch(x)
            {
                case 0:
                    sEmails[x] = sRepStuff + "1" + sGmail;
                break;
                case 1:
                    sEmails[x] = sRepStuff + "2" + sGmail;
                break;
                case 2:
                    sEmails[x] = sRepStuff + "3" + sGmail;
                break;
                case 3:
                    sEmails[x] = sRepStuff + "4" + sGmail;
                break;
                case 4:
                    sEmails[x] = sRepStuff + "5" + sGmail;
                break;
                case 5:
                    sEmails[x] = sRepStuff + "6" + sGmail;
                break;
                case 6:
                    sEmails[x] = sRepStuff + "7" + sGmail;
                break;
                case 7:
                    sEmails[x] = sRepStuff + "8" + sGmail;
                break;
                case 8:
                    sEmails[x] = sRepStuff + "9" + sGmail;
                break;
                case 9:
                    sEmails[x] = sRepStuff + "10" + sGmail;
                break;
            }
        }
    }

A better, more concise version would be:
for(int i = 0; i < 10 ; i++)
{
   sEmails[i]="repstuff"+(i+1)+"@gmail.com";
}

A: Hope you are doing well.
I will help you clean up your code today!
rather than doing a switch-case you can do this
for(int i = 0; i < 10 ; i++)
{
   emails[i]="repstuff"+i+"@gmail.com";
}

That helps you clear out a your coding style. In addition, did you check if you have instantiated / created both your sEmails, repStuff and Gmail?

A: To the solution that you already accepted I would add some "spice" to make it even more dynamic. I would not set 10 hard-coded but I would use array's length instead.
public void populateEmailArray()
{
    int length = sEmails.Length;

    for (int x = 0; x < length; x++)
    {

        sEmails[x] = sRepStuff + x + sGmail;
    }
}

I don't trust my memory when I have to return to a program some time afterwards and have to remember and check all the points that I have to change when for example your emails array must grow up to 20 elements.


text:
Q: Is there a way to filter an item in a array inside another array Basicaly I have an object that has an array in it and I have a superior array of this object.
The object is the following.
category: {
   name,
   items: [{
      id,
      name,
      price,
      image,
   }],
}

This array can look like:
[{
   name: "Category 1",
   items: [{
      id: 1,
      name: "Item 1 of category 1",
      price: 12.34,
      image: "/path/to/image",
   },
   {
      id: 2,
      name: "Item 2 of category 1",
      price: 56.78,
      image: "/path/to/image2",
   }]
},
{
   name: "Category 2",
   items: [{
      id: 3,
      name: "Item 1 of category 2",
      price: 87.65,
      image: "/path/to/image3",
   },
   {
      id: 4,
      name: "Item 2 of category 1",
      price: 43.21,
      image: "/path/to/image4",
   }]
}]

My question is, it's possible to search for the id since I have an array with all of this data.
Currently I am solving the problem with the following code:
var price = 0;
const menu = [];
state.user.menu.map((item, k) => {
  item.category.items.forEach((itm) => menu.push(itm));

  return null;
});

state.user.items.forEach((item) => {
  price += menu.filter((itm) => itm.id === item.id)[0].price * item.quantity;
});

This basicaly copies every item in the array inside of the object and ignores the category name so I only have a big array.
For what I need now, I need to correlate each item with the category name, so, I can't do as it is now.
Basically, I have a list of Ids and I need to display them with the corresponding category that is in this array.
(Items to search)
[{
   timestamp: "123456",
   userid: "123456",
   ...
   id: 1,
   price: 12.34,
},
{
   timestamp: "123456",
   userid: "123456",
   ...
   id: 3,
   price: 87.65,
},
{
   timestamp: "123456",
   userid: "123456",
   ...
   id: 4,
   price: 43.21,
}]

(Expected Result)
[{
   name: "Category 1",
   items: [{
      id: 1,
      name: "Item 1 of category 1",
      price: 12.34,
      image: "/path/to/image",
   }]
},
{
   name: "Category 2",
   items: [{
      id: 3,
      name: "Item 1 of category 2",
      price: 87.65,
      image: "/path/to/image3",
   },
   {
      id: 4,
      name: "Item 2 of category 1",
      price: 43.21,
      image: "/path/to/image4",
   }]
}]

Any sugestions is welcome, thanks.

A:

const data = [
  { name: "Category 1", items: [{ id: 1, name: "Item 1 of category 1", price: 12.34, image: "/path/to/image" }, { id: 2, name: "Item 2 of category 1", price: 56.78, image: "/path/to/image2" }] },
  { name: "Category 2", items: [{ id: 3,  name: "Item 1 of category 2",  price: 87.65, image: "/path/to/image3" }, { id: 4, name: "Item 2 of category 1", price: 43.21, image: "/path/to/image4" }] }
];

const getItemsById = (arr = []) => {
  // get list of ids to search for
  const ids = arr.map(({ id }) => id);
  // iterate over list of objects
  return data.reduce((list, elem) => {
    // get current items with ids
    const items = elem.items.filter(({ id }) => ids.includes(id));
    // if any found, add element with filtered list
    if(items.length > 0) list.push({ ...elem, items });
    return list;
  }, []);
}

console.log( getItemsById([{ id: 1 }, { id: 3 }, { id: 4 }]) );

A: Is this what you're looking for?

const obj = {
  category: {
     name: "Test",
     items: [{
        id: 1,
        name: "Test",
        price: 50,
        image: "Test",
     }],
  }
}

console.log(obj.category.items[0].id);