问:
"command not found: pyenv" when called by zsh script
I have made a launcher on my xubuntu desktop which calls a script named dev_blog.sh.

dev_blog.sh contains :

```<code>#!/usr/bin/zsh
echo ça marche
pyenv activate zinnia
/usr/bin/zsh
</code>```

When I call the launcher from the desktop, my terminal opens and I can read :

dev_blog.sh:3: command not found: pyenv

Whereas when I type the same line in the same terminal, it works.

Here's the content of my .zshrc :

```<code>export ZSH=/home/proph73/.oh-my-zsh
ZSH_THEME="agnoster"
PATH="$HOME/bin:$HOME/.local/bin:$PATH"
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
source $ZSH/oh-my-zsh.sh`
</code>```

答: PATH="$HOME/bin:$HOME/.local/bin:$PATH"  move this to your .profile or use the full path to the executable in your shortcut  $(which pyenv)</p>

Body:
I have made a launcher on my xubuntu desktop which calls a script named dev_blog.sh.

dev_blog.sh contains :

#!/usr/bin/zsh
echo ça marche
pyenv activate zinnia
/usr/bin/zsh

When I call the launcher from the desktop, my terminal opens and I can read :

dev_blog.sh:3: command not found: pyenv

Whereas when I type the same line in the same terminal, it works.

Here's the content of my .zshrc :

export ZSH=/home/proph73/.oh-my-zsh
ZSH_THEME="agnoster"
PATH="$HOME/bin:$HOME/.local/bin:$PATH"
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
source $ZSH/oh-my-zsh.sh`


来源: stackexchange

问:
Laravel redirecting when accessing post route directly
I do a post request to a route calculate-cars and display an other view with some data I query based on the data I entered in the form I do the post request from, but I want to redirect to the homepage when someone access this route directly.

Unfortunately I keep getting this error:

Symfony \ Component \ HttpKernel \ Exception \
  MethodNotAllowedHttpException No message

my route:

Route::post('calculate-cars', 'CarsController@calculateCars');

I know I get this error because I access a post route directly but I try this in my controller method but I still get the same error:

```<code>if (!$request->isMethod('post')) {
    return redirect()->to('/');
}
</code>```

答:
You didn't explain why you expect a POST request. Do you save calculations to save time (cache)? Only in that case, POST is a right decision.

In addition to others: it's important to choose your http methods wisely.

GET: for READ (no system change)!

POST: for CREATE

etc.

Like I said, why did you choose for POST? Change only to GET if you want to read. MDN has a clear summary about the methods: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

ContentLicense: CC BY-SA 3.0

Body:
I do a post request to a route calculate-cars and display an other view with some data I query based on the data I entered in the form I do the post request from, but I want to redirect to the homepage when someone access this route directly.

Unfortunately I keep getting this error:

Symfony \ Component \ HttpKernel \ Exception \
  MethodNotAllowedHttpException No message

my route:

Route::post('calculate-cars', 'CarsController@calculateCars');

I know I get this error because I access a post route directly but I try this in my controller method but I still get the same error:

if (!$request->isMethod('post')) {
    return redirect()->to('/');
}


问:
how to filter hashmap and find 1st occurance
i have converted my hashmap to json as i dont know what itt looks like in java

so my hashmap looks like

```<code>{"1":[true,false],
"2":[true,true],
"3":[true]}
</code>```

i need to get the first occurance of all true in the array list in a single key

in this case its 2 is the 1st occurance

so if there is an occurance   ///do something   else //do somethig else

```<code>   hm.forEach((key, value) -> {

            for (Object object : value) {

                   boolean b = (boolean)object;
                   if(!b){
                   break;
                    }else{
                       System.out.println(key+"->"+b);
                   }

            }
});
</code>```

i tried something like this but im getting lost in the mix  here its testing alotall the cases

any help would be greatly appreciated

答:
You can use this schema

```<code>hm.entrySet().stream().filter(SomeClass::isAllBoolean)
        .findFirst()
        .ifPresent(System.out::println);

private static boolean isAllBoolean(Map.Entry<String, List<Boolean>> values) {

}
</code>```

SomeClass is a class where isAllBoolean method is located.

Body:
i have converted my hashmap to json as i dont know what itt looks like in java

so my hashmap looks like

{"1":[true,false],
"2":[true,true],
"3":[true]}

i need to get the first occurance of all true in the array list in a single key

in this case its 2 is the 1st occurance

so if there is an occurance   ///do something   else //do somethig else

   hm.forEach((key, value) -> {

            for (Object object : value) {

                   boolean b = (boolean)object;
                   if(!b){
                   break;
                    }else{
                       System.out.println(key+"->"+b);
                   }

            }
});

i tried something like this but im getting lost in the mix  here its testing alotall the cases

any help would be greatly appreciated

Body:
You can use this schema

hm.entrySet().stream().filter(SomeClass::isAllBoolean)
        .findFirst()
        .ifPresent(System.out::println);

private static boolean isAllBoolean(Map.Entry<String, List<Boolean>> values) {

}

SomeClass is a class where isAllBoolean method is located.


问:
How to get average score of K-Fold cross validation with sklearn
I apply decision tree with K-fold using sklearn and someone can help me to show the average score of it. Below is my code:</p>

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix,classification_report

dta=pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/blood-transfusion/transfusion.data")

X=dta.drop("whether he/she donated blood in March 2007",axis=1)

X=X.values # convert dataframe to numpy array

y=dta["whether he/she donated blood in March 2007"]

y=y.values # convert dataframe to numpy array

kf = KFold(n_splits=10)

KFold(n_splits=10, random_state=None, shuffle=False)

clf_tree=DecisionTreeClassifier()

for train_index, test_index in kf.split(X):
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    clf=clf_tree.fit(X_train,y_train)
    print("classification_report_tree",
           classification_report(y_test,clf_tree.predict(X_test)))
</code>```

答:
If you only want accuracy, then you can simply use cross_val_score()

```<code>kf = KFold(n_splits=10)
clf_tree=DecisionTreeClassifier()
scores = cross_val_score(clf_tree, X, y, cv=kf)

avg_score = np.mean(score_array)
print(avg_score)
</code>```

Here cross_val_score will take as input your original X and y (without splitting into train and test). cross_val_score will automatically split them into train and test, fit the model on train data and score on test data. And those scores will be returned in the scores variable.

So when you have 10 folds, 10 scores will be returned in scores variable. You can then just take an average of that.

Body:
I apply decision tree with K-fold using sklearn and someone can help me to show the average score of it. Below is my code:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix,classification_report

dta=pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/blood-transfusion/transfusion.data")

X=dta.drop("whether he/she donated blood in March 2007",axis=1)

X=X.values # convert dataframe to numpy array

y=dta["whether he/she donated blood in March 2007"]

y=y.values # convert dataframe to numpy array

kf = KFold(n_splits=10)

KFold(n_splits=10, random_state=None, shuffle=False)

clf_tree=DecisionTreeClassifier()

for train_index, test_index in kf.split(X):
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    clf=clf_tree.fit(X_train,y_train)
    print("classification_report_tree",
           classification_report(y_test,clf_tree.predict(X_test)))

Body:
If you only want accuracy, then you can simply use cross_val_score()

kf = KFold(n_splits=10)
clf_tree=DecisionTreeClassifier()
scores = cross_val_score(clf_tree, X, y, cv=kf)

avg_score = np.mean(score_array)
print(avg_score)

Here cross_val_score will take as input your original X and y (without splitting into train and test). cross_val_score will automatically split them into train and test, fit the model on train data and score on test data. And those scores will be returned in the scores variable.

So when you have 10 folds, 10 scores will be returned in scores variable. You can then just take an average of that.


问:
What stages would be involved in compiling Assembly language to Machine Code
I'm trying to write a compiler to take an assembler file which will output raw machine code instructions.

I've found lots of tutorials on how to write a compiler, but I'm wondering if all the stages are relevant to assembler mnemonics. For instance, is lexical analysis necessary at all given the simplified stage-by-stage format of assembler, or will it still be necessary but in a simpler format?

答: As I see it, the lexical analysis is all that is needed, where the need of a parser is lessened because of the flat structure of assembly.</p>

ContentLicense: CC BY-SA 2.5


问:
using type alias doesn't work with "const" pointer
Here, const pointer hold the address of const variable. like :

```<code>#include <iostream>

int main()
{
    const int i = 5;
    const int* ptr = &i;
}
</code>```

It's working fine.

But, If I use using (Type alias) like:

```<code>#include <iostream>

using intptr = int*;

int main() {
    const int i = 5;
    const intptr ptr = &i;
}
</code>```

GCC compiler gives an error. [Live demo]

Why pointer does not work with using Type alias?

答:
The const keyword is actually binding to the word to the left of it. The notable exception is when the only word it can bind to is on the right hand side.

This means const int* ptr can be rewritten as int const* ptr while
const intptr ptr is equivalent to intptr const ptr which is int *const ptr.

Body:
Here, const pointer hold the address of const variable. like :

#include <iostream>

int main()
{
    const int i = 5;
    const int* ptr = &i;
}

It's working fine.

But, If I use using (Type alias) like:

#include <iostream>

using intptr = int*;

int main() {
    const int i = 5;
    const intptr ptr = &i;
}

GCC compiler gives an error. [Live demo]

Why pointer does not work with using Type alias?


问:
Windows Use SpeechRecognizer with UWP app in background
I need to capture speech and convert it in text while user is using its computer.
I know "SpeechRecognizer" class in UWP and i've setupped an application that works if it is in "Active", but if you switch app (i.e. use browser) it doesn't capture speech.

How can i capture speech while user is using its pc?

答: Solved creating a WPF application and using SpeechRecognitionEngine (System.Speech) instead of SpeechRecognizer of UWP</p>


问:
LDLt factorization using SciPy's Python bindings to LAPACK
I am trying to get the LDLt factorization of a given symmetric matrix with SciPy's Python bindings to LAPACK using the dsysv routine which actually solves linear systems using this matrix factorization.

I have tried the following:

```<code>import numpy as np
from scipy.linalg.lapack import dsysv

