Q: Regex for Mediawiki replacement I am using the Replace Text extension in MW 1.23 (which uses MySQL regexps) and I want to run regexes that will result in replacements like the ones in the examples below. The point is that it should find only matches that have a single Greek (extended/polytonic) word between the tags or just a word failing that.
Replacing this bit first:

and then the second one:

Is not an option as there are other instances that should not be replaced.
Examples:
First string of each example is the actual string, second string the way it should be after the replacement. The Greek word could be any Greek word (here "σπυρίς" and "ὑσμίνη"):
1.
Dim. of σπυρίς
Dim. of [[σπυρίς]]

2.
cf. ὑσμίνη
cf. [[ὑσμίνη]]

A: Search for the following pattern:
([^\s-\.]*?[σπυρίς]+?[^\s-\.]*?)<\/b>

And replace it with that:
[[$1]]

[σπυρίς] can be extended with any greek character you want to have at least in between the tags.


Q: Can "too" occur in a negative sentence? "That effort too came to nothing" The following sentence is from the BBC web site Trapped
That effort too came to nothing.
We were taught in English classes that too can be used in positive sentences, and either in negative sentences.
So, why was "too" used in this negative sentence?

A: Yes, 'too' in that context means 'also' or 'as well'.
The 'too' referred to 'that effort': "That effort also came to nothing".

A: (Converted my comment to an answer, since it has been upvoted.)
Came to nothing has a negative meaning but it isn't grammatically negative. A negative sentence would be 'That effort did not come to anything either', though in my opinion it doesn't sound as good.

A: Yes, you're right.
We do not usually use also, as well and too in negative sentences. We use not...either in negative sentences.
Positive: I like you too. Negative: I do not like you either.
Positive: I like you as well. Negative: I do not like you  either.
Positive: That effort too came to nothing.
Negative: That effort did not come to anything either.
Nothing is used in positive statements. Anything is used in negative statements.
When we use negative words such as nobody, or nothing, we do not use a negative verb.
He says nothing or He does not say anything (NOT 'He does not say nothing')
'That effort too came to nothing' is stronger and more definite than 'That effort did not come to anything either'.

A: The key point is that grammar cares naught for feelings.
Grammatically, a sentence either uses negation or it doesn't, and based on that one uses either too or either:

*

*That effort too came to nothing: no negation, so we use too and nothing.

*That effort did not come to anything either: negation, so we use either and anything.

Both sentences convey similar (negative) feelings, which grammar doesn't care about in any way.
Another example would be: I like you too <=> I do not hate you either. Both convey positive feelings, and can use either too or either.

A: Yes, but "syntactically positive" not "semantically positive"; so the OP's sentence is actually syntactically not negative:
To clarify this nuance, per @KateBunting's answer, the following example can use "too" since it is "syntactically positive", i.e. the verb isn't negated:

*

*"In 1980, President Carter failed to get reelected, mainly due to a recession. In 1992, President GHW Bush failed too, and for the same reason."
"X failed to do Y" is "syntactically positive", even if we wouldn't consider it "semantically positive" for X's political fortunes.


Q: Cannot retrieve ALL datatable names from database I am developing some code to tabulate the datatable names and their corresponding columns from a database. I want to have the list that I can see on the MS SQL Report Builder - Query Designer:

Here's my code:
SqlConnection conn = new SqlConnection("Data Source = server; Initial catalog = Catalog; Integrated Security = true");
conn.Open();
DataTable dt = conn.GetSchema("Tables");
List<string> tablenames = new List<string>();
foreach(DataRow dr in dt.Rows){
     string table = (string)dr[2];
     if((string)dr[1] == "dbo"){
          //Creating a list of table names for "dbo" schema
          tablenames.Add(table);
     }
}
foreach(string table in tablenames){
     if(true){
          SqlDataReader reader = new SqlCommand("SELECT * FROM " + table, conn).ExecuteReader();
          //Iterating the entire list of table names and getting the column names
          for(int column = 0; column < reader.FieldCount; column++){
               Console.WriteLine("Catalog - dbo - " + table + " - " + reader.GetName(column));
          }
          reader.Close();
     }
}
Console.WriteLine("END");
Console.ReadLine();

However, the list that I get doesn't display (among others) the first table "AccountBillingCode", even though I know it's contained within the list of strings.
If I change the statement:
if(true)

by
if(table.StartsWith('A'))

Then, "AccountBillingCode" is listed in the output.
I don't understand why there are some tables getting excluded from my code.
Any ideas?
Thanks!

A: Something like this as an idea.
select
t.name,c.name
from
sys.tables as t
left join sys.columns as c on t.object_id=c.object_id
order by t.name,c.column_id

A: Apparently, there's nothing wrong with the code. It's just the code is too long for the Console, and when copying from there, the content at the top is missing.
Disappointing mystery this time. Sorry! Thanks for the answers anyway!


Q: Custom Authentication using AbstractAuthenticationProcessingFilter with permitted paths and Also enabling method security with roles I am trying to implement a custom token based authentication with authentication filter:
public class AuthAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws AuthenticationException,
        IOException, ServletException {
        //some code here
    }
    @Override
    protected void successfulAuthentication(final HttpServletRequest request,
        final HttpServletResponse response, final FilterChain chain) {                                                final Authentication authResult) throws IOException, ServletException {
        SecurityContextHolder.getContext().setAuthentication(authResult);
        chain.doFilter(request, response);
    }
}

Registering it with
@Configuration
@Order(2)
@EnableWebSecurity(debug = true)
public class Security extends WebSecurityConfigurerAdapter {

    // constructor and beans etc

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
            .disable().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .requestMatchers(PROTECTED_URLS).hasAnyRole(getAllrolles()).anyRequest()
            .authenticated()
            .and()
            .addFilterBefore(authAuthenticationFilter(),
                 UsernamePasswordAuthenticationFilter.class)
            .formLogin().disable()
            .httpBasic().disable()
            .logout().disable();
    }
}

I have another websecurity config with order 1 for whitelisted urls:
@Configuration
@Order(1)
public class SecurityWhiteList extends WebSecurityConfigurerAdapter {

    //constructor and permitted path etc

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .requestMatchers(permittedPaths()).permitAll()
                .and()
                .anonymous();
    }
}

At last, I have a configuration for method security as follows:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurity extends GlobalMethodSecurityConfiguration {

    private final RoleHierarchy roleHierarchy;

    @Autowired
    public MethodSecurity(RoleHierarchy roleHierarchy) {
        this.roleHierarchy = roleHierarchy;
    }

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        DefaultMethodSecurityExpressionHandler expressionHandler = new
            DefaultMethodSecurityExpressionHandler();
        expressionHandler.setRoleHierarchy(roleHierarchy);
        return expressionHandler;
    }
}