A = np.random.randint(1, 1000, size=(5, 5))
A = (A + A.T)
b = np.random.randn(5)
lult, piv, x, _ = dsysv(A, b, lower=1)
</code>```

Where x would be the solution for the above linear system and lult and piv contain information about the factorization.

How can I reconstruct LDLt from it? Sometimes negative values are contained in piv and from the docs I was not able to understand their meaning.

LAPACK's sytrf actually computes this factorization (without solving any linear system) but it does not seem available via SciPy.

There is an example here with the output I am interested in (see eq. 3-23).

答:
Updating scipy to version >= 1.0.0 should do the trick.

A wrapper to sytrf has been added to the master branch in mid-September, just before the 1.0.0 Beta release.
You can find the relevant pull-request and commit on Github.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get the LDLt factorization of a given symmetric matrix with SciPy's Python bindings to LAPACK using the dsysv routine which actually solves linear systems using this matrix factorization.

I have tried the following:

import numpy as np
from scipy.linalg.lapack import dsysv

A = np.random.randint(1, 1000, size=(5, 5))
A = (A + A.T)
b = np.random.randn(5)
lult, piv, x, _ = dsysv(A, b, lower=1)

Where x would be the solution for the above linear system and lult and piv contain information about the factorization.

How can I reconstruct LDLt from it? Sometimes negative values are contained in piv and from the docs I was not able to understand their meaning.

LAPACK's sytrf actually computes this factorization (without solving any linear system) but it does not seem available via SciPy.

There is an example here with the output I am interested in (see eq. 3-23).


问:
ReactJS: making props available in static function of composed component
I have a higher order component, that provides the complete website layout, including a sidebar. This sidebar contains some static elements (e.g. a logo, the home button, imprint and disclaimer) and some dynamic content, provided by the composed component.

```<code>const HtmlSkeleton = (ComposedComponent) => {
    class Wrapper extends Component {
        [...]
        render() {
            return (
                <div>
                    <Sidebar content={ComposedComponent.getSidebarContent()} />
                    <Header />
                    <Content>
                        <ComposedComponent {...this.props} />
                    </Content>
                    </Footer />
                </div>
            )
        }
    }

    return connect(...)(Wrapper)
}
</code>```

Then I have some views/containers, that will be composed by that HOC:

```<code>class View extends Component {
     static getSidebarContent = () => {
         // how to access someFunction?!?

         return [...some stuff depending on props. How do I have access?]
     }
     constructor(props) {
          [....]
     }
     [...]
     someFunction = () => { [....] }
     render() {
        this.someFunction()
        [...]
    }
}
export default connect(....)(HtmlSkeleton(View))
</code>```

(connect is from react-redux, but not that important in that case)

Or is there any other possibility to keep the layout in some kind of component, that I don´t see? Where do you keep the basic HTML?
I´m using react-router, react-redux and redux-saga.

答:
You can pass the props directly to your getSidebarContent:

```<code><Sidebar content={ComposedComponent.getSidebarContent(this.props)} />
</code>```

And retrieve them in your function:

```<code>class View extends Component {
     static getSidebarContent = (props) => {
         return ...
     }
     [...]
}
</code>```

Body:
I have a higher order component, that provides the complete website layout, including a sidebar. This sidebar contains some static elements (e.g. a logo, the home button, imprint and disclaimer) and some dynamic content, provided by the composed component.

const HtmlSkeleton = (ComposedComponent) => {
    class Wrapper extends Component {
        [...]
        render() {
            return (

                    <Sidebar content={ComposedComponent.getSidebarContent()} />

                    <Content>
                        <ComposedComponent {...this.props} />
                    </Content>

            )
        }
    }

    return connect(...)(Wrapper)
}

Then I have some views/containers, that will be composed by that HOC:

class View extends Component {
     static getSidebarContent = () => {
         // how to access someFunction?!?

         return [...some stuff depending on props. How do I have access?]
     }
     constructor(props) {
          [....]
     }
     [...]
     someFunction = () => { [....] }
     render() {
        this.someFunction()
        [...]
    }
}
export default connect(....)(HtmlSkeleton(View))

(connect is from react-redux, but not that important in that case)

Or is there any other possibility to keep the layout in some kind of component, that I don´t see? Where do you keep the basic HTML?
I´m using react-router, react-redux and redux-saga.

Body:
You can pass the props directly to your getSidebarContent:

<Sidebar content={ComposedComponent.getSidebarContent(this.props)} />

And retrieve them in your function:

class View extends Component {
     static getSidebarContent = (props) => {
         return ...
     }
     [...]
}


问:
How do i use scrolltop correctly so that it triggers two times?
Im trying to change the the css of my logo, when it reaches a certain point on the website, and then backagain after the specific section is finished.
But im having trouble doing it correctly. any help?

I have already made this scroll function but it only works one way.

```<code>$(document).ready(function () {
   $(window).scroll(function () {
    if( $(this).scrollTop() > 600 ) {
      $(".uk-responsive-height").css("display", "none");
      $(".uk-logo-inverse").css("display", "block");
   } else if( $(this).scrollTop() > 999) {
      $(".uk-logo-inverse").css("display", "none");
      $(".uk-responsive-height").css("display", "block");
   }
  });
});
</code>```

This worked for me. I don't know if this is the best way. I tweaked the numbers to fit better for my page.

```<code>$(document).ready(function () {
    $(window).scroll(function () {
     if( $(this).scrollTop() > 1700 ) {
       $(".uk-responsive-height").css("display", "block");
       $(".uk-logo-inverse").css("display", "none");
    return;
 }
 if ( $(this).scrollTop() > 600) {
    $(".uk-responsive-height").css("display", "none");
    $(".uk-logo-inverse").css("display", "block");
 }
 if ( $(this).scrollTop() < 600) {
    $(".uk-responsive-height").css("display", "block");
    $(".uk-logo-inverse").css("display", "none");
  }
   });
 });
</code>```

答:
Try to check firstly highest scrollTop() and interrupt function after that

```<code>if( $(this).scrollTop() > 999 ) {
    $(".uk-logo-inverse").css("display", "none");
    $(".uk-responsive-height").css("display", "block");

    return;
}

if( $(this).scrollTop() > 600) {
    $(".uk-responsive-height").css("display", "none");
    $(".uk-logo-inverse").css("display", "block");
}
</code>```

After this comment

Maybe i need to say this. There is two logos, one is normal white and the other one is black. This code nearly works but starts to show both logos. I only need it ".uk-logo-inversed to be display block between 600-1000 after that it should be removed, unless back on those specific pixels

try this

```<code>if ($(this).scrollTop() > 600 && $(this).scrollTop() < 1000) {
    $(".uk-logo-inversed").css("display", "block");
    $(".uk-responsive-height").css("display", "none");
} else {
    $(".uk-logo-inversed").css("display", "none");
    $(".uk-responsive-height").css("display", "block");
}
</code>```

or solution with less code

```<code>$(".uk-logo-inversed")[$(this).scrollTop() > 600 && $(this).scrollTop() < 1000 ? 'show' : 'hide']();
$(".uk-responsive-height")[$(this).scrollTop() > 600 && $(this).scrollTop() < 1000 ? 'hide' : 'show']();
</code>```

Body:
Im trying to change the the css of my logo, when it reaches a certain point on the website, and then backagain after the specific section is finished.
But im having trouble doing it correctly. any help?

I have already made this scroll function but it only works one way.

$(document).ready(function () {
   $(window).scroll(function () {
    if( $(this).scrollTop() > 600 ) {
      $(".uk-responsive-height").css("display", "none");
      $(".uk-logo-inverse").css("display", "block");
   } else if( $(this).scrollTop() > 999) {
      $(".uk-logo-inverse").css("display", "none");
      $(".uk-responsive-height").css("display", "block");
   }
  });
});

This worked for me. I don't know if this is the best way. I tweaked the numbers to fit better for my page.

$(document).ready(function () {
    $(window).scroll(function () {
     if( $(this).scrollTop() > 1700 ) {
       $(".uk-responsive-height").css("display", "block");
       $(".uk-logo-inverse").css("display", "none");
    return;
 }
 if ( $(this).scrollTop() > 600) {
    $(".uk-responsive-height").css("display", "none");
    $(".uk-logo-inverse").css("display", "block");
 }
 if ( $(this).scrollTop() < 600) {
    $(".uk-responsive-height").css("display", "block");
    $(".uk-logo-inverse").css("display", "none");
  }
   });
 });

Body:
Try to check firstly highest scrollTop() and interrupt function after that

if( $(this).scrollTop() > 999 ) {
    $(".uk-logo-inverse").css("display", "none");
    $(".uk-responsive-height").css("display", "block");

    return;
}

if( $(this).scrollTop() > 600) {
    $(".uk-responsive-height").css("display", "none");
    $(".uk-logo-inverse").css("display", "block");
}

After this comment

Maybe i need to say this. There is two logos, one is normal white and the other one is black. This code nearly works but starts to show both logos. I only need it ".uk-logo-inversed to be display block between 600-1000 after that it should be removed, unless back on those specific pixels

try this

if ($(this).scrollTop() > 600 && $(this).scrollTop() < 1000) {
    $(".uk-logo-inversed").css("display", "block");
    $(".uk-responsive-height").css("display", "none");
} else {
    $(".uk-logo-inversed").css("display", "none");
    $(".uk-responsive-height").css("display", "block");
}

or solution with less code

$(".uk-logo-inversed")[$(this).scrollTop() > 600 && $(this).scrollTop() < 1000 ? 'show' : 'hide']();
$(".uk-responsive-height")[$(this).scrollTop() > 600 && $(this).scrollTop() < 1000 ? 'hide' : 'show']();


问:
How to pass the parameter to User-Defined Function?
I have a user-defined function:

```<code>calc = udf(calculate, FloatType())

param1 = "A"

result = df.withColumn('col1', calc(col('type'), col('pos'))).groupBy('pk').sum('events')

def calculate(type, pos):
   if param1=="A":
       a, b = [ 0.05, -0.06 ]
   else:
       a, b = [ 0.15, -0.16 ]
   return a * math.pow(type, b) * max(pos, 1)
</code>```

I need to pass a parameter param1 to this udf. How can I do it?

答:
You can use lit or typedLit as a parameter for your udf like this:

In Python:

```<code>from pyspark.sql.functions import udf, col, lit
mult = udf(lambda value, multiplier: value * multiplier)
df = spark.sparkContext.parallelize([(1,),(2,),(3,)]).toDF()
df.select(mult(col("_1"), lit(3)))
</code>```

In Scala:

```<code>import org.apache.spark.sql.functions.{udf, col, lit}
val mult = udf((value: Double, multiplier: Double) => value * multiplier)
val df = sparkContext.parallelize((1 to 10)).toDF
df.select(mult(col("value"), lit(3)))
</code>```

Body:
I have a user-defined function:

calc = udf(calculate, FloatType())

param1 = "A"

result = df.withColumn('col1', calc(col('type'), col('pos'))).groupBy('pk').sum('events')

def calculate(type, pos):
   if param1=="A":
       a, b = [ 0.05, -0.06 ]
   else:
       a, b = [ 0.15, -0.16 ]
   return a * math.pow(type, b) * max(pos, 1)

I need to pass a parameter param1 to this udf. How can I do it?

Body:
You can use lit or typedLit as a parameter for your udf like this:

In Python:

from pyspark.sql.functions import udf, col, lit
mult = udf(lambda value, multiplier: value * multiplier)
df = spark.sparkContext.parallelize([(1,),(2,),(3,)]).toDF()
df.select(mult(col("_1"), lit(3)))

In Scala:

import org.apache.spark.sql.functions.{udf, col, lit}
val mult = udf((value: Double, multiplier: Double) => value * multiplier)
val df = sparkContext.parallelize((1 to 10)).toDF
df.select(mult(col("value"), lit(3)))


问:
Dynamically Sorting with LINQ
I have a collection of CLR objects. The class definition for the object has three properties: FirstName, LastName, BirthDate.

I have a string that reflects the name of the property the collection should be sorted by. In addition, I have a sorting direction. How do I dynamically apply this sorting information to my collection? Please note that sorting could be multi-layer, so for instance I could sort by LastName, and then by FirstName.

Currently, I'm trying the following without any luck:

```<code>var results = myCollection.OrderBy(sortProperty);
</code>```

However, I'm getting a message that says:

... does not contain a defintion for 'OrderBy'  and the best extension method overload ... has some invalid arguments.

答:
For dynamic sorting you could evaluate the string i.e. something like

```<code>List<MyObject> foo = new List<MyObject>();
string sortProperty = "LastName";
var result = foo.OrderBy(x =>
                {
                if (sortProperty == "LastName")
                    return x.LastName;
                else
                    return x.FirstName;
                });
</code>```

For a more generic solution see this SO thread: Strongly typed dynamic Linq sorting

Title: Dynamically Sorting with LINQ

Body:
I have a collection of CLR objects. The class definition for the object has three properties: FirstName, LastName, BirthDate.

I have a string that reflects the name of the property the collection should be sorted by. In addition, I have a sorting direction. How do I dynamically apply this sorting information to my collection? Please note that sorting could be multi-layer, so for instance I could sort by LastName, and then by FirstName.

Currently, I'm trying the following without any luck:

var results = myCollection.OrderBy(sortProperty);

However, I'm getting a message that says:

... does not contain a defintion for 'OrderBy'  and the best extension method overload ... has some invalid arguments.

Body:
For dynamic sorting you could evaluate the string i.e. something like

List<MyObject> foo = new List<MyObject>();
string sortProperty = "LastName";
var result = foo.OrderBy(x =>
                {
                if (sortProperty == "LastName")
                    return x.LastName;
                else
                    return x.FirstName;
                });

For a more generic solution see this SO thread: Strongly typed dynamic Linq sorting


问:
Magento order mail are not going to customer?
My magento site stoped sending the order mail to customer, i have checked several answer, but nothing works for me.
I tried to send mail with php mail funtion, its working but mail going to spam also. Is this may be a reason?</p>

答: This may be a server fault, it may be an issue of server mail configuration. Try to install some SMTP mail extension, it will be helpful for you. Also check if there any new installation of extension which causing problem</p>


问:
Is there a way to make the compiler pick a certain overload where its somewhat ambiguous?
I got this:

```<code>json& add(char* key, char* value) {
    s.append("\"").append(key).append("\":\"").append(value).append("\",");
    return *this;
}

json& add(char* key, const char* value) {
    s.append("\"").append(key).append("\":\"").append(value).append("\",");
    return *this;
}

template <typename vt>
json& add(char* key, vt value) {
    s.append("\"").append(key).append("\":").append(std::to_string(value)).append(",");
    return *this;
}
</code>```

So 3 overloads for this function.

The first one is supposed to handle a char* value.

The last one is supposed to handle all the numeric types like uint_8t, int_8t, uint16_t .... float, double

if I use this function for example:

```<code>void test(json obj, char* value) {
    obj.add("test", value);
}
</code>```

Then everything works alright with just the first and the last overload. If I try to do this however:

```<code>void test(json obj) {
    obj.add("test", "blah");
}
</code>```

Then it will try to use the last overload (the one with the template) instead of the char* one since technically I'm passing a const char* to it.

So now I need to have the middle overload just for that.

Question is - is there a way to define a range of types for the template that its supposed to handle? To restrict vt to only the numeric types I mentioned? That should divert the compiler to use the char* overload instead and I wouldn't need the const char* one.

答:
The way to do it today is using enable_if and type traits. You want to define your template function as follows:

```<code>    template <typename vt, typename = std::enable_if_t<std::is_arithmetic_v<vt>>>
json& add(const char* key, vt value) {
    s.append("\"").append(key).append("\":").append(std::to_string(value)).append(",");
    return *this;
}
</code>```

Note this part: typename = std::enable_if_t<std::is_arithmetic_v<vt>>>

Hopefully in the next standard we will get concepts which will simplify this weird syntax.

If you are looking for more information, and background behind this technique, this is a very nice article: https://eli.thegreenplace.net/2014/sfinae-and-enable_if/

Body:
I got this:

json& add(char* key, char* value) {
    s.append("\"").append(key).append("\":\"").append(value).append("\",");
    return *this;
}

json& add(char* key, const char* value) {
    s.append("\"").append(key).append("\":\"").append(value).append("\",");
    return *this;
}

template <typename vt>
json& add(char* key, vt value) {
    s.append("\"").append(key).append("\":").append(std::to_string(value)).append(",");
    return *this;
}

So 3 overloads for this function.

The first one is supposed to handle a char* value.

The last one is supposed to handle all the numeric types like uint_8t, int_8t, uint16_t .... float, double

if I use this function for example:

void test(json obj, char* value) {
    obj.add("test", value);
}

Then everything works alright with just the first and the last overload. If I try to do this however:

void test(json obj) {
    obj.add("test", "blah");
}

Then it will try to use the last overload (the one with the template) instead of the char* one since technically I'm passing a const char* to it.

So now I need to have the middle overload just for that.

Question is - is there a way to define a range of types for the template that its supposed to handle? To restrict vt to only the numeric types I mentioned? That should divert the compiler to use the char* overload instead and I wouldn't need the const char* one.

Body:
The way to do it today is using enable_if and type traits. You want to define your template function as follows:

    template <typename vt, typename = std::enable_if_t<std::is_arithmetic_v<vt>>>
json& add(const char* key, vt value) {
    s.append("\"").append(key).append("\":").append(std::to_string(value)).append(",");
    return *this;
}

Note this part: typename = std::enable_if_t<std::is_arithmetic_v<vt>>>

Hopefully in the next standard we will get concepts which will simplify this weird syntax.

If you are looking for more information, and background behind this technique, this is a very nice article: https://eli.thegreenplace.net/2014/sfinae-and-enable_if/


问:
Eclipse Buildship: composite builds without changing settings.gradle
In Eclipse, I have a imported a Gradle project that has a binary (.jar) dependency to a library which is built using a separate Gradle project.

I want to be able to make changes to the library in Eclipse and use the changed code immediately.  This should be possible using the relatively new "Composite Builds" Gradle feature.

I'm using Buildship 2.0.  I've found out that I can do this by changing settings.gradle to specify an included build.  However, I don't want to commit this change to Git (since it breaks the standalone build) and I prefer not to have to keep local changes anyway.

Is there a way to specify the projects to include in the composite build without changing settings.gradle?  In IntelliJ IDEA this is possible simply by right-clicking the project and choosing "Composite Build Configuration"

答:
I had the same issue and have solved it with a small workaround. I don't know if it is acceptable for you because it is unfortunately a change in </p>

```<code>settings.gradle

rootProject.name = 'root'

if (file('../subA').exists()) {
    includeBuild  '../subA'
}
</code>```

<p>Hint: If your root project is a web app and you want to start it in eclipse(wtp), you have to make sure that your sub projects apply the plugin 'eclipse-wtp'. </p>

Body:
I had the same issue and have solved it with a small workaround. I don't know if it is acceptable for you because it is unfortunately a change in

settings.gradle

rootProject.name = 'root'

if (file('../subA').exists()) {
    includeBuild  '../subA'
}

Hint: If your root project is a web app and you want to start it in eclipse(wtp), you have to make sure that your sub projects apply the plugin 'eclipse-wtp'.


问:
Convert Terraform Templates to Cloudformation Templates
I want to convert the existing terraform templates(hcl) to aws cloudformation templates(json/yaml).

I basically want to find security issues with these templates through CFN_NAG.

An approach that I have already tried was converting HCL to JSON and then passing the template to CFN_NAG but I received a failure since both the templates have different structure.

Can anyone please provide any suggestions here?

答:
A rather convoluted way of achieving this is to use Terraform to stand-up actual AWS environments, and then to use AWS’s CloudFormer to extract  CloudFormation templates (JSON or YAML) from what Terraform has built. At which point you can use cfn-nag.

CloudFormer has some limitations, in that not all AWS resources are currently supported (RDS Security Groups for example) , but it will get you all the basic AWS resources.

Don't forget to remove all the environments, including CloudFormer's, to minimise the cost.


问:
unable to hide div in angular js using ng-if
unable to hide div on loading page.
I want to show the div if the value of array is empty.</p>

```<code>    <div ng-hide="loading"  ng-if="users== null || users.length === 0" >
        <h3>No Result Found</h3>
    </div>
</code>```

答:
This is what you should do.

```<code>//This will check if loading is false and Users are not undefined || less than equal to 0 (empty array)
<div ng-if="!loading || !users || users.length <= 0">
    <h3>No Result Found</h3>
</div>

//Show data if users are defined and length is greater than 0
<div ng-if="users && users.length > 0">
        <h3>Data</h3>
</div>
</code>```

Using ng-show and ng-hide

```<code>//Show if loading is true or users are undefined or users are empty
//Hide if loading is false or users are defined or users are not empty
<div ng-show="loading || !users || users.length <= 0"
     ng-hide="!loading || users || users.length > 0">
        <h3>No Result Found</h3>
</div>

//Show if users are defined and length is greater than 0
//Hide if loading is true or users are undefined or users are empty
<div ng-show="users && users.length > 0"
     ng-hide="loading || !users || users.length <= 0">
        <h3>Data</h3>