The problem here is, I get 403 for the endpoints having method security in the service method annotated with @PreAuthorize("hasAuthority('ROLE_SOMETHING')) even though the users do have ROLE_SOMETHING.
It works, if @PreAuthorize("hasAuthority('ROLE_SOMETHING')) is not present and roles authentication, permitted path everything works.
After debugging, I found that my method security runs before AuthAuthenticationFilter and thus the security context is not populated yet so the user gets ROLE_ANONYMOUS.
My question is: Is it possible to make the authentication filter fire before method security? Or am I entirely doing it wrong? Like I should instead use oncePerRequestFilter instead of AbstractAuthenticationProcessingFilter?


Q: How to instantiate a scikit-learn model from a string variable? I have a list of models as parameters in a YAML file.
When I read them into my Python script, they appear there as strings:
my_model = "LinearRegression()"
print(type(my_model)) #output: <class 'str'>

I want to initialize my sklearn model as:
model = LinearRegression()

but with LinearRegression() being a string variable.
At the moment, naturally, model = my_model is a string, and can't be fitted, etc.
How to instantiate the sklearn model from a string variable?
My use case: I want to put different models in a YAML file as params in order to sweep over them in the model fine-tuning procedure (a simple AutoML).

A: You have few options:

*

*Use eval as a quick&dirty solution:

from sklearn.linear_model import LinearRegression
model_str = 'LinearRegression()'
model = eval(model_str)
print(model)

Note: using eval is not a safe because it will execute any string so if you have no control about a string variable being executed a malicious code may be executed.
Also you need to import exact the same class before using eval. Without the first line the code will not work.

*use pickle.dumps
from sklearn.linear_model import LinearRegression

model_class_serialized = pickle.dumps(LinearRegression)
print(model_class_serialized)
model_class = pickle.loads(model_class_serialized)
print(model_class)

In that case you do not need explicitly import classes from sklearn.
An example of saving models to YAML:
import pickle
import yaml

from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import LinearSVC

models = [LinearRegression, RandomForestClassifier, LinearSVC]

with open('models.yml', 'w') as out_file:
    yaml.dump({m.__name__: pickle.dumps(m) for m in models}, out_file)

After that you can read YAML file like that:
import pickle
import yaml

with open('models.yml', 'r') as in_file:
    models = yaml.load(in_file, Loader=yaml.FullLoader)
    models = {name: pickle.loads(serialized_cls) for name, serialized_cls in models.items()}

print(models)

Which produces:
{'LinearRegression': <class 'sklearn.linear_model._base.LinearRegression'>, 'LinearSVC': <class 'sklearn.svm._classes.LinearSVC'>, 'RandomForestClassifier': <class 'sklearn.ensemble._forest.RandomForestClassifier'>}

so you can easily instantiate these models:
model = models['RandomForestClassifier']()
print(model)
# model.fit(...)


Q: Grails form token not available for ajax forms? In grails it is easy to add tokens to prevent form double submission and also the click hijacking.
Just add useToken="true" to the form tag:
<g:form ... useToken="true" >

But, this is not available for formRemote tag. I know that I can do normal form and write js code to transform them into ajax froms with token, but because of that is odd that is not supported by default in the formRemote tag.
Any reason for this, or is just (another) bug in Grails?


Q: Some help with connections and voltage arrow in CircuitikZ Good evening,
in the following drawing I added two diodes on the secondary side.
Three questions:

*

*As you can see, I placed D1 first and went from there to D2, inverting D3. I did the same starting from the transformer with the lower part. How do I know connect the transformer terminal B2 to the wire between D3 and D4?

*My added voltage arrow is not placed very well. It needs to go on the right with a little space added. Also it needs to be clear, that it points from the node c1 to node c2. Is there a way to improve this?

Thank you very much.

  \documentclass{article} \usepackage[utf8]{inputenc} \usepackage[siunitx,european,fetbodydiode,smartlabels]{circuitikz} \usetikzlibrary{positioning} \begin{document}

    \begin{figure}   % Generalized diagram of different components inside an AC drive with voltage intermediate circuit % Based on a template by % Author: Erno Pentzin (2013), http://www.texample.net/tikz/examples/ac-drive-components/

      \begin{circuitikz}
        \draw
        % top part of switch legs
        (0,0) coordinate[label=above:s1] (s1)
        to ++ (0,-0.4)
        node (mosfet1) [nigfete,below,anchor=D] {$Q_1$}
        (mosfet1) node (mosfet3) [nigfete,right=22mm]     {$Q_3$}
        (mosfet1.S) to [short,-*] ++ (0,-0.4)           coordinate[label=above:t1] (t1)

        % transformer       (t1 -| mosfet3.S) % Connect Q1 with Q3S which is electrically wrong, but easier to draw
        node (T) [transformer core,below right=0mm and 11mm]{}

        % bottom part of switch legs
        (mosfet3.S |- T.A2)                             coordinate (t2)  % likewase counter intuitive
        to ++ (0,-0.4)
        node (mosfet4) [nigfete,below,anchor=D] {$Q_4$}
        (t1 |- mosfet4.D)   node (mosfet2) [nigfete,below,anchor=D] {$Q_2$}

        % connection lines origins at transformer
        (T.A1) to                       (t1)
        (T.A2) to [short,-*]            (t2)
        (T.B1) to [short,-o]                ++ (0.5,0)  coordinate (t3)
        (T.B2) to [short,-o]                ++ (0.5,0)  coordinate (t4)
        (t3)   to[open, v^=$v_o(t)$]    (t4)

        % connection lines orign at mosfet
        (t1)        to      (mosfet2.D)
        (mosfet2.S) to ++   (0,-0.4)                    coordinate[label=below:s2] (s2)
        (mosfet3.D) to ++   (0, 0.4)                    coordinate[label=above:s3] (s3)
        (mosfet3.S) to      (mosfet4.D)
        (mosfet4.S) to ++   (0,-0.4)                    coordinate (s4)

        % supply lines
        (s3) -- (s1) to [short,*-o] ++ (-2,0)           coordinate (s+) % added *-o, * to get dot at S1
        (s4) -- (s2) to [short,*-o] ++ (-2,0)           coordinate (s-) % added *-o, * to get dot at S2
        (s+) to [open, v=60<\volt>, invert] (s-)

        % secondary side
      (t3) to [Do,name=d1,label=D1] ++(0,1.5) --++(1.5,0)               coordinate[label=above:c1] (c1)
    (c1) to [Do,invert,name=d3,label=$D3$] ++(0,-1.5)

    (t4) to [Do,invert,name=d2,label=D2] ++(0,-1.5) --++(1.5,0)     coordinate[label=below:c2] (c2)
    (c2) to [Do,name=d4,label=D4] ++(0,1.5) -- (d3)
    (d2) -- (d1)
    (t4) -- (d4)
    (c1) to [open, v=60<\volt>, invert] (c2)
;
\end{circuitikz}
\caption[Ersatzschaltbild]{Ersatzschaltbild}
\label{fig:ersatzschaltbild}
\end{figure}
\end{document}

A: First I moved 1.5cm to the right to avoid the voltage label.  Since components are centered relative to the end point for to[] one should skip over the interval between the two leads.  The (AA |- BB) notation locates the point where (AA) up/down intersects (BB) left/right.
I switched to standalone simply to avoid cropping the image.
\documentclass{standalone}
\usepackage[utf8]{inputenc}
\usepackage[siunitx,european,fetbodydiode,smartlabels]{circuitikz}
\usetikzlibrary{positioning}
\begin{document}

  \begin{circuitikz}
    \draw
    % top part of switch legs
    (0,0) coordinate[label=above:s1] (s1)
    to ++ (0,-0.4)
    node (mosfet1) [nigfete,below,anchor=D] {$Q_1$}
    (mosfet1) node (mosfet3) [nigfete,right=22mm]     {$Q_3$}
    (mosfet1.S) to [short,-*] ++ (0,-0.4)           coordinate[label=above:t1] (t1)

    % transformer       (t1 -| mosfet3.S) % Connect Q1 with Q3S which is electrically wrong, but easier to draw
    node (T) [transformer core,below right=0mm and 11mm]{}

    % bottom part of switch legs
    (mosfet3.S |- T.A2)                             coordinate (t2)  % likewase counter intuitive
    to ++ (0,-0.4)
    node (mosfet4) [nigfete,below,anchor=D] {$Q_4$}
    (t1 |- mosfet4.D)   node (mosfet2) [nigfete,below,anchor=D] {$Q_2$}

    % connection lines origins at transformer
    (T.A1) to                       (t1)
    (T.A2) to [short,-*]            (t2)
    (T.B1) to [short,-o]                ++ (0.5,0)  coordinate (t3)
    (T.B2) to [short,-o]                ++ (0.5,0)  coordinate (t4)
    (t3)   to[open, v^=$v_o(t)$]    (t4)

    % connection lines orign at mosfet
    (t1)        to      (mosfet2.D)
    (mosfet2.S) to ++   (0,-0.4)                    coordinate[label=below:s2] (s2)
    (mosfet3.D) to ++   (0, 0.4)                    coordinate[label=above:s3] (s3)
    (mosfet3.S) to      (mosfet4.D)
    (mosfet4.S) to ++   (0,-0.4)                    coordinate (s4)

    % supply lines
    (s3) -- (s1) to [short,*-o] ++ (-2,0)           coordinate (s+) % added *-o, * to get dot at S1
    (s4) -- (s2) to [short,*-o] ++ (-2,0)           coordinate (s-) % added *-o, * to get dot at S2
    (s+) to [open, v=60<\volt>, invert] (s-)

    % secondary side
   % secondary side
(t3) to[short,-*] ++(1.5,0) coordinate (AA)
(t4) to[short,-*] ++(2.5,0) coordinate (BB)
(AA) to [Do] ++(0,1.5) to[short,-*] ++(1,0) coordinate (CC)
(AA) -- (AA |- BB) to [Do,invert] ++(0,-1.5) to[short,-*] ++(1,0) coordinate (DD)
(BB) -- (BB |- AA) to [Do] (CC)
(BB) to [Do,invert] (DD)
 ;
\end{circuitikz}
\end{document}

A: let me continue where i stop in answer on your previous question:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[siunitx,european,fetbodydiode]{circuitikz}
\usetikzlibrary{positioning}

\begin{document}
\begin{figure}
\begin{circuitikz}[
lbl/.style = {label={[label distance=4mm]above right:#1}} % <-- added
                    ]
    \draw
    % top part of switch legs
    (0,0)                                           coordinate (s1)
                        to              ++ (0,-0.4)
                        node (mosfet1) [nigfete,below,anchor=D,lbl=$Q_1$] {}
    (mosfet1)           node (mosfet3) [nigfete,right=12mm,lbl=$Q_3$]     {}
    (mosfet1.S)         to [short,-*]   ++ (0,-0.4) coordinate (t1)
    % transformer
    (t1 -| mosfet3.S)   node (T) [transformer core,below right=0mm and 5mm]{}
    % bottom part of switch legs
    (mosfet3.S |- T.A2)                             coordinate (t2)
                        to              ++ (0,-0.4)
                        node (mosfet4) [nigfete,below,anchor=D,lbl=$Q_4$] {}
    (t1 |- mosfet4.D)   node (mosfet2) [nigfete,below,anchor=D,lbl=$Q_2$] {}
    % connection lines origins at transformer
    (T.A1) to                       (t1)
    (T.A2) to [short,-*]            (t2)
    (T.B1) to [short,-o]                ++ (0.1,0)  coordinate (t3)
    (T.B2) to [short,-o]                ++ (0.1,0)  coordinate (t4)
    (t3)   to[open, v^=$v_o(t)$]    (t4)
    % connection lines orign at mosfet
    (t1)        to      (mosfet2.D)
    (mosfet2.S) to ++   (0,-0.4)                    coordinate (s2)
    (mosfet3.D) to ++   (0, 0.4)                    coordinate (s3)
    (mosfet3.S) to      (mosfet4.D)
    (mosfet4.S) to ++   (0,-0.4)                    coordinate (s4)
    % supply lines
    (s3) -- (s1) to [short,-o]          ++ (-2,0)   coordinate (s+)
    (s4) -- (s2) to [short,-o]          ++ (-2,0)   coordinate (s-)
    (s+) to [open, v^=60<\volt>]           (s-)
    % rectifier (on secundar side of transormer)
    (t3) to [short, -*]  ++ (1.5,0)                 coordinate (t5)
    (t4) to [short, -*]  ++ (2.5,0)                 coordinate (t6)
    (mosfet4.S -| t5)   to [Do,l=$D2$]      (t5 |- t6)
         -- (t5)        to [Do,l=$D1$]      (mosfet3.D -| t5)
    (mosfet4.S -| t6)   to [Do,l_=$D4$]     (t6)
         -- (t6 |- t5)  to [Do,l_=$D3$]     (mosfet3.D -| t6)
    % rectifier conection and output lines
    (mosfet4.S -| t5)   to [short,-*]       (mosfet4.S -| t6)
                        to [short,-o] ++ (1,0)
    (mosfet3.D -| t5)   to [short,-*]       (mosfet3.D -| t6)
                        to [short,-o] ++ (1,0)
      ;
\end{circuitikz}
  \caption[Ersatzschaltbild]{Ersatzschaltbild}
  \label{fig:ersatzschaltbild}
\end{figure}
\end{document}

edit:
naming of of transistors (mosfet) in my previous answer as here in the first version of answer not allow to simle adjustify distance between element symbol and its name. better is add their names as labels with appropriate label distance.
for shorter code i define (in edited answer) new style `lbl7 and define it as:
lbl/.style = {label={[label distance=4mm]above right:#1}}

its use is:
node (mosfet1) [nigfete,below,anchor=D,lbl=$Q_1$] {}


Q: material-ui component style customization – change color of select component to white I want to use a dropdown menu of the material-ui components (see https://material-ui.com/components/selects/). Therefore, I copied the specific component out of the example:
Component
return

<FormControl variant="outlined" className={classes.root}>
  <InputLabel ref={inputLabel} id="demo-simple-select-outlined-label">
    Plan
  </InputLabel>
  <Select
    labelId="demo-simple-select-outlined-label"
    id="demo-simple-select-outlined"
    value={age}
    onChange={handleChange}
    labelWidth={labelWidth}

  >
    <MenuItem value="">
      None
    </MenuItem>
    <MenuItem value={10}>dsnfsdjfnsduifn</MenuItem>
    <MenuItem value={20}>Twenty</MenuItem>
    <MenuItem value={30}>Thirty</MenuItem>
  </Select>
</FormControl>

Style
const useStyles = makeStyles(theme => ({
root: {
  margin: theme.spacing(1),
  minWidth: 120,
  color: 'white',
  borderColor: 'white'
},}));

Because of my app design, I want to change the color of this dropdown menu to white. At the moment the component looks like this:

As you can see in the component, the variant is outlined. As I understand the documentation (https://material-ui.com/api/select/)  I have to overwrite the .MuiSelect-outlined class but I am not sure how I can do this. Unfortunately, the manual only describes the style of simple buttons and not how I can change the style of more complex components like these.
I hope someone can give me an example how I can change the color of the outline, the text and the arrow to white.

A: There you go
.MuiOutlinedInput-notchedOutline {
    border-color: #fff;//for border color
}
 .MuiSelect-icon {
    color: #fff;// for icon drop down icon color
}
.MuiInputLabel-root {
    color: #fff;// for lable color
}

For focus just add the parent .Mui-focused selector on these

A: const useStyles = makeStyles(theme => ({
select: {
  borderColor: 'white'
},
fomrControl{
  margin: theme.spacing(1),
  minWidth: 120,
  color: 'white',
}
}));


Q: Using a DocumentTermMatrix with a neural net classifier to make predictions in R I have been trying to learn how to use a DocumentTermMatrix to make predictions in R.
I have been using the following link as a reference to try and make predictions for a different dataset.
https://rpubs.com/cen0te/naivebayes-sentimentpolarity
Here, the author uses an IMDB movie review dataset where the review text is analysed. Predictions are then made based on the review text as to whether the review is positive or negative using the Naive Bayes classifier (from e1071). The dataset contains a separate column with yes/no values where if a review was positive, the value is 'yes' else it is 'no'.
I have successfully implemented this for the naive bayes classifier on a different dataset however I now want to use different classifiers to do this so I can compare their performance.
I have been trying to use the neural net classifier (from the neuralnet package) however I do not know where to begin.
For the naive bayes classifier the following code was used to make predictions:
classifier <- naiveBayes(train_DocumentTermMatrix, input_training_data$class, laplace = 1)
pred <- predict(classifier, test_DocumentTermMatrix)

For the neural net package, I require a formula to run the classifier however I want to make predictions based on the document term matrix so I am confused as to what the formula is.
Could somebody please point me to the right direction and tell me how to proceed with this?


Q: How to run 2 functions simultaneously in vuejs I wanted to run 2 functions simultaneously in VUE. One function will be called when component is mounted and it will be running every 10 seconds. The other function will start executing when we click on the button.
Now my problem is when I click the button the function start executing and the first function will not be called till this function completed its execution.
<template>
  <div>
    <select v-model="file_id" class="form-control" id="">
      <option v-for="(file, index) in files" :value="file.value" :key="index">
        {{ file.label }}
      </option>
    </select>
    <button class="btn btn-success" @click="handleFileUpload">Import</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      files: [],
    };
  },
  mounted() {
    this.upload_status = setInterval(() => {
      this.getUploadedStatus();
    }, 5000);
  },
  methods: {
    handleFileUpload() {
       //it will start executing when we click the button (need to call API)
       axios.post();
    },
    getUploadedStatus() {
        //it has to run every 10 seconds (Need to call API)
        axios.get();
    },
    beforeDestroy() {
      clearInterval(this.upload_status);
    },
  },
};
</script>


Q: Can I play an audio (or audio/video) file from a DLL written in C++? We want to play audio (and video) files from a DLL.  RenderSharedEvent/TimerDriven works, but for a number of reasons we prefer to do playback at a higher level- Media Foundation, or even the deprecated MediaPlay or waveOut functions would work.  However, so far I'm not seeing the callbacks, and they seem to be a critical part of the process.
Is that because they don't work from a DLL, or is there something I'm missing?  I remember it used to be impossible to use waveOut from a DLL, but I assumed the new frameworks would support a DLL.


Q: Problem extracting Youtube search results I am new to Python and have learned basis of Web Scraping with bs4. here i tried to extract all the links of Youtube search results , it doesn't work like on other sites. i analyzed the search result html data and the links of search results were in anchor tag with id "video title" , but the tag doesn't appear in my bs4 parsed html document
from bs4 import BeautifulSoup as bs
import requests
name=input("Enter video name ")
url='https://www.youtube.com/results?search_query='+name
searched=requests.get(url)
soup=bs(searched.text,'html.parser')
aid=soup.find_all('a',{'id':'video-title'})
print(aid)

i expect the output contain all the search result.
i have not learned other packages , i want to do this in bs4 if possible.

A: All this trouble to get YouTube search result data is just a waste of time and effort.
Why not try out these options

*

*YouTube Data API

*Selenium + Headless chrome
That being said, for the first 20 results, you can get the data from the JavaScript content in the source. The answer to that is given below.
After about 1 hr of making sense of the resulting json, it still fails for some queries.YouTube is a very complicated site. The response may vary based on location, browser, search query etc.
We are extracting the data from this script tag in the source.

Code:
from bs4 import BeautifulSoup as bs
import requests
import re
import json
headers={
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
}
name=input("Enter video name: ")
url='https://www.youtube.com/results?search_query=hello'+name
searched=requests.get(url,headers=headers)
soup=bs(searched.text,'html.parser')
aid=soup.find('script',string=re.compile('ytInitialData'))
extracted_josn_text=aid.text.split(';')[0].replace('window["ytInitialData"] =','').strip()
video_results=json.loads(extracted_josn_text)
#print(item_section=video_results["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][1])
item_section=video_results["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"]

for item in item_section:
    try:
        video_info=item["videoRenderer"]
        title=video_info["title"]["simpleText"]
        url=video_info["navigationEndpoint"]["commandMetadata"]["webCommandMetadata"]["url"]
        print('Title:',title)
        print('Url:',url, end="\n----------\n")
    except KeyError:
            pass

Output:
Enter video name: hello
Title: New Punjabi Songs 2017-Hello Hello(Ful Song)-Prince Narula-Yuvika Chaudhary-Latest Punjabi Song 2017
Url: /watch?v=mv326-zVpAQ
----------
Title: Alan Walker - The Spectre
Url: /watch?v=wJnBTPUQS5A
----------
Title: Hello Hello (Full HD) - Rajvir Jawanda | MixSingh | Josan Bros | New Punjabi Songs 2018
Url: /watch?v=xydupjQSj44
----------
Title: Bachchan - Hello Hello - Kannada Movie Full Song Video | Sudeep | Bhavana | V Harikrishna
Url: /watch?v=oLMMgoug4Uk
----------
Title: Hello Hello latest 2017 16 june punjabi song
Url: /watch?v=MqCSsPXw8QU
----------
Title:   Hello Hello   | + More Kids Songs | Super Simple Songs
Url: /watch?v=saDkICxEdgY
----------
Title: 'Gallan Goodiyaan' Full VIDEO Song | Dil Dhadakne Do | T-Series
Url: /watch?v=jCEdTq3j-0U
----------
Title: Hello Hello Gippy Grewal Feat. Dr. Zeus Full Song HD | Latest Punjabi Song 2013
Url: /watch?v=IRW2O4QZhgs
----------
Title: Hello Hello | Pataakha | Malaika Arora | Vishal Bhardwaj & Rekha Bhardwaj | Gulzar | Ganesh Acharya
Url: /watch?v=RxBAitQLSLA
----------
Title: Hello Hello (Lyrical Audio) Prince Narula ft. Yuvika Chaudhary | Punjabi Lyrical Audio 2017 | WHM
Url: /watch?v=v8VIsIvhDoQ
----------
Title: Hello Hello Full Video Song || Bhale Bhale Magadivoi || Nani, Lavanya Tripathi
Url: /watch?v=y3FI02OO_kU
----------
Title: Hello hello gaad bahe dhufee na egaa  (new comedy hhhhhh)
Url: /watch?v=DuRrcTo4rgg
----------
Title: Proper Patola - Official Video | Namaste England | Arjun | Parineeti | Badshah | Diljit | Aastha
Url: /watch?v=YmXJp4RtBCM
----------
Title: Official Video: Nikle Currant Song | Jassi Gill | Neha Kakkar | Sukh-E Muzical Doctorz | Jaani
Url: /watch?v=uBaqgt5V0mU
----------
Title: Insane (Full Song)  Sukhe - Jaani - Arvindr Khaira - White Hill Music - Latest Punjabi Song 2018
Url: /watch?v=mKpPhVVF8So
----------
Title: Radha bole HELLO HELLO-cartoon song mix with step up 2
Url: /watch?v=TFCTgNCzrck
----------
Title: Hello Song | CoCoMelon Nursery Rhymes & Kids Songs
Url: /watch?v=fxVMqaViVaA
----------
Title: Bachchan - Hello Hello Unplugged Version | Sudeep | Bhavana | V Harikrishna
Url: /watch?v=lvH3kTGJeEQ
----------
Title: Hello Hello! Can You Clap Your Hands? | Original  Kids Song | Super Simple Songs
Url: /watch?v=fN1Cyr0ZK9M
----------

One last thing that you can try out is to emulate the API used by youtube itself
ie. POST request to
https://www.youtube.com/results?search_query=yoursearchtext
It has a lot of cookie and session values being sent as parameters.  You may need to emulate all of them. You may need to use Requests session objects to do that.


Q: How to create pdf programmatically in specific format?
I have all the data in NSData object but I dont know how to create a pdf that will display in this format. The main problem is that product does not have a fixed content size, there will be more and more depending upon the customer, how much he/she purchases.
I don't want to make uiview like below format because if do so then how do captured entire uitableview in .png format.
Please give the logic how to create pdf for below format. Thanks a ton!

A: There are two ways to create PDFs in iOS:
If you want text in your PDF, you need to use Quartz 2D
There is no API that helps you to draw in tabular format. You need to draw lines, text by calculating x and y positions, all done manually. If you have fixed set of fields then only you can follow this approach.
Else, you can create a html page for your required format, and then set this page in PDF as an image, a very simple approach.
Both will be done using Quartz 2D
Hope this helps :)

A: Best place to start here and then here
need to draw a table with lines and add text and image to it also :)
For info refer
and docs

A: There are two ways to draw PDF.

*

*Using UIKit API:
For this your can draw pdf line by line & image by imagem i.e. Object by Object.
  Link to this is : http://www.raywenderlich.com/6581/how-to-create-a-pdf-with-quartz-2d-in-ios-5-tutorial-part-1

*Using Quartz 2D Api:
Using this You can draw pdf using the UIViews. Link for the same is:
http://mobile.tutsplus.com/tutorials/iphone/generating-pdf-documents/
http://www.ioslearner.com/generate-pdf-programmatically-iphoneipad/
The UIKit Api creates a nice clean & smooth PDF. While Quartz2D framework creates a little blur pdf. So you need to be sure before using it.
Let me know if it works or any issues.


Q: No matching constructor for initialization of "Type" I am writing a board game using C++ (with SFML2.2 library, Xcode 6.1.1). I created two classes: block and board. The idea is to create a 4x4 vector of blocks inside board. The codes are below:
In block.h
#ifndef __Game1024__block__
#define __Game1024__block__
#include <stdio.h>
#include <iostream>
#endif /* defined(__Game1024__block__) */

using namespace std;

class block{
public:
    sf::RectangleShape rect;
    sf::Text text;
    block();
    block(const int X,const int Y,const double size, const double blockSize, const double charSize, const int value, const sf::Color fillColor, const sf::Color textColor);
};

In block.cpp
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <string>
#include <sstream>
#include "block.h"

using namespace std;

block::block(){}

block::block(const int X,const int Y,const double size, const double blockSize, const double charSize, const int value, const sf::Color fillColor, const sf::Color textColor){

    double centerX = (X+0.5)*size;
    double centerY = (Y+0.5)*size;
    stringstream ss;
    ss << value;
    string sval = ss.str();

    rect.setSize(sf::Vector2f(blockSize,blockSize));
    rect.setOrigin(blockSize/2.0, blockSize/2.0);
    rect.setPosition(centerX, centerY);
    rect.setFillColor(fillColor);

    text.setStyle(sf::Text::Bold);
    text.setCharacterSize(charSize);
    text.setString(sval);
    text.setColor(textColor);
    text.setOrigin(text.getLocalBounds().width/2.0, text.getLocalBounds().height);
    text.setPosition(centerX, centerY);
 }

In board.h
#ifndef __Game1024__board__
#define __Game1024__board__
#include <stdio.h>
#endif /* defined(__Game1024__board__) */
#include <vector>
#include "block.h"
using namespace std;

class board{
private:
    int winSizeX;
    int winSizeY;
    int margin;
    double charSize;
public:
    vector<vector<block>> matrix;
    board();
    board(int winSizeX_,int winSizeY_,int margin_, double charSize_);
    void draw();
};

And in board.cpp
#include "board.h"
//#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include "block.h"
using namespace std;

board::board(){}

board::board(int winSizeX_,int winSizeY_,int margin_, double charSize_){
    winSizeX = winSizeX_;
    winSizeY = winSizeY_;
    margin = margin_;
    charSize = charSize_;
    matrix = vector<vector<block>>(4,vector<block>(4));

    double size = winSizeX/4.0; // = 256
    double blockSize = size - 2*margin;
    const sf::Color fillColor = sf::Color::Red;
    const sf::Color textColor = sf::Color::White;

    sf::Font font;
    if(!font.loadFromFile("./sansation.ttf")){
        exit(EXIT_FAILURE);
    };
    for (int i = 0; i < 4; ++i){
        for (int j = 0; j < 4; ++j){
            int value = 4*j + i + 1;
            matrix[i][j] = block(i,j,size,blockSize, charSize,value,fillColor,textColor);
            matrix[i][j].text.setFont(font);
            matrix[i][j].text.setOrigin(matrix[i][j].text.getLocalBounds().width/2.0,b[i][j].text.getLocalBounds().height);
        }
    }
}

The error comes from board.cpp
matrix[i][j] = block(i,j,size,blockSize, charSize,value,fillColor,textColor);

One weird thing is when I typed matrix[i][j] = block, the autofill of my IDE (Xcode) will generate
matrix[i][j] = block(<#const int X#>, <#const int Y#>, <#const double size#>, <#const double blockSize#>, <#const double charSize#>, <#const int value#>, <#const int fillColor#>, <#const int textColor#>)

The last two arguments of constructor block are changed from type sf::Color into int.
If I create a 4x4 vector of blocks in the main.cpp file and call the constructor of block, there is no error...
Any help?
Thanks in advance!
[Update] I attached the scrrenshot of the error message

A: Thanks @molbdnilo
I made a stupid mistake that I forgot to include the SFML header in "block.h"
#include <SFML/Graphics.hpp>

Now problem solved! Thanks for all advices. I am new to C++ projects, please feel free to speak out all my bad practices in the code. Very helpful!


Q: find the range $(x_{1}+x_{2}+\cdots+x_{2009})^2=4(x_{1}x_{2}+x_{2}x_{3}+\cdots+x_{2009}x_{1})^2$ let $x_{i}\ge 0(i=1,2,3,\cdots,2009$,and such $$(x_{1}+x_{2}+\cdots+x_{2009})^2=4(x_{1}x_{2}+x_{2}x_{3}+\cdots+x_{2009}x_{1})=4$$
find the range  $\sum_{i=1}^{2009}x^2_{i}$
I guess the range is $[1.5,2]$
because I think when $x_{1}=1,x_{2}=1,x_{3}=x_{4}=\cdots=x_{2009}=0$then is maximum of value $2$
and when $x_{1}=0.5,x_{2}=1,x_{3}=0.5,x_{4}=\cdots=x_{2009}=0$ is minmum of the value  $1.5$

A: I think you are right!
We'll prove that
$$(x_1+x_2+...+x_{2009})^2\geq4(x_1x_2+x_2x_3+...+x_{2009}x_1)$$ for all non-negatives $x_i$.
Indeed, let $x_2=\max\limits_{i}\{x_i\}$.
Thus, $$x_2x_{2009}\geq x_1x_{2009}$$ and by AM-GM we obtain:
$$4(x_1x_2+x_2x_3+...+x_{2009}x_1)\leq4(x_1+x_3+...+x_{2009})(x_2+x_4+...+x_{2008})\leq\left(\sum\limits_{i=1}^{2009}x_i\right)^2,$$
where the equality occurs for
$$x_1(x_4+x_6+...+x_{2008})=0,$$
$$x_2(x_5+...+x_{2007})=0,$$ which gives
$$x_5=...=x_{2007}=0.$$
Now, if $x_1=0$ then $x_2x_3=1,$ which gives
$$2=\sum_{i=1}^{2009}x_i\geq x_2+x_{3}\geq2\sqrt{x_2x_{3}}=2,$$
which gives $x_2=x_{3}=1$, $x_1=x_4=...=x_{2009}=0$ and  $\sum\limits_{i=1}^{2009}x_i^2=2$.
If $x_1>0$ we obtain:
$$x_1(x_4+...+x_{2008})=0,$$
which gives $x_4=x_5=...=x_{2008}=0.$
Now, let $x_2=a$, $x_1=b$,$x_3=c$ and $x_{2009}=d$.
Thus, $$(a+b+c+d)^2=4(ab+bd+ca)=4,$$
which gives $a+b+c+d=2$ and $ab+bd+ca=1.$
Thus,  by AM-GM  $$1=ab+bd+ca=ab+bd+dc+ca-dc=(a+d)(b+c)-dc\leq$$
$$\leq\left(\frac{a+b+c+d}{2}\right)^2-dc=1-dc\leq1,$$
which gives $dc=0$ and $a+d=b+c=1.$
Now, let $c=0$.
Thus, $b=1=a+d$ and since $a\geq b$, we obtain $d=0$ and $\sum\limits_{i=1}^{2009}x_i^2=2$ again.
Let $d=0$.
Id est, by C-S
$$\sum_{i=1}^{2009}x_i^2=a^2+b^2+c^2=1+\frac{1}{2}(1+1)(b^2+c^2)\geq1+\frac{1}{2}(b+c)^2=1.5.$$
The equality occurs for $a=1$ and $b=c=\frac{1}{2},$ which says that we got a minimal value.
Also, $$\sum_{i=1}^{2009}x_i^2=a^2+b^2+c^2=1+(b+c)^2-2bc\leq1+(b+c)^2=2.$$
The equality occurs for $a=b=1$ and $c=0,$ which says that we got a maximal value.

A: Solution
We are to state a lemma, on which the whole thing is based.

Lemma
Let $n > 4$ and $x_0,x_1,\ldots,x_n,x_{n+1}$ be non-negative real
  numbers, with $x_0=x_n$ and $x_{n+1} = x_1$. Then $$\left (\sum_{i=1}^n x_i \right )^2 \geq 4\sum_{i=1}^n
x_{i}x_{i+1},$$
  with the equality holding if and only if, for any $j~~ (1\leq j\leq n)$ we have$$x_j =\dfrac {1}{2} \sum\limits_{i=1}^n x_i = x_{j-1}+x_{j+1}$$ and the rest
  of the variables are equal to $0$.

Come back to the present case. Since $n=2009> 4$,  $\sum\limits_{i=1}^n x_i = 2$ and $\sum\limits_{i=1}^n x_{i}x_{i+1} = 1$, thus the equality holds. Therefore, for any $j~~~(1 \leq j \leq 2009)$, we have $x_j=1$,$x_{j-1}+x_{j+1}=1,$ and the rest are equal to $0$.
Under these constraints, we obtain $$S = \sum_{i=1}^n x_i^2 = x_j^2 + x_{j-1}^2 + x_{j+1}^2 =1 + x_{j-1}^2 + x_{j+1}^2,$$ where $x_{j-1}, x_{j+1} \geq 0$ and $x_{j-1}+x_{j+1}= 1$. Thus, $\dfrac {1}{2} \leq x_{j-1}^2 + x_{j+1}^2 \leq 1$, therefore $$\dfrac {3}{2} \leq S \leq 2.$$


Q: Access to object in module Im doing some logic which parse json data to object and I want to expose in some module specific object outside that other module can use,
I try with the following which doesnt work,any other idea?
var jsonObject;

module.exports = {

    parse: function () {
    //here I do the parsing
    ....

    jsonObject = JSON.parse(res)

    ,
    //here I want to expose it outside
    jsonObj:jsonObject
    }

A: If you are trying to expose the entire object, you build it like you would any other JavaScript object and then use module.exports at the end :
MyObj = function(){
   this.somevar = 1234;
   this.subfunction1 = function(){};
}
module.exports = MyObj;

If you just want to expose certain functions, you don't NEED to build it like an object, and then you can export the individual functions :
var somevar = 1234;
subfunction1 = function(){};
nonExposedFunction = function(){};
module.exports = {
   subfunction1:subfunction1,
   somevar:somevar
};

A: you simply assign the result of JSON.parse to this.jsonObj:
module.exports = {
    parse: function (res) {
        this.jsonObj = JSON.parse(res);
    }
};

Using this.jsonObj you are exposing the JSON object to the outside and you can use your module in this way:
var parser = require('./parser.js'),
    jsonString = // You JSON string to parse...

parser.parse(jsonString);
console.log(parser.jsonObj);


Q: Setting CSS classes with current_user I'm having trouble arriving at an approach to this problem. tl;dr I want to be able to set the css class of an li to the name of the current_user that posted the chat. Then based on that class, I'll apply different styling.
This is for a chat window and I want all the current users messages to display on one side and I want all other messages to display on the other side with a different color, etc.
I have a file.js.coffee that basically reads in some user input and apends it to an ordered list and adds some elements and classes along the way
      projectRef.on "child_added", (snapshot) ->
        message = snapshot.val()
        $("
").append($("
").append($("
").text(message.text))).prepend($("").text(message.name + ": ")).appendTo $("#messagesDiv")
        $("#messagesDiv")[0].scrollTop = $("#messagesDiv")[0].scrollHeight

      $("#messageInput").keypress (e) ->
        if e.keyCode is 13
          text = $("#messageInput").val()
          projectRef.push
            name: userName
            text: text
          $("#messageInput").val ""

The above would yield something like this in the browser

 User :

My chatt message from file.js.coffee!!

That 'self' class in the li is what I have been trying to dynamically set based on the current_user. So I have 2 issues - 1. I'm trying to figure out who posted the li and 2. I'm trying to dynamically set the class of that li based on the user that chatted/posted it.
My thinking was something along the lines of in the file.js.coffee use JQuery to grab that li and add the <%= current_user.name %> as a class then I could have a file.js.erb where I would do something like
<% unless $('li').hasClass('<%= current_user.name %>'); %>
    <%= $('li').toggleClass('others') %>
<% end %>

This way it checks if the class of the target li is from the current user and if it is keep the css class as self if not toggle it to others. Then I could style the classes appropriately (left, right, background-color:blue;, etc).
Is there a more correct way to approach this problem given what I am trying to accomplish? I think so..

A: It seems like you are saying you're trying to assign a class as the current user's name.
I'm wondering if going that far is necessary.
Assigning the list element with a class named "current_user" might be enough, then have separate CSS to control anything with class named "current_user".
Here's an example fiddle.
CSS
li {
    list-style:none;
    clear:both;

    float:right;
    text-align:right;
    background-color:#A7A2A0;
    border:1px solid #EEE;
    width:200px;
    margin:10px;
    padding:5px;
}
li.current_user {
    float:left;
    text-align:left;
    background-color:#24887F;
}

HTML

    Current User:

My message!

    All Other Users:

Other person's smessage.

UPDATE:
Looking at the firebase example I altered it to add a class "current_user" if the username matched the the name of the user that wrote the message. Below is the part of the code that I altered in the "displayChatMessage" function, I also added CSS to the head section for the "current_user" class.
Here's a link to the working example, view it in to different web browsers using different usernames at the same time to see.
function displayChatMessage(name, text) {
  if(name == $('#nameInput').val()){
    $('
').text(text).prepend($('').text(name+': ')).appendTo($('#messagesDiv')).addClass('current_user');
    $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
  }
  else{
    $('
').text(text).prepend($('').text(name+': ')).appendTo($('#messagesDiv'));
    $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
  }
};

This is the CSS I added to the head.

A: There are many users using the app concurrently. But for every user, there is only one current_user in session. Don't mix it up.
Since the message is to be processed by server, you can easily add a new attribute of message.klass in server side by judging the message comes from current_user. If it is, the class may be current, else blank or others.
Then, in JS
$('li').addClass('<%= message.klass %>')


Q: Ponteiro de struct em C O que acontece é o seguinte, dentro da função ins_ult() eu consigo alterar o valor de root->data, mas fora da função o valor permanece NULL.
Estou passando o parametro de forma errada ou usando o malloc incorretamente?
#include<stdlib.h>
#include<stdio.h>
typedef struct Node_t{
        void *data;
        struct Node_t *next;
}Node;
int main(){
        Node *root;
        root=NULL;
        ins_ult(root,100);
        printf("%d,%d\n",root->data);
}
void ins_ult(Node *root, void *data){
        if(root == NULL){
                root = malloc(sizeof(Node));
                root->data = data;
                root->next = 0;
                printf("%d\n",root->data);
        }
}

A: Voce nao altera root na funcao. Voce precisa que ela receba um ponteiro para um ponteiro do tipo Node para que o valor nao se perca depois que a funcao retorne.
Esse codigo:
#include<stdlib.h>
#include<stdio.h>

struct node{
  void *data;
  struct node *next;
};

void ins_ult(struct node **root, void *data){
  if(*root == NULL){
    *root = (struct node *)malloc(sizeof(struct node *));
    (*root)->data = data;
    (*root)->next = 0;
    printf("%d\n", (*root)->data);
  }
}

int main(){
  struct node *root;
  root=NULL;
  ins_ult(&root, 100);
  printf("%d\n", root->data);
  return 0;
}

vai imprimir 100 duas vezes na tela.


Q: Meteor: change a user password WITHOUT logout? Accounts.setPassword(userId, password);
Before Meteor v1.0.2, the user was not logout when calling this function.
Since v1.0.2, I quote from https://github.com/meteor/meteor/blob/devel/History.md, "Expire a user's password reset and login tokens in all circumstances when their password is changed".
I don't know the reason of this change,but the fact is that function above logout the user.
Is there a way, with v1.0.2, to change a user password without logout the user?
If not, how do I downgrade the package account-base so the behaviour is like before?
Thanks.

A: The above answer is correct and here's the exact copy-paste code in case you're struggling:
Accounts.setPassword(userId, password, {logout: false});

Note: make sure you are doing this call server side.

A: Accounts.setPassword(userId, password, options)

This method now supports options parameter that includes options.logout option which could be used to prevent the current user's logout.

A: You could use Accounts.changePassword (docs) to change the password instead, this will not affect the user's existing tokens (as from) https://github.com/meteor/meteor/blob/devel/packages/accounts-password/password_server.js#L299-L302
If you want to do this from the server without knowing the existing password you would have to fork the accounts-password package and remove this line: https://github.com/meteor/meteor/blob/devel/packages/accounts-password/password_server.js#L338 and add this package into the /packages directory of your app
If you want to downgrade your package (so long as the version you're using of meteor supports it):
meteor remove accounts-password
meteor add accounts-password@1.0.3


Q: Why am I getting error: initializing argument 1 of 'Item::Item(int)' [-fpermissive] in Eclipse when I try to compile my C++ code? I'm new to C++, and have finally given up on trying to get this to compile after staring at it for too long. The compiler seems to be rejecting the constructor prototype in the header file for some reason... I can't figure out what's wrong with it.
Item.h:
#ifndef ITEM_H_
#define ITEM_H_

class Item {
public:
    Item(int); //This line is what Eclipse keeps flagging up with the error in the title
    virtual ~Item();
    Item* getNextPtr();
    int getValue();
    void setNextPtr(Item *);
};

#endif /* ITEM_H_ */

In my Item.cpp file I have:
int val;
Item* nextPtr = 0;
Item::Item(int value) {
    val = value;
}

Item* Item::getNextPtr() {
    return nextPtr;
}

void Item::setNextPtr(Item *nextItem) {
    nextPtr = nextItem;
}

int Item::getValue() {
    return val;
}

Item::~Item() {
    // TODO Auto-generated destructor stub
}

Oops, I'm using GCC. And yeah, they should have been member variables! How do I go about doing that using this format? The code where I use instantiate Item is below. I am aware that there should be no global variables in that either...
#include "LinkList.h"
#include "Item.h"

Item* first = 0;
int length = 0;

LinkList::LinkList(int values[], int size) {
    length = size;
    if (length > 0) {
        Item firstItem = new Item(values[0]);
        Item *prev = &firstItem;
        first = &firstItem;
        for (int i = 0; i < size; i++) {
            Item it = new Item(values[i]);
            prev->setNextPtr(&it);          //set 'next' pointer of previous item to current item
            prev =                      // set the current item as the new previous item
        }

    }
}

LinkList::~LinkList() {
    for (int i = 0; i < length; i++) {
        Item firstItem = *first;
        Item *newFirst = firstItem.getNextPtr();
        delete(first);
        first = newFirst;
    }
}

int LinkList::pop() {
    Item firstItem = *first;
    first = firstItem.getNextPtr();
    return firstItem.getValue();
}

I've just noticed a bug with the functionality of the pop() and destructor functions... please ignore those, I just want to figure out what's wrong with the instantiation of Item.
GCC error:
Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\LinkList.o" "..\\src\\LinkList.cpp"
..\src\LinkList.cpp: In constructor 'LinkList::LinkList(int*, int)':
..\src\LinkList.cpp:16:38: error: invalid conversion from 'Item*' to 'int' [-fpermissive]
..\src\/Item.h:14:2: error:   initializing argument 1 of 'Item::Item(int)' [-fpermissive]
..\src\LinkList.cpp:20:32: error: invalid conversion from 'Item*' to 'int' [-fpermissive]
..\src\/Item.h:14:2: error:   initializing argument 1 of 'Item::Item(int)' [-fpermissive]

21:24:26 Build Finished (took 256ms)

A: Here:
Item firstItem = new Item(values[0]);

You are creating a new Item with an item pointer as its argument. This is the same as:
Item firstItem(new Item(values[0]));

And it should be:
Item *firstItem = new Item(values[0]);


Q: why my custom tld not accessible from /WEB-INF/lib/ In my web application I'd placed my custom.tld file in /WEB-INF/lib/custom.tld and referenced in my web.xml as
<jsp-config>
    <taglib>
        <taglib-uri>customTldUri</taglib-uri>
        <taglib-location>/WEB-INF/lib/custom.tld</taglib-location>
    </taglib>
</jsp-config>

and if I do add taglib in jsp then I'm getting JasperException for not able to find/add referenced tld.
But if I do move the custom.tld to /WEB-INF/custom.tld and update the web.xml to <taglib-location>/WEB-INF/custom.tld</taglib-location> then it works.
But in the same project I do have struts tld files added in /WEB-INF/lib/struts-*.tld and there is not exception for them.
My question is why my custom.tld is not accessible if I do place it in /WEB-INF/lib/ while the strtus tlds are working fine?


Q: Copy from HTML div without copying the formatting style I have a div which has a bunch of styling (font-family, font-size, background-color, etc.) and I'd like to be able to copy text from it, and paste it into a rich text editor (Google Docs or Gmail for eg.) without it pasting the styles.
I know I can use the "paste without formatting" or equivalent option, but I'd like to know if there's a clean way to disable copying the formatting at all on the webpage itself, because I only care about the text.
To test: run this snippet, copy the styled text, and paste it into a google doc.

<div style="background-color: orange">
Copy me!
</div>


Q: Scala / Spray: Return all rejections as JSON I'm writing a JSON API using Spray 1.2.1 and I would like to return all HTTP Responses in the following format by default.
{
"type":"error",
"status":404,
"message":"Not Found"
}
My own custom rejections / exceptions will have less generic content in the 'message' field, but I'm looking for a way of globally formatting (and possibly otherwise decorating, for debug/testing) all non-2xx responses.
Is this possible without handling every possible rejection and status code?
Thanks!
Sam

A: I don't know if this is generic enough for you but here's how I do something similar:
import spray.json.DefaultJsonProtocol

case class Rejection(type:String, status: Int, message: String)

object RejectionJsonProtocol extends DefaultJsonProtocol{
   implicit val rejectionFormat = jsonFormat3(Rejection)
}

Then you can complete your routes with a Rejection, possibly in your RouteExceptionHandler like this:
trait RouteExceptionHandlers extends HttpService {

  import RejectionJsonProtocol._

  implicit def routeExceptionHandler(implicit log: LoggingContext) = ExceptionHandler {
    case e: UnsuccessfulResponseException =>
      requestUri { uri =>
        complete(e.response.status, Rejection("error",e.response.status,"Not found"))
      }
  }
    //other exceptions go here
}


Q: CLion doesn't sort include statements on commit I'm using clang-format to define rules for sorting my include statements. This works perfectly when using the "Code > Reformat Code" button or pressing CTRL + ALT + L within a file.
However, even when setting the "Reformat code" checkbox in the CLion commit dialog, the include statements don't get sorted when commiting. For some reason other formatting tasks (such as fixing indentation) take place when commiting. It's just the include sorting that's missing.
Does anybody know why that is the case? Many thanks!
From the .clang-format file:
IncludeCategories:
  - Regex: '^<.*\.h>'
    Priority: 1
  - Regex: '^<[^.]*>'
    Priority: 2
  - Regex: '<.*>'
    Priority: 3
  - Regex: '.*'
    Priority: 3
IncludeBlocks: Regroup
SortIncludes: true

A: JetBrains Support confirmed to be that this is a bug within CLion that they managed to reproduce on their system.
Hoping for it to be fixed in a future version :)


Q: Функция mail() и IE: не появляется письмо на почте php-функция mail() работает во всех браузерах, а в IE8 функция срабатывает без выдачи ошибок, но на почте отправленное письмо не появляется. Что за баг?
A: IE8 здесь совершенно не при чем. Функции mail() абсолютно все равно с какого браузера вы вызвали обработку вашего php скрипта, это php скрипт все равно выполняет интерпретатор php.
Возможно письмо не доходит на сервер из-за неправильного header'a или из-за того, что ваш сервер не является доверенным или из-за того, что ваше письмо показалось спамом.
Есть уйма вариантов. Еще можете в логах посмотреть. Может там что-то важное пишется по этому поводу.


Q: Is possible to make screen shot in ipad programmatically?
Possible Duplicate:
screenshots programmatically in IPad with the image name

Is possible to make screenshot programmatically like this?

I want to be able to take screenshots of the current screen, which is not necessarily my app, i.e., my app may be in the background when activated. You might think of it as programatically pressing the home and sleep button at the same time.
I am aware that this will be limited to jailbroken devices.


Q: Assigning id to validation message I am trying to assign id to span where validation message is dynamically shown. Am I doing some thing wrong?
 <div>@Html.ValidationMessageFor(model => model.Title,new{id="prjTitle"})</div>

It throws Argument type is not assignable to parameter string

A: just use the correct overload:
 @Html.ValidationMessageFor(model => model.YourProperty, "", new { @class = "a-class-if-you-want-one", id = "yourId" })

A: There is no overload that takes only the linq expression and an html attributes object.
According to MSDN there is an overload that takes a linq expression, an errormessage (string) AND an html attributes object, like this:
@Html.ValidationMessageFor(model => model.Title,"entry invalid",new{id="prjTitle"})

A: public static MvcHtmlString IDValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string id)
    {
        var validationString = Regex.Replace(htmlHelper.ValidationMessageFor(expression).ToString(), @"^data-valmsg-for=""*\""$", String.Format("data-valmsg-for=\"{0}\"", id));

        return MvcHtmlString.Create(validationString);
    }


Q: Jenkins and local PyCharm running tests using different path I am checking out a project from git repo. The project was run on Jenkins. One of the unit tests file is reading the file with filename:
filename = os.path.join(self.config_dir, name, 'my_parameters.json')

This works fine on Jenkins, but failed to work on my local machine using pyCharm. On the local machine, I have to change the filename to:
filename = '../' + os.path.join(self.config_dir, name, 'my_parameters.json') to make the test works.
It seems that Jenkins and local pyCharm is running test files in different path. How do I resolve this issue to make the code running in both machines? Thank you!


Q: problem with mapping table in NHibernate I rewrite application from ASP.NET to Silverlight and use NHibernate 2.
Tables in my db looks like this:
alt text http://img268.imageshack.us/img268/4940/tablesqp.jpg
In Dziecko table I have reference to id of Opiekun and Grupy. In ASP it's ok for me but in videos Summer with NHibernate I see that Stephen Bohlen  in exchange use object of this type, for me its Opiekun and Grupy.But in SQL Server I can't define object type, so better is map only this id[will I could problem querying for id] and or something else ?? Using all object of specific type is efficiency? We must query all object in exchange only int type of id's ??

A: (I hope I've understood your question correctly.)
The relations in your database are always defined in database types, probably either an int or a uniqueidentifer in the case of foreign key columns. The database should know nothing of the data transfer objects NHibernate returns to your application code.
When you map the foreign key columns in your data transfer objects using ManyToOne, etc., you specify the type of the object because NHibernate knows that the relation is always going to be between the foreign key column you specify in the attribute, and the Id (primary key) of the object type to be returned. This saves you the trouble of doing extra queries to return parent or child entities -- NHibernate just does a JOIN for you automatically and returns the relational information as an object hierarchy, instead of just a set of id values.


Q: Multiline regular expressions with python requests module I am iterating over a web page line by line using requests, but trying to capture some multi-line regular expressions:
import requests

r = requests.get(url)

for line in r.iter_lines():
    pat = re.search(regex, line)
    if pat:
        print pat.group(1)

I have tried concatenating the whole file into one long string, but that seems wrong.
What is the best way to capture these multiline expressions (preferably using requests)?
Note: I am new to requests. I have looked at the docs but haven't found, or understood, the answer.
Thanks

A: r = requests.get(url)
pat = re.search(regex, r.text)


Q: Classroom.Courses.CourseWork.patch I am trying to update the "state" of an assignment within Google Classroom using Google Apps Script. The current state of the assingment is DRAFT.
I am trying in two different codes and get two different errors:
function publicarBorradores() {
      var courseId = "320315007220"
      var assingid = "320315007244"
      var newState = { "state":'PUBLISHED'}

     var patchDraft = Classroom.Courses.CourseWork.patch(newState,courseId,assingid);
     patchDraft.updateMask = newState;

or
      patchDraft.updateMask = 'state'
         }

I always get the same Error:
"GoogleJsonResponseException: API call to classroom.courses.courseWork.patch failed with error: updateMask: Update mask is required"
I also tried this other way:
function valoresDraft (){
     var courseId = "320315007220"
     var assingId = "320315007244"
     changeState(courseId,assingId);
    }

 function changeState(courseId,assingId) {
      var estado = {'state': "PUBLISHED",}
      const patchDraft = Classroom.Courses.CourseWork
      patchDraft.patch(estado, courseId, assID,{"updateMask":"state"});
  }

And I get a different error: "API call to classroom.courses.courseWork.patch failed with error: @ProjectPermissionDenied The Developer Console project is not permitted to make this request." which is strange as I am the owner of the class AND I have published via the same "Developer Console project" other publications within this same class. (The class was NOT created via API. I created it manually from within classroom.google.com)
Thanks

A: The are a few issues with your code:

*

*In the first example, the GoogleJsonResponseException: API call to classroom.courses.courseWork.patch failed with error: updateMask: Update mask is required" error you are receiving is due to the fact that you are not specifying the updateMask field before making the request.

So even though you added the patchDraft.updateMask = newState;  line, this won't help as it will be execute after the API call.

*The second example ends up executing properly because you supplied the updateMask field at the time of making the request.

However, since the class was created manually from the Classroom UI, this is the expected behavior, as the class is essentially not associated with any Developer Console Project.
According to the documentation:

ProjectPermissionDenied indicates that the request attempted to modify a resource associated with a different Developer Console project.
Possible Action: Indicate that your application cannot make the desired request. It can only be made by the Developer Console project of the OAuth client ID that created the resource.

What you can do in this situation is to create the class from the API and afterwards execute the patch call.
Reference

*

*Classroom API Access Errors.


Q: How can I return an object (ie. List) from an object mocked with NSubstitute? I am using NSubstitute to mock one of my classes/interfaces. One of the functions implemented by my class should return an object of type List.
But when I try to use _mockedObject.MyFunction().Returns(myList), it gives me an error saying I cannot convert between my List and an object of type Func.
I figured I could pass my list as a string using some ToString() function and convert it back? But that doesn't seem particularly clean as I'm expecting a list to come back from my function.
I saw from a video on Unit Testing with Dependency Injection that you can return objects from mocked objects with Moq (https://www.youtube.com/watch?v=DwbYxP-etMY). I am considering switching to that if I can't manage to return an object with NSubstitute.

A: Here is an example of how to return a List<string> from an object mocked by NSubstitute:
using System.Collections.Generic;
using NSubstitute;
using Xunit;

public interface ISomeType {
    List<string> MyFunction();
}

public class SampleFixture {
    [Fact]
    public void ReturnList() {
        var _mockedObject = Substitute.For<ISomeType>();
        var myList = new List<string> { "hello", "world" };

        _mockedObject.MyFunction().Returns(myList);

        // Checking MyFunction() now stubbed correctly:
        Assert.Equal(new List<string> { "hello", "world" }, _mockedObject.MyFunction());
    }
}

The error you have described sounds like there are different types involved. Hopefully the above example will help show the source of the problem, but if not please post an example of the _mockedObject interface and the test (as suggested in @jpgrassi's comment).


Q: Error while creating formula field There is  field : "Company Identifier "on  Company object. Which having lookup relation with Item Object.
Now i am creating formula field on Item object with the below condition
If Company identifier is equal to "SMI" then on the formula field it should update "SMC"
However, Company identifier is a Text field(External ID).
I created a formula using if condition but its showing me an error:
Error: Field SMI does not exist. Check spelling.
I am wondering if we can use CASE function ?

A: You will have to use quotes while making comparison in the formula. You must have used SMI directly without quotes which is why it is giving you that error.
Your formula should be like this
IF(Company__r.Company_Identifier__c='SMI', 'SMC','Other Value')


Q: MS Tests/ Moq - ExpectedException failing I'm trying to create unit test for one of my method using MS test and Moq. Below is my interface, implementation class and method.
public  interface IDocumentManagementHandler
    {
      Task AddData(long documentId, string metadataCategoryName, List<KeyValuePair<string, string>> metadata);
    }

public class DocumentManagementHandler : IDocumentManagementHandler
    {
        private readonly IService _service;
        private readonly IFService _fService;
        public readonly ILogger _logger;
        private static readonly long rootFolderId = 123456;

        public DocumentManagementHandler(IService Service, IFService FService, ILogger Logger)
        {
            _service = Service;
            _fService = FService;
            _logger = Logger;
        }

public Task AddData(long documentId, string metadataCategoryName, List<KeyValuePair<string, string>> metadata)
        {
            if(string.IsNullOrEmpty(metadataCategoryName))
                throw new ArgumentNullException(nameof(metadataCategoryName));

            if (metadata == null)
                throw new ArgumentNullException(nameof(metadata));

            return AddDocumentMetadataAsync(documentId, metadataCategoryName, metadata);
        }

My MSTest method
[TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void TestAddData()
        {
            long documentID = 123;
            string metadataCategoryName = null;
            List<KeyValuePair<string, string>> metadata = null;

            var documentHandler = new Mock<IDocumentManagementHandler>();
            documentHandler.Setup(s => s.AddData(documentID, metadataCategoryName, metadata));

            var newresult = documentHandler.Object.AddData(documentID, metadataCategoryName, metadata);

        }

I'm expecting the test method to pass when I pass the variable "metadataCategoryName" as NULL but test is failing with the message "Test method did not throw expected exception System.ArgumentNullException." .
Any idea what's wrong here.

A: Your issue: you are using a mock representing an interface of the object containing the method you want to test, which means your code is never really called (a breakpoint would have revealed this particular issue).
As for how you should have written your test :
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestAddData()
{
    long documentID = 123;
    string metadataCategoryName = null;
    List<KeyValuePair<string, string>> metadata = null;

    // Configure as needed using Mock.Get()
    var service = Mock.Of<IService>();
    var fService = Mock.Of<IFService>();
    var logger = Mock.Of<ILogger>();

    var documentHandler = new DocumentManagementHandler(service, fService, logger);

    documentHandler.AddData(documentID, metadataCategoryName, metadata);
}

Additionally, you might want to assert the data contained in your exception. E.g. To check that your ArgumentNullException is reporting the correct parameter name


Q: Make php date dropdown function 'sticky' Out of coffee and brain's given up...
...can anyone help to make this form date dropdown function retain selected month on $_POST ['submit'] or isset($missing) in the case of there being an error/missing field etc
 function createMonths($id='month_select', $selected=null)
{
    /*** array of months ***/
    $months = array(
            1=>'Jan',
            2=>'Feb',
            3=>'Mar',
            4=>'Apr',
            5=>'May',
            6=>'Jun',
            7=>'Jul',
            8=>'Aug',
            9=>'Sep',
            10=>'Oct',
            11=>'Nov',
            12=>'Dec');

    /*** current month ***/
    $selected = is_null($selected) ? date('m') : $selected;

    $select = '<select name="'.$id.'" id="'.$id.'">'."\n";
    foreach($months as $key=>$mon)
    {
        $select .= '<option value="'.str_pad($key, 2, "0", STR_PAD_LEFT).'"';
        $select .= ($key==$selected) ? ' selected="selected"' : '';
        $select .= ">$mon</option>\n";

    }
    $select .= '</select>';
    return $select;
}

A: In the event you have invalid form data, you should check if the $_POST['month_select'] variable is set and not empty and create your dropdown passing in it's value like so:
$selected = (!empty($_POST['month_select'])) ? $_POST['month_select'] : null;
createMonths('month_select', $selected);

function createMonths($id='month_select', $selected = null)
{
    /*** array of months ***/
    $months = array(
            '01'=>'Jan',
            '02'=>'Feb',
            '03'=>'Mar',
            '04'=>'Apr',
            '05'=>'May',
            '06'=>'Jun',
            '07'=>'Jul',
            '08'=>'Aug',
            '09'=>'Sep',
            '10'=>'Oct',
            '11'=>'Nov',
            '12'=>'Dec');

    /*** current month ***/
    $selected = is_null($selected) ? date('n') : $selected;

    $select = '<select name="'.$id.'" id="'.$id.'">'."\n";
    $select .= "<option value=""></option>\n";
    foreach($months as $key => $mon)
    {
        $select .= '<option value="'.$key.'"';
        $select .= ($key == $selected) ? ' selected="selected"' : '';
        $select .= ">$mon</option>\n";
    }
    $select .= '</select>';
    return $select;
}

I have also taken the liberty of fixing your createMonths() function by the recommendation regarding date('n') and changing your array keys to strings as this will avoid having to pad your months.


Q: ruby on rails - thin - HTTP GET URL > 1024 When I use an URL bigger than 1024 appear this in the console of the rails server.

Invalid request: HTTP element REQUEST_PATH is longer than the 1024 allowed length.
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/thin-1.6.1/lib/thin/request.rb:84:in `execute'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/thin-1.6.1/lib/thin/request.rb:84:in `parse'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/thin-1.6.1/lib/thin/connection.rb:41:in `receive_data'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run_machine'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/thin-1.6.1/lib/thin/backends/base.rb:73:in `start'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/thin-1.6.1/lib/thin/server.rb:162:in `start'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/rack-1.5.2/lib/rack/handler/thin.rb:16:in `run'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/rack-1.5.2/lib/rack/server.rb:264:in `start'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/railties-4.0.1/lib/rails/commands/server.rb:84:in `start'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/railties-4.0.1/lib/rails/commands.rb:76:in `block in <top (r
equired)>'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/railties-4.0.1/lib/rails/commands.rb:71:in `tap'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/railties-4.0.1/lib/rails/commands.rb:71:in `<top (required)>
'
        bin/rails:4:in `require'
        bin/rails:4:in `<main>'

Can I rescue this exception?


Q: QuantLib's HestonModelHelper class is throwing error I have below QuantLib model in python -
import QuantLib as ql
import pandas as pd
day_count = ql.Actual365Fixed()
calendar = ql.UnitedStates()
calculation_date = ql.Date(6, 11, 2015)
spot = ql.SimpleQuote(659.37)
risk_free_rate = ql.SimpleQuote(0.01)
dividend_rate = ql.SimpleQuote(0.0)

riskFreeCurve = ql.FlatForward(
                                calculation_date,
                                ql.QuoteHandle(risk_free_rate),
                                day_count
                            )
dividend_yield = ql.FlatForward(
                                calculation_date,
                                ql.QuoteHandle(dividend_rate),
                                day_count
                            )
yield_ts = ql.YieldTermStructureHandle(riskFreeCurve)
dividend_ts = ql.YieldTermStructureHandle(dividend_yield)
p = ql.Period(ql.Date(6,12,2015) - calculation_date, ql.Days)
s = 527.50
vols = 0.35
helper = ql.HestonModelHelper(
                                            p,
                                            calendar,
                                            ql.QuoteHandle(spot),
                                            ql.QuoteHandle(ql.SimpleQuote(s)),
                                            ql.QuoteHandle(ql.SimpleQuote(vols)),
                                            yield_ts,
                                            dividend_ts
                                        )

With above I got below error -
Traceback (most recent call last):
  File "<stdin>", line 8, in <module>
  File "/usr/local/lib/python2.7/dist-packages/QuantLib/QuantLib.py", line 9840, in __init__
    _QuantLib.HestonModelHelper_swiginit(self, _QuantLib.new_HestonModelHelper(*args))
TypeError: Wrong number or type of arguments for overloaded function 'new_HestonModelHelper'.
  Possible C/C++ prototypes are:
    HestonModelHelper::HestonModelHelper(Period const &,Calendar const &,Real const,Real const,Handle< Quote > const &,Handle< YieldTermStructure > const &,Handle< YieldTermStructure > const &,BlackCalibrationHelper::CalibrationErrorType)
    HestonModelHelper::HestonModelHelper(Period const &,Calendar const &,Real const,Real const,Handle< Quote > const &,Handle< YieldTermStructure > const &,Handle< YieldTermStructure > const &)

Any clue where my code went wrong will be highly helpful.
Thanks,

A: The problem is that the HestonModelHelper expects the type of the spot and the strike to be a float.
For it to work with minimal change, use:
helper = ql.HestonModelHelper(
                                            p,
                                            calendar,
                                            spot.value(),
                                            s,
                                            ql.QuoteHandle(ql.SimpleQuote(vols)),
                                            yield_ts,
                                            dividend_ts
                                        )


Q: Creating a Docker volume at a specific location Can I tell Docker to create a volume at a specific location on the host machine?
The host machine has some storage restrictions and I'd like the volume to be stored in /data instead of /var/lib/docker/vfs/dir/.
This isn't even mentioned in the documentation so I suspect I misunderstood something.

A: Do you want to use a  different directory than the default /var/lib/docker as Docker runtime? You can do this by starting docker daemon with -g option and path to the  directory of your choice. From the man page:
-g, --graph=""
     Path to use as the root of the Docker runtime. Default is /var/lib/docker.

A: When firing up your container with "docker run":
 docker run -v /data/some_directory:/mount/location/in/your/container your_docker_image

You cannot do this in the same way via Dockerfile because of portability.


Q: Is there a way I can specify a different repository for the CocoaPods master repo? At my work, we have a private cocoapods repository that we use to host whitelisted libraries for developers, and I am trying to validate a library I wrote.
Whenever i do a pod spec lint MYPODNAME --verbose, CocoaPods tries to validate my spec against the master repo instead of my private repo.
Is there any way to get around this behavior?
I have tried completely removing the master repo, but it still attempts to validate my pod's dependencies against master
EDIT: This issue seems to describe what I am experiencing.

A: Answering my own question. You have to manually specify the --sources for what CocoaPods will validate the spec against.
pod spec lint MYPODNAME --verbose --sources=git@<DOMAIN>:<REPO>.git


Q: how to access php variable out side of a foreach loop i have a veriable named (num) which is used for increments changes names of ids by 1 num+1 but in my foreachloop i cant access it .
i tried declaring it before the loop still doesnot work
<?php $num = 0; ?>
<?php foreach($listings as $list):?>

            <input type="checkbox" class="css-checkbox" value="<?php echo $list['title'];?>" id="visit<?php echo $num+1;?>" name="treatment<?php echo $num+1;?>">
            <label for="visit<?php echo $num+1;?>" class="css-label"><?php echo $list['title']?> <?php echo $list['price'];?>£

<?php endforeach;   ?>

<input type="hidden" value="<?php echo $num;?>" name="total"/>

i want the input ids to be incremented by 1 like treatment1,treatment2

A: You should increment the $num variable by doing $num++; once inside the loop, then print it where you need it with <?php echo $num; ?> without using <?php echo $num+1; ?> - as doing so will only increment it as you echo it - not add one to each iteration.
<?php
$num = 0;
foreach($listings as $list):
    $num++; // Increment $num for each iteration
    ?>

            <input type="checkbox" class="css-checkbox" value="<?php echo $list['title'];?>" id="visit<?php echo $num;?>" name="treatment<?php echo $num;?>">
            <label for="visit<?php echo $num;?>" class="css-label"><?php echo $list['title']?> <?php echo $list['price'];?>£

<?php endforeach; ?>

If your $listings is numeric indexed, you can use the key of each element in the array instead by doing
foreach($listings as $num=>$list):
    ?>

            <input type="checkbox" class="css-checkbox" value="<?php echo $list['title'];?>" id="visit<?php echo $num;?>" name="treatment<?php echo $num;?>">
            <label for="visit<?php echo $num;?>" class="css-label"><?php echo $list['title']?> <?php echo $list['price'];?>£

<?php endforeach; ?>

A: The problem is you did not set the value of $num variable you just only print or echo it inside the html tags. You need to add or increment the $num variable  inside the loop like this.
 <?php $num++; ?>

or
 <?php $num = $num+1; ?>


Q: Integration by parts: $\int e^{ax}\cos(bx)\,dx$ I need to evaluate the following function and then check my answer by taking the derivative:
$$\int e^{ax}\cos(bx)\,dx$$
where $a$ is any real number and $b$ is any positive real number.

I know that you set $u=\cos(bx)$  and $dv=e^{ax} dx$,
and the second time you need to integrate again you set $u=\sin(bx)$ and $dv=e^{ax}dx$ again.
It eventually simplifies down to
$$\int e^{ax}\cos(bx)dx = \frac{1}{a}e^{ax}\cos(bx) + \frac{b}{a}\left(\frac{1}{a}e^{ax}\sin(bx) - \frac{b}{a}\int e^{ax}\cos(bx)\,dx\right).$$
Now I know to move the integral on the left side to the right side so that I can just divide by the constant to solve.
Here is my problem:
I know I need to solve the right side to be:
$$\frac{e^{ax}\left(a\cos(bx) + b\sin(bx)\right)}{a^2+b^2} + C.$$
To divide by the constant, I multiplied everything on the right side by
$$\frac{a^2}{b^2+1}.$$
but this leads me to get $b^2 + 1$ on the bottom instead of $a^2 + b^2$.
I will show what I am doing in detail:
After setting the initial integral equal to:
$$\frac{1}{a}e^{ax}\cos(bx) + \frac{b}{a}\left(\frac{1}{a}e^{ax}\sin(bx) - \frac{b}{a}\int e^{ax}\cos(bx)\,dx\right) + C$$
I simplify:
$$\int e^{ax}\cos(bx)\,dx = \frac{a^2}{b^2+1}\left(\frac{1}{a}e^{ax}\cos(bx) + \frac{b}{a}\left(\frac{1}{a}e^{ax}\sin(bx)\right)\right) + C$$
If this is already wrong, can someone point be in the right direction?
If I have not gone wrong yet, I can edit to show the rest of my work.

A: Another solution to your original question can be using complex numbers.
$$\begin{align}
I&=\displaystyle\int e^{ax}\cos {bx}dx \\
&=\Re\left(\displaystyle\int e^{ax}(\cos {bx}+i\sin {bx})\right)dx\\
&=\Re\left(\displaystyle\int e^{(a+ib)x}dx\right)\\
&=\Re\left(\dfrac{e^{(a+ib)x}}{a+ib}\right)\\
&=\Re\left(\dfrac{e^{ax}(\cos {bx}+i\sin {bx})}{a+ib}\right)\\
&=\Re\left(\dfrac{e^{ax}}{a^2+b^2}(\cos {bx}++i\sin {bx})(a-ib)\right)+C\\
\therefore I&=\dfrac{e^{ax}}{a^2+b^2}(a\cos {bx}+b\sin {bx})+C
\end{align}$$

A: So you have
$$\int e^{ax}\cos(bx)dx = \frac{1}{a}e^{ax}\cos(bx) + \frac{b}{a}\left(\frac{1}{a}e^{ax}\sin(bx) - \frac{b}{a}\int e^{ax}\cos(bx)\,dx\right).$$
Multiplying out you get
$$\int e^{ax}\cos(bx)\,dx = \frac{1}{a}e^{ax}\cos(bx) + \frac{b}{a^2}e^{ax}\sin(bx) - \frac{b^2}{a^2}\int e^{ax}\cos(bx)\,dx.$$
At this point, you should move that last integral on the right hand side to the left hand side and add in the constant of integration on the right.
Moving the last integral to the left hand side, you get
$$\left(1 + \frac{b^2}{a^2}\right)\int e^{ax}\cos(bx)\,dx = \frac{1}{a}e^{ax}\cos(bx) + \frac{b}{a^2}e^{ax}\sin(bx) + C,$$
and I think this is where you made your mistake.
You tried to clear that $1 + \frac{b^2}{a^2}$ by  multiplying through by $\frac{a^2}{1+b^2}$. But this is incorrect:
$$1 + \frac{b^2}{a^2} = \frac{a^2+b^2}{a^2} \neq \frac{1+b^2}{a^2}$$
so that what you multiplied through did not clear that factor. You need to multiply by $\frac{a^2}{a^2+b^2}$ (or, more horribly, by
$$\frac{1}{1+\frac{b^2}{a^2}}$$
which is too horrible for words) for things to cancel out.
If you do that, from
$$\frac{a^2+b^2}{a^2}\int e^{ax}\cos(bx)\,dx = \frac{1}{a}e^{ax}\cos(bx) + \frac{b}{a^2}e^{ax}\sin(bx) + C,$$
multiplying both sides by $\frac{a^2}{a^2+b^2}$, we get:
$$\int e^{ax}\cos(bx)\,dx = \frac{a}{a^2+b^2}e^{ax}\cos(bx) + \frac{b}{a^2+b^2}e^{ax}\sin(bx) + C$$
the intended answer.
By the way: you don't need to have the "$+C$" on the right hand side until there are no more indefinite integrals there; the constant of integration is implicit in the indefinite integral, so for example, in your penultimate displayed equation, the "$+C$" is superfluous.


Q: Vagrant broken with Ruby 'Segmentation Fault' Error All of a sudden Vagrant is broken on my machine.
I don't see what might have caused this. It came up with an older version of Virtualbox and Vagrant 1.9.8. I updated both to the current version in hope to get it fixed.
I run

*

*Windows 10 Pro 1709

*Virtualbox 5.2.0-118431

*Vagrant 2.0.1

I was using a current Ruby installation in parallel but removed it for testing.
For any Vagrant command I get this error:
https://gist.github.com/cfoellmann/b8c50dc386d241d44ed0fca60e7680d1
I have read about issues with the ffi gem but I see no way to fix the bundled components of the vagrant install.
Any pointer into debugging this will be much appreciated.


Q: In text classification, how to find the part of sentence that is important for the classification? I have trained a text classification model that works well. I wanted to get deeper and understand what words/phrases from a sentence were most impactful in the classification outcome. I want to understand what words are most important for each classification outcome
I am using Keras for the classification and below is the code I am using to train the model. It's a simple embedding plus max-pooling text classification model that I am using.
from tensorflow.keras.models import Sequential
from tensorflow.keras import layers
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping

# early stopping
callbacks = tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', min_delta=0,
patience=5, verbose=2,  mode='auto', restore_best_weights=True)

# select optimizer
opt = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999,
epsilon=1e-07, amsgrad=False, name="Adam")
embedding_dim = 50

# declare model
model = Sequential()
model.add(layers.Embedding(input_dim=vocab_size,
                           output_dim=embedding_dim,
                           input_length=maxlen))
model.add(layers.GlobalMaxPool1D())
model.add(layers.Dense(10, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(optimizer=opt,
              loss='binary_crossentropy',
              metrics=['accuracy'])
model.summary()

# fit model
history = model.fit(X_tr, y_tr,
                    epochs=20,
                    verbose=True,
                    validation_data=(X_te, y_te),
                    batch_size=10, callbacks=[callbacks])
loss, accuracy = model.evaluate(X_tr, y_tr, verbose=False)

How do I extract the phrases/words that have the maximum impact on the classification outcome?

A: It seems that the keyword you need are "neural network interpretability" and "feature attribution". One of the best known methods in this area is called Integrated Gradients; it shows how model prediction depend on each input feature (each word embedding, in your case).
This tutorial shows how to implement IG in pure tensorflow for images, and this one uses the alibi library to highlight the words in the input text with the highest impact on a classification model.


Q: Modal view controller not in the window hierarchy The App I'm trying to do has a tabbar controller.
When the App starts, I'm getting the user location in the AppDelegate and when I've got the accuracy I need the AppDelegate sends an NSNotification to my App's starting page (index 0 of the tab bar controller).
Upon receiving the notification, this view tries to send an email with the user coordinates and other data, but as soon as the MFMailComposeViewController is presented I get the following error:
Warning: Attempt to present <MFMailComposeViewController: 0x98a0270> on <UITabBarController: 0x988c630> whose view is not in the window hierarchy!

What am I missing?
Thanks.
EDIT: adding some code...
This is what I've got in my AppDelegate.m:
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSUserDefaults *phoneNumbers = [NSUserDefaults standardUserDefaults];
NSDate *eventDate = newLocation.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 10.0) {
    [self locationUpdate:newLocation];
    smsLoc = newLocation;
    if ([[phoneNumbers objectForKey:@"sendSMS"] isEqualToString:@"yes"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sendSMS" object:nil];
    } else if ([[phoneNumbers objectForKey:@"sendEmail"] isEqualToString:@"yes"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sendEmail" object:nil];
    }

}
}

Then, in my first view controller I have:
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendSMS:) name:@"sendSMS" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendEmail:) name:@"sendEmail" object:nil];
}