</div>
</code>```

ng-hide/show just sets the display property of the element to "none" whereas, ng-if removes the element from the dom

Body:
unable to hide div on loading page.
I want to show the div if the value of array is empty.

No Result Found

Body:
This is what you should do.

//This will check if loading is false and Users are not undefined || less than equal to 0 (empty array)
<div ng-if="!loading || !users || users.length <= 0">
    <h3>No Result Found</h3>
</div>

//Show data if users are defined and length is greater than 0
<div ng-if="users && users.length > 0">
        <h3>Data</h3>
</div>

Using ng-show and ng-hide

//Show if loading is true or users are undefined or users are empty
//Hide if loading is false or users are defined or users are not empty
<div ng-show="loading || !users || users.length <= 0"
     ng-hide="!loading || users || users.length > 0">
        <h3>No Result Found</h3>
</div>

//Show if users are defined and length is greater than 0
//Hide if loading is true or users are undefined or users are empty
<div ng-show="users && users.length > 0"
     ng-hide="loading || !users || users.length <= 0">
        <h3>Data</h3>
</div>

ng-hide/show just sets the display property of the element to "none" whereas, ng-if removes the element from the dom


问:
Is there a way to NOT load a specific control in ASP.NET/C#?
I've a container (RadDockZone - Telerik), and inside it, a textbox field with an "Asp:RequiredFieldValidator", which makes it mandatory. Every time that I work with AJAX operations, the entire container is "reloaded", including the RequiredFieldValidator. This makes the ValidationSummary show the same error message twice, until the page is completely reloaded (I'm using RadAjaxManager to solve the AJAX operations).

So, how can I "don't reload" a specific control (in this case, the RequiredFieldValidator) using C#?

Regards!

答:
You should use validation groups.  This lets you group all of your validation controls into a group.  Then put this same validation group on your submit button and those validation controls will only validate when that particular button is clicked.

Property is assigned on the validation control and button using the ValidationGroup property.

Thomasvdb's suggestion of setting CausesValidation to false also might be a good way to do it.


问:
Multiple Useful-Buttons on same page
I've made a "Useful-Button" with jQuery so user can rate e.g. an answer of a question (like the upvote function here on stackoverflow).

function submitForm() {
 var form = document.myform;
 var dataString = $(form).serialize();

 $.ajax({
  type:'POST',
    url:'like_submit.php',
    data: dataString,
    success: function(data){
     $('#myResponse').html(data);
     $('#myResponse').fadeIn().delay(3000).fadeOut();
    }
   });
   return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" class="myform" method="post" name="myform">
 Was this 1. answer helpful?
  <input type="hidden" name="answer_id" value="1" />
  <input  class="label__checkbox" type="checkbox" name="helpful" onclick="submitForm()" />
</form>
<div id="myResponse"></div></code>```

The like_submit.php is like this:

```<code><?php
$helpful = $_POST['helpful'];
$answer_id = $_POST['answer_id'];
echo "Thank you! Helpful? $helpful | AnswerID: $answer_id";
?>
</code>```

So for one answer it works.

But now I want to add more than one answer and I doesn't know how get the script to work for this case.

If I add a second form...

```<code><form id="myform" class="myform" method="post" name="myform">
Was this 2. answer helpful?
  <input type="hidden" name="answer_id" value="2" />
  <input  class="label__checkbox" type="checkbox" name="helpful" onclick="submitForm()" />
</form>
<div id="myResponse"></div>
</code>```

... I have two problems. I only get the last POST-data right. If I click the first form, it says:
Thank you! Helpful? on | AnswerID: 2

Second problem, the response message appears allways an the first position.

Can anyone help? Many thanks!

答:
Get the elements relative to the submitted form

html:
onclick="submitForm(this)"

js:

```<code>function submitForm(el) {
    var form = $(el).closest('form');
    var dataString = form.serialize();

    $.ajax({
        type:'POST',
    url:'like_submit.php',
    data: dataString,
    success: function(data){
        form.next('#myResponse').html(data);
        form.next('#myResponse').fadeIn().delay(3000).fadeOut();
    }
   });
   return false;
}
</code>```

function submitForm(el) {
 var form = $(el).closest('form');
 var dataString = form.serialize();
     form.next('#myResponse').html(dataString);
     form.next('#myResponse').fadeIn().delay(3000).fadeOut();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" class="myform" method="post" name="myform">
 Was this 1. answer helpful?
  <input type="hidden" name="answer_id" value="1" />
  <input  class="label__checkbox" type="checkbox" name="helpful" onclick="submitForm(this)" />
</form>
<div id="myResponse"></div>
<form id="myform" class="myform" method="post" name="myform">
Was this 2. answer helpful?
  <input type="hidden" name="answer_id" value="2" />
  <input  class="label__checkbox" type="checkbox" name="helpful" onclick="submitForm(this)" />
</form>
<div id="myResponse"></div></code>```

Title: Multiple Useful-Buttons on same page

Body:
I've made a "Useful-Button" with jQuery so user can rate e.g. an answer of a question (like the upvote function here on stackoverflow).

function submitForm() {
 var form = document.myform;
 var dataString = $(form).serialize();

 $.ajax({
  type:'POST',
    url:'like_submit.php',
    data: dataString,
    success: function(data){
     $('#myResponse').html(data);
     $('#myResponse').fadeIn().delay(3000).fadeOut();
    }
   });
   return false;
}

<form id="myform" class="myform" method="post" name="myform">
 Was this 1. answer helpful?
  <input type="hidden" name="answer_id" value="1" />
  <input  class="label__checkbox" type="checkbox" name="helpful" onclick="submitForm()" />
</form>

The like_submit.php is like this:

<?php
$helpful = $_POST['helpful'];
$answer_id = $_POST['answer_id'];
echo "Thank you! Helpful? $helpful | AnswerID: $answer_id";
?>

So for one answer it works.

But now I want to add more than one answer and I doesn't know how get the script to work for this case.

If I add a second form...

<form id="myform" class="myform" method="post" name="myform">
Was this 2. answer helpful?
  <input type="hidden" name="answer_id" value="2" />
  <input  class="label__checkbox" type="checkbox" name="helpful" onclick="submitForm()" />
</form>

... I have two problems. I only get the last POST-data right. If I click the first form, it says:
Thank you! Helpful? on | AnswerID: 2

Second problem, the response message appears allways an the first position.

Can anyone help? Many thanks!

Body:
Get the elements relative to the submitted form

html:
onclick="submitForm(this)"

js:

function submitForm(el) {
    var form = $(el).closest('form');
    var dataString = form.serialize();

    $.ajax({
        type:'POST',
    url:'like_submit.php',
    data: dataString,
    success: function(data){
        form.next('#myResponse').html(data);
        form.next('#myResponse').fadeIn().delay(3000).fadeOut();
    }
   });
   return false;
}

function submitForm(el) {
 var form = $(el).closest('form');
 var dataString = form.serialize();
     form.next('#myResponse').html(dataString);
     form.next('#myResponse').fadeIn().delay(3000).fadeOut();
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" class="myform" method="post" name="myform">
 Was this 1. answer helpful?
  <input type="hidden" name="answer_id" value="1" />
  <input  class="label__checkbox" type="checkbox" name="helpful" onclick="submitForm(this)" />
</form>
<div id="myResponse"></div>
<form id="myform" class="myform" method="post" name="myform">
Was this 2. answer helpful?
  <input type="hidden" name="answer_id" value="2" />
  <input  class="label__checkbox" type="checkbox" name="helpful" onclick="submitForm(this)" />
</form>
<div id="myResponse"></div>


问:
Check if value exists in the list
Let’s say I have 123-0-1 and I want to check if this value exists inside the list. Below is the list that I have:

```<code> df = [
       {'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'},
       {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}
      ]
</code>```

In SQL I would use:

```<code>select mpls, source from df where source = 192.168.10.10
</code>```

From the list, I would like extract mpls 123-0-1 from the source 192.168.10.10 such that I can get the correct destination 12.168.100.10.

答:
Why not make a dataframe of it?</p>

```<code>df = pd.DataFrame(df)
df[df['source'] == '192.168.10.10']
</code>```

Title: Check if value exists in the list

Body:
Let’s say I have 123-0-1 and I want to check if this value exists inside the list. Below is the list that I have:

 df = [
       {'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'},
       {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}
      ]

In SQL I would use:

select mpls, source from df where source = 192.168.10.10

From the list, I would like extract mpls 123-0-1 from the source 192.168.10.10 such that I can get the correct destination 12.168.100.10.

Body:
Why not make a dataframe of it?

df = pd.DataFrame(df)
df[df['source'] == '192.168.10.10']


问:
Keep information in div always display with specific number of lines
I have a question about how can I keep the information inside a div always displays within a specific number of lines.

As stated as the structure inside the JSFiddle, I have 3 kinds of information to be displayed within a div. Sometime each of them will be short as one line only, but sometimes they may be long name displayed in multiple lines. And for the "
" which may appear occasionally.

So what I want is those information in the div will always display within 3 lines. If there is information inside the "promotion-content", only the promotion content will be shown, it will still be 3 lines height even its information has less that 3 lines.

So when I do not contain any promotion, only brand name and product name will be shown and they are limited as 3 lines height.  But if both names are short that only have 2 lines, I will still have a empty 3rd. Can I do it with HTML and CSS other than adding a
 by myself for each related product?

I am confused about the way to do all these and I have tried with height limitation but seems it doesn't work. I am wondering if they can be done by HTML and CSS tricks?? Can someone please give me some direction on it? Thanks!!!

答:
You can set min-height to the div

In HTML

```<code>    <div class="information">
      <p class="promotion-content">
      Buy 1 Get 1 Free
      </p>
      <p class="brand-name">
      ABC Brand
      </p>
      <p class="product-name">
      Product Name
      </p>
    </div>
</code>```

In CSS

```<code>    .information {
      min-height:120px;
      border: 1px solid #ddd;
    }
</code>```

you can refer this JSFiddle

Body:
You can set min-height to the div

In HTML

    <div class="information">
      <p class="promotion-content">
      Buy 1 Get 1 Free
      </p>
      <p class="brand-name">
      ABC Brand
      </p>
      <p class="product-name">
      Product Name
      </p>
    </div>

In CSS

    .information {
      min-height:120px;
      border: 1px solid #ddd;
    }

you can refer this JSFiddle


问:
Pygame.midi.init() function errors
I can't call the pygame.midi.init() function on my Debian machine. Running the following code:

```<code>import pygame, pygame.midi
pygame.midi.init()
</code>```

will result in the following errors:

ALSA lib conf.c:3009:(snd_config_update_r) Cannot access file /etc/alsa/alsa.conf

ALSA lib seq.c:935:(snd_seq_open_noupdate) Unknown SEQ default

Can any one help?
PS: i am using Debian 9.2

答:
Making a link to the /usr/share/alsa/alsa.conf did the work:

sudo ln -s /usr/share/alsa/alsa.conf /etc/alsa/alsa.conf

Title: Pygame.midi.init() function errors

Body:
I can't call the pygame.midi.init() function on my Debian machine. Running the following code:

import pygame, pygame.midi
pygame.midi.init()

will result in the following errors:

ALSA lib conf.c:3009:(snd_config_update_r) Cannot access file /etc/alsa/alsa.conf

ALSA lib seq.c:935:(snd_seq_open_noupdate) Unknown SEQ default

Can any one help?
PS: i am using Debian 9.2


问:
Loading localStorage is not updating my variables
I got these variables

```<code>var moneycount = 0;
var b1 = document.createElement("IMG");

function update() {
  document.getElementById('money').innerHTML = moneycount;
}
</code>```

And functions for saving/loading

```<code>function save() {
  localStorage.setItem("moneycount", moneycount);
};

function load() {
  moneycount = localStorage.getItem("moneycount");
  moneycount = parseInt(moneycount);
  update();
};
</code>```

This function works as intended but wont update with localStorage

```<code>function add() {
  moneycount = moneycount + 1
  if (moneycount >= 1) {
    document.getElementById('badge1').appendChild(b1);
  }
  update();
}
</code>```

It seems like var moneycount = 0 still is 0 after I load localStorage because if (moneycount >= 1) is not working. The document element is still displaying a bigger number after loading localStorage. Any ideas on how I can store my add() function?

Edit:

Found a temporary solution with setting setInterval(save, 5000); and adding  and calling it on refresh.

答:
that is because you do not update the localStorage instead you just update the html element:  should do it as followed:</p>

```<code>var moneycount = 0;
var b1 = document.createElement("IMG");

    function update() {
      document.getElementById('money').innerHTML = moneycount;
    localStorage.setItem("moneycount", moneycount);

    }

    function save() {
      localStorage.setItem("moneycount", moneycount);
    };

    function add() {
      localStorage.getItem("moneycount")+=  1;
      if (moneycount >= 1) {
        document.getElementById('badge1').appendChild(b1);
      }
      update();
    }
</code>```

Body:
I got these variables

var moneycount = 0;
var b1 = document.createElement("IMG");

function update() {
  document.getElementById('money').innerHTML = moneycount;
}

And functions for saving/loading

function save() {
  localStorage.setItem("moneycount", moneycount);
};

function load() {
  moneycount = localStorage.getItem("moneycount");
  moneycount = parseInt(moneycount);
  update();
};

This function works as intended but wont update with localStorage

function add() {
  moneycount = moneycount + 1
  if (moneycount >= 1) {
    document.getElementById('badge1').appendChild(b1);
  }
  update();
}

It seems like var moneycount = 0 still is 0 after I load localStorage because if (moneycount >= 1) is not working. The document element is still displaying a bigger number after loading localStorage. Any ideas on how I can store my add() function?

Edit:

Found a temporary solution with setting setInterval(save, 5000); and adding  and calling it on refresh.

Body:
that is because you do not update the localStorage instead you just update the html element:  should do it as followed:

var moneycount = 0;
var b1 = document.createElement("IMG");

    function update() {
      document.getElementById('money').innerHTML = moneycount;
    localStorage.setItem("moneycount", moneycount);

    }

    function save() {
      localStorage.setItem("moneycount", moneycount);
    };

    function add() {
      localStorage.getItem("moneycount")+=  1;
      if (moneycount >= 1) {
        document.getElementById('badge1').appendChild(b1);
      }
      update();
    }


问:
Angular typescript error: Type 'string' is not assignable to type 'any[]'
I make a service to get data from back-end as the pre-defined model then I call the data into my component, however, I got the error that I could not solve it after doing research on the Internet. The error happens in my component when I try to pass data into an empty string that I declared before.

This is my service:

```<code>import { Observable } from 'rxjs/Observable';
import { Injectable, Inject } from '@angular/core';
import { Http, Response } from '@angular/http';
import { ORIGIN_URL, API_PREFIX } from '../shared/constants/baseurl.constants';
import { History } from '../models/history';
import 'rxjs/add/operator/map';

@Injectable()
export class HistoricalBpiService {

  private apiUrl: string;

  constructor(
    private http: Http,
    @Inject(ORIGIN_URL) private baseUrl: string,
    @Inject(API_PREFIX) private apiPrefix: string
  ) {
    this.apiUrl = baseUrl + apiPrefix;
  }

  oneYear(): Observable<History[]> {
    return this.http.get(this.apiUrl + 'data/history/365')
      .map((res: Response) => res.json() as History[])
      .catch(this.handleError);
  }

  private handleError(error: any) {
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }
}
</code>```

This is the model:

```<code>export interface History {
    date: string;
    value: number;
}
</code>```

This is the component:

```<code>import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core';
import { HistoricalBpiService } from '../../services/historical-bpi.service';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
import { History } from '../../models/history';

@Component({
  selector: 'app-banner',
  templateUrl: './banner.component.html',
  styleUrls: ['./banner.component.scss']
})
export class BannerComponent implements OnInit {

  history: History[] = [];

  public lineChartData: any = [
    { data: [], label: 'BTC' }
  ];

  public lineChartLabels: Array<any> = [];

  constructor(
    private historicalBpiService: HistoricalBpiService,
    @Inject(PLATFORM_ID) private platformId: Object
  ) {}

  oneYear() {
    this.historicalBpiService.oneYear()
      .subscribe((data: History[]) => {
        this.history = data;
        for (let i of this.history) {
          this.lineChartData[0].data = i.value;
          this.lineChartLabels = i.date; // THIS LINE CAUSES ERROR !!!
        }
      });
  }

  ngOnInit() {
    if (isPlatformBrowser(this.platformId)) {
      // Default chart
      this.oneYear();
    }
  }
}
</code>```

答:
As the error says, you are trying to assign a string to the type of any,
You need to push the string to the array,</p>

```<code>this.lineChartLabels.push(i.date);
</code>```

Body:
I make a service to get data from back-end as the pre-defined model then I call the data into my component, however, I got the error that I could not solve it after doing research on the Internet. The error happens in my component when I try to pass data into an empty string that I declared before.

This is my service:

import { Observable } from 'rxjs/Observable';
import { Injectable, Inject } from '@angular/core';
import { Http, Response } from '@angular/http';
import { ORIGIN_URL, API_PREFIX } from '../shared/constants/baseurl.constants';
import { History } from '../models/history';
import 'rxjs/add/operator/map';

@Injectable()
export class HistoricalBpiService {

  private apiUrl: string;

  constructor(
    private http: Http,
    @Inject(ORIGIN_URL) private baseUrl: string,
    @Inject(API_PREFIX) private apiPrefix: string
  ) {
    this.apiUrl = baseUrl + apiPrefix;
  }

  oneYear(): Observable<History[]> {
    return this.http.get(this.apiUrl + 'data/history/365')
      .map((res: Response) => res.json() as History[])
      .catch(this.handleError);
  }

  private handleError(error: any) {
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }
}

This is the model:

export interface History {
    date: string;
    value: number;
}

This is the component:

import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core';
import { HistoricalBpiService } from '../../services/historical-bpi.service';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
import { History } from '../../models/history';

@Component({
  selector: 'app-banner',
  templateUrl: './banner.component.html',
  styleUrls: ['./banner.component.scss']
})
export class BannerComponent implements OnInit {

  history: History[] = [];

  public lineChartData: any = [
    { data: [], label: 'BTC' }
  ];

  public lineChartLabels: Array<any> = [];

  constructor(
    private historicalBpiService: HistoricalBpiService,
    @Inject(PLATFORM_ID) private platformId: Object
  ) {}

  oneYear() {
    this.historicalBpiService.oneYear()
      .subscribe((data: History[]) => {
        this.history = data;
        for (let i of this.history) {
          this.lineChartData[0].data = i.value;
          this.lineChartLabels = i.date; // THIS LINE CAUSES ERROR !!!
        }
      });
  }

  ngOnInit() {
    if (isPlatformBrowser(this.platformId)) {
      // Default chart
      this.oneYear();
    }
  }
}

Body:
As the error says, you are trying to assign a string to the type of any,
You need to push the string to the array,

this.lineChartLabels.push(i.date);


问:
org.springframework.beans.factory.UnsatisfiedDependencyException on Cloud Rest Client with Netflix Ribbon
I am getting
a org.springframework.beans.factory.UnsatisfiedDependencyException while running SpringClientSideRibbonApplication.java class. I think there is no error but I don't know why this exception comes. Please help me. I am using STS IDE.

MyConfiguration.java

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.PingUrl;
import com.netflix.loadbalancer.WeightedResponseTimeRule;
public class MyConfiguration {
@Autowired
IClientConfig ribbonClientConfig;
@Bean
public IPing ribbonPing(IClientConfig config) {
    return new PingUrl();
}

@Bean
public IRule ribbonRule() {
  return new WeightedResponseTimeRule();
}

}
</code>```

SpringClientSideRibbonApplication.java

```<code>package com.javasampleapproach.ribbon;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.ribbon.RibbonClient;

@SpringBootApplication
@RibbonClient(name = "helloworld", configuration =
MyConfiguration.class)
public class SpringClientSideRibbonApplication {

public static void main(String[] args)
{
    SpringApplication.run(SpringClientSideRibbonApplication.class,
args);
}
}
</code>```

WebController.java

```<code>package com.javasampleapproach.ribbon;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class WebController {
@LoadBalanced
@Bean
RestTemplate restTemplate() {
    return new RestTemplate();
}
@Autowired
RestTemplate restTemplate;
@RequestMapping("/helloworld")
public String home() {
    return
this.restTemplate.getForObject("http://helloworld/greeting",
String.class);
}
}
</code>```

Error Msg

```<code>Error creating bean with name 'myConfiguration': Unsatisfied
dependency expressed through field 'ribbonClientConfig'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'ribbonClientConfiguration': Invocation
of init method failed; nested exception is
java.lang.NoClassDefFoundError:
org/apache/commons/configuration/AbstractConfiguration
</code>```

Application.yml

```<code>spring:
application:
name: Ribbon-Client

helloworld:
ribbon:
eureka:
  enabled: false
listOfServers: localhost:8090,localhost:8091,localhost:8092
ServerListRefreshInterval: 15000

server:
port: 8080
</code>```

Dependency

```<code><dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-ribbon</artifactId>
        <version>1.3.5.RELEASE </version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
   </dependencies>
</code>```

答: Their is no coding error. The problem was in my Maven dependency.My internet is slow so Maven download the corrupt jar file. I tried with Gradle. Now it's okey </p>

Body:
I am getting
a org.springframework.beans.factory.UnsatisfiedDependencyException while running SpringClientSideRibbonApplication.java class. I think there is no error but I don't know why this exception comes. Please help me. I am using STS IDE.

MyConfiguration.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.PingUrl;
import com.netflix.loadbalancer.WeightedResponseTimeRule;
public class MyConfiguration {
@Autowired
IClientConfig ribbonClientConfig;
@Bean
public IPing ribbonPing(IClientConfig config) {
    return new PingUrl();
}

@Bean
public IRule ribbonRule() {
  return new WeightedResponseTimeRule();
}

}

SpringClientSideRibbonApplication.java

package com.javasampleapproach.ribbon;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.ribbon.RibbonClient;

@SpringBootApplication
@RibbonClient(name = "helloworld", configuration =
MyConfiguration.class)
public class SpringClientSideRibbonApplication {

public static void main(String[] args)
{
    SpringApplication.run(SpringClientSideRibbonApplication.class,
args);
}
}

WebController.java

package com.javasampleapproach.ribbon;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class WebController {
@LoadBalanced
@Bean
RestTemplate restTemplate() {
    return new RestTemplate();
}
@Autowired
RestTemplate restTemplate;
@RequestMapping("/helloworld")
public String home() {
    return
this.restTemplate.getForObject("http://helloworld/greeting",
String.class);
}
}

Error Msg

Error creating bean with name 'myConfiguration': Unsatisfied
dependency expressed through field 'ribbonClientConfig'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'ribbonClientConfiguration': Invocation
of init method failed; nested exception is
java.lang.NoClassDefFoundError:
org/apache/commons/configuration/AbstractConfiguration

Application.yml

spring:
application:
name: Ribbon-Client

helloworld:
ribbon:
eureka:
  enabled: false
listOfServers: localhost:8090,localhost:8091,localhost:8092
ServerListRefreshInterval: 15000

server:
port: 8080

Dependency

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-ribbon</artifactId>
        <version>1.3.5.RELEASE </version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
   </dependencies>


问:
multiple object creation on a single API call on django
i have to create multiple object creation on a single API call.My
 serializer class is like this

```<code>def create(self, validated_data):
    dt = datetime.now()
    strg = '{:%d%m%Y%H%M%S}'.format(dt, dt.microsecond // 1000)
    hat= "REQ" + strg
    creater = dot_order_models.DotOrder(reqnum=hat,**validated_data)
    creater.save()
    return creater
class Meta:
    model = dot_order_models.DotOrder
    fields = ('merchant', 'biker','batch','customer_name','contact','city','locality','order_amount')
</code>```

i just given many=true but did not work. then i give

```<code>def __init__(self, *args, **kwargs):
    many = kwargs.pop('many', True)
    super(BikerSerializer, self).__init__(many=many, *args, **kwargs)
</code>```

this too didn't work.how can i solve it using serializers and view class.
thanks in advance

答:
```<code>def create(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list))
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    results = dot_order_models.DotOrder.objects.all()
    output_serializer = dot_order_serializers.DotOrderSerializer(results, many=True)
    return super(DotOrderViewSet, self).create(request)
</code>```

Body:
i have to create multiple object creation on a single API call.My
 serializer class is like this

def create(self, validated_data):
    dt = datetime.now()
    strg = '{:%d%m%Y%H%M%S}'.format(dt, dt.microsecond // 1000)
    hat= "REQ" + strg
    creater = dot_order_models.DotOrder(reqnum=hat,**validated_data)
    creater.save()
    return creater
class Meta:
    model = dot_order_models.DotOrder
    fields = ('merchant', 'biker','batch','customer_name','contact','city','locality','order_amount')

i just given many=true but did not work. then i give

def __init__(self, *args, **kwargs):
    many = kwargs.pop('many', True)
    super(BikerSerializer, self).__init__(many=many, *args, **kwargs)

this too didn't work.how can i solve it using serializers and view class.
thanks in advance


问:
Using IObservable (Rx) as a INotifyCollectionChanged Replacement for MVVM?
I have been looking into using Rx in an MVVM framework.  The idea is to use 'live' LINQ queries over in-memory datasets to project data into View Models to bind with.

Previously this has been possible with the use of INotifyPropertyChanged/INotifyCollectionChanged and an open source library called CLINQ.  The potential with Rx and IObservable is to move to a much more declarative ViewModel using Subject classes to propagate changed events from the source model through to the View.  A conversion from IObservable to the regular databinding interfaces would be needed for the last step.

The problem is that Rx doesn't seem to support the notification that an entity has been removed from the stream.  Example below.

The code shows a POCO which uses BehaviorSubject class for the field state.  The code goes onto to create a collection of these entities and use Concat to merge the filter streams together.  This means that any changes to the POCOs are reported to a single stream.

A filter for this stream is setup to filter for Rating==0. The subscription simply outputs the result to the debug window when an even occurs.

Settings Rating=0 on any element will trigger the event.  But setting Rating back to 5 will not see any events.

In the case of CLINQ the output of the query will support INotifyCollectionChanged - so that items added and removed from the query result will fire the correct event to indicate the query result has changed (an item added or removed).

The only way I can think of address this is to set-up two streams with oppossite (dual) queries.  An item added to the opposite stream implies removal from the resultset.  Failing that, I could just use FromEvent and not make any of the entity models observable - which makes Rx more of just an Event Aggregator.  Any pointers?

```<code>using System;
using System.ComponentModel;
using System.Linq;
using System.Collections.Generic;

namespace RxTest
{

    public class TestEntity : Subject<TestEntity>, INotifyPropertyChanged
    {
        public IObservable<string> FileObservable { get; set; }
        public IObservable<int> RatingObservable { get; set; }

        public string File
        {
            get { return FileObservable.First(); }
            set { (FileObservable as IObserver<string>).OnNext(value); }
        }

        public int Rating
        {
            get { return RatingObservable.First(); }
            set { (RatingObservable as IObserver<int>).OnNext(value); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public TestEntity()
        {
            this.FileObservable = new BehaviorSubject<string>(string.Empty);
            this.RatingObservable = new BehaviorSubject<int>(0);
            this.FileObservable.Subscribe(f => { OnNotifyPropertyChanged("File"); });
            this.RatingObservable.Subscribe(f => { OnNotifyPropertyChanged("Rating"); });
        }

        private void OnNotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property));
            // update the class Observable
            OnNext(this);
        }

    }

    public class TestModel
    {
        private List<TestEntity> collection { get; set; }
        private IDisposable sub;

        public TestModel()
        {
            this.collection = new List<TestEntity>() {
            new TestEntity() { File = "MySong.mp3", Rating = 5 },
            new TestEntity() { File = "Heart.mp3", Rating = 5 },
            new TestEntity() { File = "KarmaPolice.mp3", Rating = 5 }};

            var observableCollection = Observable.Concat<TestEntity>(this.collection.Cast<IObservable<TestEntity>>());
            var filteredCollection = from entity in observableCollection
                                     where entity.Rating==0
                                     select entity;
            this.sub = filteredCollection.Subscribe(entity =>
                {
                    System.Diagnostics.Debug.WriteLine("Added :" + entity.File);
                }
            );
            this.collection[0].Rating = 0;
            this.collection[0].Rating = 5;
        }
    };
}
</code>```

答:
The problem is that you are looking at the notifications from a List of TestEntitys, not from the TestEntity themselves.  So you see adds, but not changes in any TestEntity. To see this comment out:

```<code>        if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property));
</code>```

and you'll see that the program runs the same! Your notifications in your TestEntity's are not wired up to anything. As stated by others, using an ObservableCollection will add this wiring for you.

Body:
I have been looking into using Rx in an MVVM framework.  The idea is to use 'live' LINQ queries over in-memory datasets to project data into View Models to bind with.

Previously this has been possible with the use of INotifyPropertyChanged/INotifyCollectionChanged and an open source library called CLINQ.  The potential with Rx and IObservable is to move to a much more declarative ViewModel using Subject classes to propagate changed events from the source model through to the View.  A conversion from IObservable to the regular databinding interfaces would be needed for the last step.

The problem is that Rx doesn't seem to support the notification that an entity has been removed from the stream.  Example below.

The code shows a POCO which uses BehaviorSubject class for the field state.  The code goes onto to create a collection of these entities and use Concat to merge the filter streams together.  This means that any changes to the POCOs are reported to a single stream.

A filter for this stream is setup to filter for Rating==0. The subscription simply outputs the result to the debug window when an even occurs.

Settings Rating=0 on any element will trigger the event.  But setting Rating back to 5 will not see any events.

In the case of CLINQ the output of the query will support INotifyCollectionChanged - so that items added and removed from the query result will fire the correct event to indicate the query result has changed (an item added or removed).

The only way I can think of address this is to set-up two streams with oppossite (dual) queries.  An item added to the opposite stream implies removal from the resultset.  Failing that, I could just use FromEvent and not make any of the entity models observable - which makes Rx more of just an Event Aggregator.  Any pointers?

using System;
using System.ComponentModel;
using System.Linq;
using System.Collections.Generic;

namespace RxTest
{

    public class TestEntity : Subject<TestEntity>, INotifyPropertyChanged
    {
        public IObservable<string> FileObservable { get; set; }
        public IObservable<int> RatingObservable { get; set; }

        public string File
        {
            get { return FileObservable.First(); }
            set { (FileObservable as IObserver<string>).OnNext(value); }
        }

        public int Rating
        {
            get { return RatingObservable.First(); }
            set { (RatingObservable as IObserver<int>).OnNext(value); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public TestEntity()
        {
            this.FileObservable = new BehaviorSubject<string>(string.Empty);
            this.RatingObservable = new BehaviorSubject<int>(0);
            this.FileObservable.Subscribe(f => { OnNotifyPropertyChanged("File"); });
            this.RatingObservable.Subscribe(f => { OnNotifyPropertyChanged("Rating"); });
        }

        private void OnNotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property));
            // update the class Observable
            OnNext(this);
        }

    }

    public class TestModel
    {
        private List<TestEntity> collection { get; set; }
        private IDisposable sub;

        public TestModel()
        {
            this.collection = new List<TestEntity>() {
            new TestEntity() { File = "MySong.mp3", Rating = 5 },
            new TestEntity() { File = "Heart.mp3", Rating = 5 },
            new TestEntity() { File = "KarmaPolice.mp3", Rating = 5 }};

            var observableCollection = Observable.Concat<TestEntity>(this.collection.Cast<IObservable<TestEntity>>());
            var filteredCollection = from entity in observableCollection
                                     where entity.Rating==0
                                     select entity;
            this.sub = filteredCollection.Subscribe(entity =>
                {
                    System.Diagnostics.Debug.WriteLine("Added :" + entity.File);
                }
            );
            this.collection[0].Rating = 0;
            this.collection[0].Rating = 5;
        }
    };
}

Body:
The problem is that you are looking at the notifications from a List of TestEntitys, not from the TestEntity themselves.  So you see adds, but not changes in any TestEntity. To see this comment out:

        if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property));