And at the end, the selector for "sendSMS" (the other is pretty similar):
- (void)sendSMS: (NSNotification *)notification {
NSUserDefaults *phoneNumbers = [NSUserDefaults standardUserDefaults];
if ([phoneNumbers objectForKey:@"first"] || [phoneNumbers objectForKey:@"second"]) {
        MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
        if ([MFMessageComposeViewController canSendText]) {
            AppDelegate *deleg = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            controller.body = [NSString stringWithFormat:@"some message with coordinates %.4f - %.4f", [deleg currentLocation].coordinate.latitude, [deleg currentLocation].coordinate.longitude];
            controller.recipients = [NSArray arrayWithObjects:[phoneNumbers objectForKey:@"first"], [phoneNumbers objectForKey:@"second"], nil];
            controller.messageComposeDelegate = self;
            [self presentModalViewController:controller animated:YES];
        }
    }
}
}

Second edit: adding some more code.
UITabBarController *tabBarController = [[UITabBarController alloc] init];
tabBarController.delegate = self;
tabBarController.selectedIndex = 0;
[[tabBarController.tabBar.items objectAtIndex:0] setTitle:NSLocalizedString(@"Home", nil)];
[[tabBarController.tabBar.items objectAtIndex:1] setTitle:NSLocalizedString(@"Requests", nil)];
[[tabBarController.tabBar.items objectAtIndex:2] setTitle:NSLocalizedString(@"Account", nil)];
[[tabBarController.tabBar.items objectAtIndex:3] setTitle:NSLocalizedString(@"Settings", nil)];
//some other controls from DB
[[tabBarController.tabBar.items objectAtIndex:1] setBadgeValue:[NSString stringWithFormat:@"%d",number]];