and you'll see that the program runs the same! Your notifications in your TestEntity's are not wired up to anything. As stated by others, using an ObservableCollection will add this wiring for you.


问:
Regarding Dilated Convolutions vs Max-Pooling with Padding
I have been going through the paper, Multi-Scale Context Aggregation by Dilated Convolutions.

In it they propose using dilated convolution to get global context as opposed to max-pooling/downsampling since pooling will shrink your image and dilated convolutions will not.

My first question is: They modify VGG16 and remove the last two max-pooling layers but they leave the other 3 max-pooling layers in. Why did they not just remove all the max pooling layers? Computational efficiency? Won't this result in a smaller image? How do they expand it back to the original size, bilinear interpolation?

My second question is: They note in the paper:

"We also remove the padding of the intermediate feature maps.
  Intermediate padding was used in the original classification network,
  but is neither necessary nor justified in dense prediction."

Why would that be the case, if you don't pad will you not further reduce the size of our final output, especially given that dilated convolutions can have very large receptive fields?

答:
Answering your first question, I think you are correct, the output is 1/8th the original size and they  use interpolation to upsample to original size. You can find the evidence in source code available here. In the file test.py, function test_image, the default zoom is set at 8 (line 103). More evidence can be found in the file train.py where again default zoom is set to True and they use an upsampling layer.

And since they are already reducing size they dont need to use padding just to retain size. The reason I think padding is not needed in their case is that segmentation is a case of dense prediction and thus introducing some pixels from our own side don't intuitively make sense. But again the best way to argue about the same would be to practically test a network both with and without intermediate pooling.


问:
How to use grep -e to match partial words?
If you use grep like

```<code>grep -rnw '/your/path/to/search/' -e 'n getFoo'
</code>```

grep wouldn't find a file that contains "function getFoo()".

If you only search for 'getFoo' or else 'function getFoo', grep will find the file that contains the function.

So what's the best way to find a file containing part(s) of a string?

Thanks in advance!

答:
You should remove the -w option which tells grep to only match whole words.

```<code>grep -rn '/your/path/to/search/' -e 'n getFoo'
</code>```

will also search in between word boundaries.

Body:
If you use grep like

grep -rnw '/your/path/to/search/' -e 'n getFoo'

grep wouldn't find a file that contains "function getFoo()".

If you only search for 'getFoo' or else 'function getFoo', grep will find the file that contains the function.

So what's the best way to find a file containing part(s) of a string?

Thanks in advance!

Body:
You should remove the -w option which tells grep to only match whole words.

grep -rn '/your/path/to/search/' -e 'n getFoo'

will also search in between word boundaries.


问:
In PL/SQL what is a difference between a cursor and a reference cursor?
As per my knowledge, a cursor is used to process SQL statements in private area and we can use it further. A Ref cursor is defining a cursor at the spot where it is needed. Please correct me if I am wrong..</p>

答:
Static cursor is associated with single SQL query.
It is not flexible that is why use dynamic cursor called as ref cursor to use same cursor for different queries.


问:
Change Packet interface using NKE
Im developing a VPN app, i was looking for to route App specific packets from the default en0 interface. I was wondering can I achieve this by using NKE?

Let say all data from Safari goes through ppp0 interface and all data from Chrome goes through en0.

答:
I can't give you a 100% definite answer as I've never had to solve that specific problem before, and it doesn't seem to be documented anywhere. I can point you at a few things, which are where I would be focusing my research if I was being tasked with implementing such functionality.

As of WWDC 2017, Network Kernel Extensions are deprecated. Apple wants you to create user-space "Network Extensions" instead. There are special VPN classes you can implement. In theory, these allow per-app rules (see "Per-App VPN"), but in practice they seem to be tied to MDM, which seems like an odd decision. You may want to get in touch with Apple about getting that changed if that conflicts with what you're trying to do. They're actively soliciting input on the Network Extension API.

Network Kernel Extensions (NKE) are the more mature API. Routing happens between the "IP Filter" and "Interface Filter" stages. I'm not sure you can directly affect them through either of those filtering stages. Perhaps by removing packets using an interface filter on the default interface, and injecting them into your VPN interface's? I'm not sure that's wise though, and you may have trouble matching packets to the process that sent them at that stage of the network stack.

You could try binding a socket to a specific interface device (using IP_BOUND_IF) from a socket filter NKE.

The Berkeley Packet Filter (BPF) is also a possible solution.

Title: Change Packet interface using NKE


答:
Here is a possible solution using list comprehension, as you are working with lists:

```<code>[(x['mpls'], x['destination']) for x in df if x['source'] == '192.168.10.10']
</code>```

It returns a tuple with mpls and destination based on source:

```<code>[('123-0-1', '12.168.100.10')]
</code>```

Title: Check if value exists in the list

Body:
Here is a possible solution using list comprehension, as you are working with lists:

[(x['mpls'], x['destination']) for x in df if x['source'] == '192.168.10.10']

It returns a tuple with mpls and destination based on source:

[('123-0-1', '12.168.100.10')]


问:
XAMPP/Localhost external Javascript File empty
I've set up a website with XAMPP, have working on some PHP things and now tried to include some Javascript functions. My index.php is in the htdocs folder. In that htdocsfolder, I have a JS folder with a scripts.js file. The file shows up in my Sources when inspecting the website in my browser, but it is completely empty.

I have the following line in the head of my index file:

```<code><script src="js/scripts.js" type="text/javascript" ></script>
</code>```

I found this question:
resource files are coming up empty when hosted locally

People mention it might be an htaccess problem. I don't know anything about htaccess. There is currently no htaccess file in my htdocs folder.

Code in my scripts.js file:

```<code>alert("Hi!");

function toggle(element, show) {
    document.getElementById(element).style.display = show;
}

function toggleLogin() {
    toggle('registerWrapper', 'none');
    toggle('loginWrapper', 'block');
}

function toggleRegister() {
    toggle('loginWrapper', 'none');
    toggle('registerWrapper', 'block');
}
</code>```

How can I solve this?

答:
Try to give that file full permissions just to see if that is your issue. Then lower it if that is a case.

Also see if the file owner is as your xampp expects (or as other files are)

Body:
I've set up a website with XAMPP, have working on some PHP things and now tried to include some Javascript functions. My index.php is in the htdocs folder. In that htdocsfolder, I have a JS folder with a scripts.js file. The file shows up in my Sources when inspecting the website in my browser, but it is completely empty.

I have the following line in the head of my index file:

I found this question:
resource files are coming up empty when hosted locally

People mention it might be an htaccess problem. I don't know anything about htaccess. There is currently no htaccess file in my htdocs folder.

Code in my scripts.js file:

alert("Hi!");

function toggle(element, show) {
    document.getElementById(element).style.display = show;
}

function toggleLogin() {
    toggle('registerWrapper', 'none');
    toggle('loginWrapper', 'block');
}

function toggleRegister() {
    toggle('loginWrapper', 'none');
    toggle('registerWrapper', 'block');
}

How can I solve this?


问:
How to find the Nth number in a fractal sequence?
The assignment is to write a C++ program which takes the input number n and outputs the nth number in the sequence:

1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 ...

This is what I've come up with so far:

```<code>#include <iostream>
using namespace std;

int main()
{
    long long n,k=1,result;
    cin >> n;
    if(n==1){
        result=1;
    }else{
        for(int i=1,j=1;;i=j,j=j+k){
            if(n>i&&n<=j){
                result=n-i;
                break;
            }else{
                k++;
            }
        }
    }
    cout << result << endl;
}
</code>```

This is also what I've written before:

```<code>#include <iostream>
using namespace std;

int main()
{
    long long n,count=0,result;
    cin >> n;
    for(int i=1;;i++){
        for(int j=1;j<=i;j++){
            count=count+1;
            if(count==n){
                result=j;
                break;
            }
        }
        if(count>=n){
            break;
        }
    }
    cout << result << endl;
}
</code>```

Both of these work properly for smaller numbers, but the problem is I have to follow the constraint:

1 <= n <= 10^12

So when bigger numbers are inputted, the programs both take too long to output the solution and exceed the time limit, which is 2 seconds. I've been working on this for 5 hours now and I don't know how to improve these programs so they are faster. I also thought about a certain formula that could help determine the nth number in such a sequence, but I can't seem to find anything about it on the internet or in my math books. Could somebody point me to the solution? I would be very grateful.

答:
The first job is to write out the sequence like this:

```<code>1
2   3
4   5   6
7   8   9   10
</code>```

And note that we want to map this to

```<code>1
1   2
1   2   3
1   2   3   4
</code>```

The row position of a number is given by rearranging the formula for an arithmetic progression, solving the resultant quadratic, discarding the negative root, and removing any fractional part of the answer. A number t appears in the row r given by the whole number part

r = R(1/2 + (1/4 + 2 * (t - 1))1/2)

Where R() is a function that rounds a number downwards to the whole number.

But you are after the column c. That is obtained subtracting the value of the first term in that row from t:

c = t - 1/2 * r * (r - 1)

Reference: https://en.wikipedia.org/wiki/Arithmetic_progression

Body:
The assignment is to write a C++ program which takes the input number n and outputs the nth number in the sequence:

1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 ...

This is what I've come up with so far:

#include <iostream>
using namespace std;

int main()
{
    long long n,k=1,result;
    cin >> n;
    if(n==1){
        result=1;
    }else{
        for(int i=1,j=1;;i=j,j=j+k){
            if(n>i&&n<=j){
                result=n-i;
                break;
            }else{
                k++;
            }
        }
    }
    cout << result << endl;
}