The tabbarController has been made via IB, but I've added the code above in my AppDelegate because I need to localize the tab bar items and to add a badge to one of them.
Am I doing something wrong here?

A: Using this may help someone: [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:picker animated:NO completion:nil];

A: I'm not sure if you have solve this issue. The error message means the viewcontroller you use to present another modal viewcontroller is not visible on the window. This can happen for e.g:
[VC1 presentModalViewController:VC2];

// Error here, since VC1 is no longer visible on the window
[VC1 presentModalViewController:VC3];

If your issue is like above, you can fix it like:
if (self.modalViewController != nil) {
    [self.modalViewController presentModalViewController:VC3 animated:YES];
} else {
    [self.tabBarController presentModalViewController:VC3 animated:YES];
}

If that doesn't fix your issue, maybe you can try to present using self.tabBarController instead of self. Again just suggestion, not sure if it works though.

A: Since modalViewController and presentModalViewController are deprecated, the following is what works for me:
presentingVC = [[UIApplication sharedApplication] keyWindow].rootViewController;
if (presentingVC.presentedViewController) {
    [presentingVC.presentedViewController presentViewController:VC3 animated:YES completion:nil];
} else {
    [presentingVC presentViewController:VC3 animated:YES completion:nil];
}

A: You can follow this pattern
[VC1 presentModalViewController:VC2];