This is also what I've written before:

#include <iostream>
using namespace std;

int main()
{
    long long n,count=0,result;
    cin >> n;
    for(int i=1;;i++){
        for(int j=1;j<=i;j++){
            count=count+1;
            if(count==n){
                result=j;
                break;
            }
        }
        if(count>=n){
            break;
        }
    }
    cout << result << endl;
}

Both of these work properly for smaller numbers, but the problem is I have to follow the constraint:

1 <= n <= 10^12

So when bigger numbers are inputted, the programs both take too long to output the solution and exceed the time limit, which is 2 seconds. I've been working on this for 5 hours now and I don't know how to improve these programs so they are faster. I also thought about a certain formula that could help determine the nth number in such a sequence, but I can't seem to find anything about it on the internet or in my math books. Could somebody point me to the solution? I would be very grateful.

Body:
The first job is to write out the sequence like this:

1
2   3
4   5   6
7   8   9   10

And note that we want to map this to

1
1   2
1   2   3
1   2   3   4

The row position of a number is given by rearranging the formula for an arithmetic progression, solving the resultant quadratic, discarding the negative root, and removing any fractional part of the answer. A number t appears in the row r given by the whole number part

r = R(1/2 + (1/4 + 2 * (t - 1))1/2)

Where R() is a function that rounds a number downwards to the whole number.

But you are after the column c. That is obtained subtracting the value of the first term in that row from t:

c = t - 1/2 * r * (r - 1)

Reference: https://en.wikipedia.org/wiki/Arithmetic_progression


问:
How to insert a list of values as an IN(list) criterion in a query?
Consider a table like the following

```<code>CREATE TABLE tbl1(
 id INTEGER PRIMARY KEY,
 someVal INTEGER
);
</code>```

filled with some data (just to not feel like querying an empty table) and a query as follows

```<code>SELECT tbl1.ID, tbl1.someVal
FROM tbl1
WHERE (tbl1.ID In ([TempVar]![t1]));
</code>```

The TempVars collection has been filled with the contents

```<code>TempVars.Add "t1", 1
TempVars.Add "t2", "2"
TempVars.Add "t3", "2,3"
</code>```

via the immediate window.

Now when viewing the query results for different WHERE clauses the following scenarios work (meaning they display the expected results):

Querying for WHERE (tbl1.ID In ([TempVar]![t1])) returns the entry with id = 1

Querying for WHERE (tbl1.ID In ([TempVar]![t2])) returns the entry with id = 2

So far, everything as expected. But for WHERE (tbl1.ID In ([TempVar]![t3])) the query results are empty. Why?

(When I execute ?TempVars("t3") it returns 2,3 - when I then copy/paste that line into the query so it reads WHERE (tbl1.ID In (2,3)) it returns the entries 2 and 3...)

Things to consider:

I'm using the German version of Access 2013, which means that your name for the TempVars collection might differ (for me, in the VBE it's called TempVars, while the query design only allows access via [TempVar]).

Also when manually entering lists into the criterion field in query design mode, I need to separate them with a semicolon, whereas in SQL mode I'm required to use a comma. Stupid language differences. (Whether I define TempVars("t3") with a semicolon or comma doesn't change anything about the zero results, however...)

My research suggests that the very method presented above should work, so I assume I either implemented it wrong or there is something else at play.

My approach isn't necessarily tied to the usage of TempVars. When experimenting with the values of textbox and label controls on forms, I experienced the same issue.

答:
The Why is very easy to answer. If TempVars("t3") contains a string "2, 3", it's only going to match entries where your ID is a string equal to "2, 3". You can't dynamically build IN criteria the way you're doing it, since the , can't be stored in a variable, it has to be present in the SQL.

To fix this, you can use a user-defined function to do the IN check for you. There aren't other solid workarounds as long as you're not dynamically changing your SQL.

Sample UDF:

Public Function SplitIn(commaseparatedlist As String, compare As Variant) As Boolean
    Dim strInArr() As String
    strInArr = Split(commaseparatedlist, ",")
    Dim arrItem As Variant
    For Each arrItem In strInArr
        If arrItem = CStr(Nz(compare, "")) Then
            SplitIn = True
            Exit Function
        End If
    Next arrItem
    SplitIn = False
End Function
```

<p>Usage:</p>

<pre class="lang-sql prettyprint-override"><code>WHERE SplitIn([TempVar]![t3], tbl1.ID)
</code>```

Body:
Consider a table like the following

CREATE TABLE tbl1(
 id INTEGER PRIMARY KEY,
 someVal INTEGER
);

filled with some data (just to not feel like querying an empty table) and a query as follows

SELECT tbl1.ID, tbl1.someVal
FROM tbl1
WHERE (tbl1.ID In ([TempVar]![t1]));

The TempVars collection has been filled with the contents

TempVars.Add "t1", 1
TempVars.Add "t2", "2"
TempVars.Add "t3", "2,3"

via the immediate window.

Now when viewing the query results for different WHERE clauses the following scenarios work (meaning they display the expected results):

Querying for WHERE (tbl1.ID In ([TempVar]![t1])) returns the entry with id = 1

Querying for WHERE (tbl1.ID In ([TempVar]![t2])) returns the entry with id = 2

So far, everything as expected. But for WHERE (tbl1.ID In ([TempVar]![t3])) the query results are empty. Why?

(When I execute ?TempVars("t3") it returns 2,3 - when I then copy/paste that line into the query so it reads WHERE (tbl1.ID In (2,3)) it returns the entries 2 and 3...)

Things to consider:

I'm using the German version of Access 2013, which means that your name for the TempVars collection might differ (for me, in the VBE it's called TempVars, while the query design only allows access via [TempVar]).

Also when manually entering lists into the criterion field in query design mode, I need to separate them with a semicolon, whereas in SQL mode I'm required to use a comma. Stupid language differences. (Whether I define TempVars("t3") with a semicolon or comma doesn't change anything about the zero results, however...)

My research suggests that the very method presented above should work, so I assume I either implemented it wrong or there is something else at play.

My approach isn't necessarily tied to the usage of TempVars. When experimenting with the values of textbox and label controls on forms, I experienced the same issue.

Body:
The Why is very easy to answer. If TempVars("t3") contains a string "2, 3", it's only going to match entries where your ID is a string equal to "2, 3". You can't dynamically build IN criteria the way you're doing it, since the , can't be stored in a variable, it has to be present in the SQL.

To fix this, you can use a user-defined function to do the IN check for you. There aren't other solid workarounds as long as you're not dynamically changing your SQL.

Sample UDF:

Public Function SplitIn(commaseparatedlist As String, compare As Variant) As Boolean
    Dim strInArr() As String
    strInArr = Split(commaseparatedlist, ",")
    Dim arrItem As Variant
    For Each arrItem In strInArr
        If arrItem = CStr(Nz(compare, "")) Then
            SplitIn = True
            Exit Function
        End If
    Next arrItem
    SplitIn = False
End Function

Usage:

WHERE SplitIn([TempVar]![t3], tbl1.ID)


问:
Javascript String.replace(/\$/,str) works weirdly in jsp file
For simplicity, i have the following file named test.jsp:

```<code><script language="javascript">
    alert("a$b".replace(/\$/g,"k"));
</script>
</code>```

I put this file in my local server, then display it using firefox:  http://localhost:8080/myproj/test.jsp. It works okay, the result alert string is:

```<code> akb
</code>```

But when i put this file in a remote server and use the same firefox to display, it output is: a$bk which is incorrect for me.

Then i change the test.jsp content to:

```<code><script language="javascript">
    alert("a$b".replace(/\\$/g,"k"));
</script>
</code>```

Note here i add two slashes instead of one. In this case it works in the remote server but not in local one.

Then i rename the file from test.jsp to test.html, but the content is the same as my first case, i.e.:

```<code><script language="javascript">
    alert("a$b".replace(/\$/g,"k"));
</script>
</code>```

By using the same firefox, it works okay in both servers.

But my file needs to embed the javascript in jsp file. it is not allowed to use .html suffix for my file. What should I do to write a portable javascript in this scenario?

My local server uses tomcat-5.5.26; remote server uses tomcat-5.0.28. Firefox version is  3.0.4.

答: Maybe you can move the javascript code to a separate .js file? This will prevent the code from being interpreted as jsp.</p>

OwnerDisplayName: jscoot

Body:
For simplicity, i have the following file named test.jsp:

I put this file in my local server, then display it using firefox:  http://localhost:8080/myproj/test.jsp. It works okay, the result alert string is:

 akb

But when i put this file in a remote server and use the same firefox to display, it output is: a$bk which is incorrect for me.

Then i change the test.jsp content to:

Note here i add two slashes instead of one. In this case it works in the remote server but not in local one.

Then i rename the file from test.jsp to test.html, but the content is the same as my first case, i.e.:

By using the same firefox, it works okay in both servers.

But my file needs to embed the javascript in jsp file. it is not allowed to use .html suffix for my file. What should I do to write a portable javascript in this scenario?

My local server uses tomcat-5.5.26; remote server uses tomcat-5.0.28. Firefox version is  3.0.4.

LastEditorDisplayName: jscoot

OwnerDisplayName: Simon Groenewolt


答:
I'm guessing that i.date is a string, because this.lineChartLabels is an Array<any> you can't assign a string to it.

Best to push instead of assign:

```<code>this.lineChartLabels.push(i.date)
</code>```

Title: Angular typescript error: Type 'string' is not assignable to type 'any[]'

Body:
I'm guessing that i.date is a string, because this.lineChartLabels is an Array<any> you can't assign a string to it.

Best to push instead of assign:

this.lineChartLabels.push(i.date)


问:
Need Subversion pre-commit hook to block check-ins by a specific user
I have Subversion installed on Windows Server 2008.  I want to add code to the pre-commit.bat to block commits by domain user jdoe on domain foo.  What does that code look like?  I am assuming it will use C:\Program Files (x86)\VisualSVN Server\bin\svnlook.</p>

答:
Please, read the VisualSVN Server Getting Started guide and the section Configuring User Permissions in particular.

VisualSVN Server offers a UI to manage the user permissions. You can use the VisualSVN Server Manager MMC console, PowerShell or RepoCfg to manage the permissions.

Don't forget that SVN server administrators and repository supervisors must understand the access control principles in Subversion. Read the article KB33: Understanding VisualSVN Server authorization for more information.