//
[**VC2** presentModalViewController:VC3];


Q: Detecting a pattern in a list/array This is rather an algorithmic question.
I have a Java List (sorted) or array that consists of chars (X and Y) and I need to detect a certain pattern of the way the values are ordered.
The List size is fixed (for example 5). The patterns I'd like to detect are the following:
XYYYY
XXYYY
XXXYY
XXXXY
XXXXX

So X is always followed by only Y's.
Simple String.equals or contains doesn't work, since it's not scalable and is restricted to a known list size.

A: You can use a simple regular expression for this:
boolean matches = s.matches("^X+Y*$");

This means:

*

*^ matches the start of the string

*X+ means one or more consecutive Xs

*Y* means zero or more consecutive Ys

*$ is the end of the string

Alternatively, you can check the string character-wise:
int i = 0;
while (i < s.length() && s.charAt(i) == 'X') {
  ++i;
}
if (i < s.length()) {
  if (s.charAt(i) != 'Y') {
    return false;
  }
  while (i < s.length() && s.charAt(i) == 'Y') {
    ++i;
  }
}
return i == s.length();

A: You can use the following regular expression to detect the particular pattern.
String pattern = "^(X){1,}Y*$";

Here's the complete java code,
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternMatch {
    public static void main(String[] args){
        // String to be scanned to find the pattern.
        String line = "XXXXY";
        String pattern = "^(X){1,}Y*$";

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.
        Matcher m = r.matcher(line);
        if (m.find( )) {
             System.out.println("Found value: " + m.group(0) );
        } else {
             System.out.println("NO MATCH");
        }
    }
}


Q: What goes into writing a cache simulator program? Can any one explain or point me to a source that explain what goes into writing a cache simulator program.
It's a school project and I have no intention to use anyone else's code as it does me no good. I will be tested on understanding of the program and concept, but I would like so see some detailed material, a pseudo code or gant chart or something.
I'm asking here because text book and lectures have not given me enough information and I've googled for hours this week and found nothing relevant.

A: Try this. But keep in mind about Academic Integrity, which is posted at the bottom of the page. It may not be the same school you go to, but I'm sure AI is universal regardless of whatever school assignment you're going through. You can also try Googling your problem, I found ~five references for doing so.