问:
Elm: Update value in sub types
I have this type

```<code>type alias Cat =
 { head : Head
 }

type alias Head =
  { eyes : Int
  , nose : Int
  , mouth : Mouth
  }

type alias Mouth =
  { tongue : Int
  , prey : Prey
  }

type alias Prey =
  { left : Int
  , right : Int
  }
</code>```

Inserting values

```<code>cat : Cat
cat =
  { head =
    { eyes = 2
    , nose = 1
    , mouth =
      { tongue = 1
      , prey =
        { left = 1
        , right = 1
        }
      }
    }
  }
</code>```

I'm usually doing this to change the right side of the prey

```<code>let
  newCat =
    (Cat
      (Head oldValue.eyes oldValue.nose
        (Mouth
          (Prey oldValue.left 1)
        )
      )
    )
in
 ({model | cat = newCat }, Cmd.none)
</code>```

And I hate hitting that, but I can not figure out how to do it the right way. When I try to do it right I can not return 'type cat'.

How to change the right prey in the right way?

答:
You're already doing it the right way.

When you're dealing with nested records, you have to build them up, just like you're already doing.

Now, what you can do is abstract newCat and turn it into a function of type Int -> Cat -> Cat. Then, you'd be able to do ({model | cat = updateRightPrey 1 model.cat }, Cmd.none)

But honestly, you may want to reconsider your data model. Does Head, Mouth, and Prey actually provide any value? What would you loose (and what would you have to gain) if you flatten your model like this:

```<code>type alias Cat =
  { eyes : Eyes
  , nose : Nose
  , tongue : Tongue
  , left : Prey
  , right : Prey
  }

type alias Eyes = Int
type alias Nose = Int
type alias Tongue = Int
type alias Prey = Int
</code>```

Even if you change all those Int type alias to types...

```<code>type Eyes = Eyes Int
</code>```

... it would be a lot simpler than dealing with nested records:

```<code>let
    cat = model.cat
in
({model | cat = { cat | right = 1 }, Cmd.none)
</code>```

or...

```<code>let
    cat = model.cat
in
({model | cat = { cat | right = Prey 1 }, Cmd.none)
</code>```

Title: Elm: Update value in sub types

Body:
I have this type

type alias Cat =
 { head : Head
 }

type alias Head =
  { eyes : Int
  , nose : Int
  , mouth : Mouth
  }

type alias Mouth =
  { tongue : Int
  , prey : Prey
  }

type alias Prey =
  { left : Int
  , right : Int
  }

Inserting values

cat : Cat
cat =
  { head =
    { eyes = 2
    , nose = 1
    , mouth =
      { tongue = 1
      , prey =
        { left = 1
        , right = 1
        }
      }
    }
  }

I'm usually doing this to change the right side of the prey

let
  newCat =
    (Cat
      (Head oldValue.eyes oldValue.nose
        (Mouth
          (Prey oldValue.left 1)
        )
      )
    )
in
 ({model | cat = newCat }, Cmd.none)

And I hate hitting that, but I can not figure out how to do it the right way. When I try to do it right I can not return 'type cat'.

How to change the right prey in the right way?

Body:
You're already doing it the right way.

When you're dealing with nested records, you have to build them up, just like you're already doing.

Now, what you can do is abstract newCat and turn it into a function of type Int -> Cat -> Cat. Then, you'd be able to do ({model | cat = updateRightPrey 1 model.cat }, Cmd.none)

But honestly, you may want to reconsider your data model. Does Head, Mouth, and Prey actually provide any value? What would you loose (and what would you have to gain) if you flatten your model like this:

type alias Cat =
  { eyes : Eyes
  , nose : Nose
  , tongue : Tongue
  , left : Prey
  , right : Prey
  }

type alias Eyes = Int
type alias Nose = Int
type alias Tongue = Int
type alias Prey = Int

Even if you change all those Int type alias to types...

type Eyes = Eyes Int

... it would be a lot simpler than dealing with nested records:

let
    cat = model.cat
in
({model | cat = { cat | right = 1 }, Cmd.none)

or...

let
    cat = model.cat
in
({model | cat = { cat | right = Prey 1 }, Cmd.none)


来源: stackexchange

问:
Declaration or Definition in C
From External Variables Wiki:

If neither the extern keyword nor an
  initialization value are present, the
  statement can be either a declaration
  or a definition. It is up to the
  compiler to analyse the modules of the
  program and decide.

I was not able to fully grasp the meaning of this statement with respect to C. For example, does it imply that:

```<code>int i;
</code>```

is not necessarily a declaration (as I have been assuming until now), but could be a definition as well (by definition of Definition & Declaration on the same webpage, no puns intended)?

In a nutshell, is the above statement:
a. just a declaration, or
b. declaration +  definition?

Reference: Variable declaration and definition

Summary of answers received:

```<code>                         Declaration    Definition    Tentative Definition   Initialized
int i;   (inside a block)    Yes           Yes                No                No
int i=5; (inside a block)    Yes           Yes                No               Yes(to 5)
int i;   (otherwise)         Yes            No               Yes               Yes(to 0)
extern int i;                Yes            No                No                No

All definitions are declarations but not vice-versa.
</code>```

答:
As C uses the terms:

A "definition" creates something (which occupies some sort of memory). It also describes something. This means a "definition" is also a "declaration".

A "declaration" just describes something. The idea is that the compiler needs to know how to build the code that uses the thing defined elsewhere. Later, the linker then links the use to the something.

Declarations allow you to compile code and link it (later) as a separate step.

ContentLicense: CC BY-SA 2.5

Title: Declaration or Definition in C

Body:
From External Variables Wiki:

If neither the extern keyword nor an
  initialization value are present, the
  statement can be either a declaration
  or a definition. It is up to the
  compiler to analyse the modules of the
  program and decide.

I was not able to fully grasp the meaning of this statement with respect to C. For example, does it imply that:

int i;

is not necessarily a declaration (as I have been assuming until now), but could be a definition as well (by definition of Definition & Declaration on the same webpage, no puns intended)?

In a nutshell, is the above statement:
a. just a declaration, or
b. declaration +  definition?

Reference: Variable declaration and definition

Summary of answers received:

                         Declaration    Definition    Tentative Definition   Initialized
int i;   (inside a block)    Yes           Yes                No                No
int i=5; (inside a block)    Yes           Yes                No               Yes(to 5)
int i;   (otherwise)         Yes            No               Yes               Yes(to 0)
extern int i;                Yes            No                No                No

All definitions are declarations but not vice-versa.


问:
<input type="radio"> does not line up with <text></text> behind it
My
<input type="radio">

in my form does not line up with my
<text></text>

behind it.

Example of my form

答:
below is working fine have look , to make it work you have to wrap you radio button in span, than wrap span and text div.

Real magic is you put your input control in span and set style sheet of span to make content center. that will do work for you.

```<code>.center {
    vertical-align: middle;
    display:inline;
}

<div>
    <span class="center">
       <input type="radio">
    </sapn> text of radio
</div>
</code>```

Working demo at jsfiddle : https://jsfiddle.net/hfu1zaxg/1/

ContentLicense: CC BY-SA 3.0

Body:
below is working fine have look , to make it work you have to wrap you radio button in span, than wrap span and text div.

Real magic is you put your input control in span and set style sheet of span to make content center. that will do work for you.

.center {
    vertical-align: middle;
    display:inline;
}

<div>
    <span class="center">
       <input type="radio">
    </sapn> text of radio
</div>

Working demo at jsfiddle : https://jsfiddle.net/hfu1zaxg/1/


问:
What does Openshift mean when it says it's "Evicted" my pods - and why does it keep doing so?
I am using OpenShift 3 Starter on OpenShift Online to run a small web project.  It had been running fine for the last two months and suddenly stopped running yesterday.  I found the deployment had simply gotten stuck at "Creating Container..."  When I tried to rebuild and restart the project, I ran into this problem.  After fixing that, the application now builds.

However, when I try to deploy, the deployment fails.  There are no logs.  The pod listing says "Evicted."

Why would this be happening?

There is a persistent volume claim in the project, and it is possible that the 1 GB storage space is full. Would this be a reason for eviction?  I cannot find any way to check if this is the case or not, as I cannot connect using oc rsh without any running pods, and there seems to be no way to check this fact from the Web Console.

I should mention that I have really struggled to understand the Openshift 3 documentation (which, in contrast to the Openshift 2 documentation, I find very unclear and confusing), so it is possible that I've missed some basic point that is contained in it.

EDIT: Graham Dumpleton in the comments below has pointed out that one of the servers is undergoing an upgrade and another had some scheduled maintenance.  However, the maintenance was completed on December 5th (according to the now updated status site).  I still cannot find any documentation that says what "evicted" means, so I have no information on how long this problem is going to continue, and what I can do to resolve it.

答: And, after four days, it started working again today.  Clearly @GrahamDumpleton was right, which is much poorer performance than one would expect from a large company like Red Hat. Hence I'm just leaving this question and answer here in case this happens to someone in future.</p>


问:
Group and center images of varying width?
I have 4 images that need to be "grouped" then centered horizontally.  These are letters in a word. They cannot be combined into a single image.

Here is what I have right now:

#imageContainer {
  width: 100%;
  border: 1px solid blue;
}
#images {
  display: block;
  margin: auto;
}
#imageContainer img {
  display: inline;
  margin: auto;
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="imageContainer">
  <div id="images">
    <img src="https://dummyimage.com/100x100/000/fff" alt="">
    <img src="https://dummyimage.com/80x100/000/fff" alt="">
    <img src="https://dummyimage.com/105x100/000/fff" alt="">
    <img src="https://dummyimage.com/135x100/000/fff" alt="">
  </div>
</div></code>```

The desired behavior would look more like this:

How can I achieve this?

答:
Just use this:

```<code>#imageContainer {
    width: 100%;
    border: 1px solid blue;
    text-align: center;
}
</code>```

I only add  text-align: center; in parent div. And It is working. Let me know if you have any problem.

Body:
I have 4 images that need to be "grouped" then centered horizontally.  These are letters in a word. They cannot be combined into a single image.

Here is what I have right now:

#imageContainer {
  width: 100%;
  border: 1px solid blue;
}
#images {
  display: block;
  margin: auto;
}
#imageContainer img {
  display: inline;
  margin: auto;
  padding: 5px;
}

The desired behavior would look more like this:

How can I achieve this?

Body:
Just use this:

#imageContainer {
    width: 100%;
    border: 1px solid blue;
    text-align: center;
}

I only add  text-align: center; in parent div. And It is working. Let me know if you have any problem.


问:
How to disable scrolling temporarily?
I'm using the scrollTo jQuery plugin and would like to know if it is somehow possible to temporarily disable scrolling on the window element through Javascript? The reason I'd like to disable scrolling is that when you scroll while scrollTo is animating, it gets really ugly ;)

Of course, I could do a $("body").css("overflow", "hidden"); and then put it back to auto when the animation stops, but it would be better if the scrollbar was still visible but inactive.

答:
Here's a really basic way to do it:

```<code>window.onscroll = function () { window.scrollTo(0, 0); };
</code>```

It's kind of jumpy in IE6.

Title: How to disable scrolling temporarily?

Body:
Here's a really basic way to do it:

window.onscroll = function () { window.scrollTo(0, 0); };

It's kind of jumpy in IE6.


问:
getting the Id of a button in JavaFX
I created about 10 buttons in javafx each of them onclick is suppose to  change the label field in a certain way. My problem is that I don't want to  create 10 different methods for each label I will like to use one method then test the id of the button if correct I preform what I want

example of what I am asking

```<code>   if (button.id == Info_205_btn) {
        System.out.println("clicked");
     subject_name.setText("stanly");
    }
</code>```

This is an update after @math  answer

Here is the code I did

```<code>    @FXML
    private void chooseSubject() {
  for (int i = 0; i < buttonInfo.length; i++) {
            buttonInfo[i] = new Button("Info"+i);
            buttonInfo[i].setId("Info"+i);
            int finalI = i;
            buttonInfo[i].setOnAction(event -> checkID(buttonInfo[finalI]));
        }
    }

    @FXML
    private void checkID(Button button){
                System.out.println("running");

    if (button.getId().equals("Info0")) {
        System.out.println("clicked");
       subject_name.setText("stanly");
    }
    else if (button.getId().equals("Info1")) {
        System.out.println("clicked");
       subject_name.setText("stanly1");
    }
}

    @Override
    public void initialize(URL url, ResourceBundle rb) {
         chooseSubject();
    }
</code>```

also on click I placed the method chooseSubject in FXML controller

答:
For all of your buttons I think you will still need to put a .setOnAction but you can have them all point to the same function

```<code>button.setOnAction(event -> checkID(button));
</code>```

and from that function check the id

```<code>private void checkID(Button button){
    if (button.getId().equals("Info_205_btn")) {
        System.out.println("clicked");
        button.setText("stanly");
    }
    else if (button.getId().equals("Info_206_btn")) {
        System.out.println("clicked");
        button.setText("stanly");
    }
    //So on
}
</code>```

Also if you put all of your buttons into a list or if they are already in a list you can iterate though the list and do the .setOnAction that way

```<code>for (int i = 0; i < buttonList.length; i++)
    button[i].setOnAction(event -> checkId((Button) event.getSource()));
</code>```

Here is a test program I just wrote to give you an example

```<code>import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        Button[] buttonList = new Button[10];

        for (int i = 0; i < buttonList.length; i++) {
            buttonList[i] = new Button("Button "+i);
            buttonList[i].setId("Button"+i);
            buttonList[i].setOnAction(event -> checkId((Button) event.getSource()));
        }

        VBox root = new VBox();
        root.setAlignment(Pos.CENTER);
        root.getChildren().addAll(buttonList);
        Scene scene = new Scene(root);
        Stage stage = new Stage();
        stage.setWidth(200);
        stage.setScene(scene);
        stage.show();
    }

    private void checkId(Button button) {
        for (int i = 0; i <= 10; i++) {
            if(button.getId().equals("Button" + i))
                if(!button.getText().equals("Button " + i + " Clicked"))
                    button.setText("Button " + i + " Clicked");
                else
                    button.setText("Button " + i);
        }
    }

    public static void main(String[] args) { launch(args); }
}
</code>```

Edit: Got carried away

Title: getting the Id of a button in JavaFX

Body:
I created about 10 buttons in javafx each of them onclick is suppose to  change the label field in a certain way. My problem is that I don't want to  create 10 different methods for each label I will like to use one method then test the id of the button if correct I preform what I want

example of what I am asking

   if (button.id == Info_205_btn) {
        System.out.println("clicked");
     subject_name.setText("stanly");
    }

This is an update after @math  answer

Here is the code I did

    @FXML
    private void chooseSubject() {
  for (int i = 0; i < buttonInfo.length; i++) {
            buttonInfo[i] = new Button("Info"+i);
            buttonInfo[i].setId("Info"+i);
            int finalI = i;
            buttonInfo[i].setOnAction(event -> checkID(buttonInfo[finalI]));
        }
    }

    @FXML
    private void checkID(Button button){
                System.out.println("running");

    if (button.getId().equals("Info0")) {
        System.out.println("clicked");
       subject_name.setText("stanly");
    }
    else if (button.getId().equals("Info1")) {
        System.out.println("clicked");
       subject_name.setText("stanly1");
    }
}

    @Override
    public void initialize(URL url, ResourceBundle rb) {
         chooseSubject();
    }

also on click I placed the method chooseSubject in FXML controller

Body:
For all of your buttons I think you will still need to put a .setOnAction but you can have them all point to the same function

button.setOnAction(event -> checkID(button));

and from that function check the id

private void checkID(Button button){
    if (button.getId().equals("Info_205_btn")) {
        System.out.println("clicked");
        button.setText("stanly");
    }
    else if (button.getId().equals("Info_206_btn")) {
        System.out.println("clicked");
        button.setText("stanly");
    }
    //So on
}

Also if you put all of your buttons into a list or if they are already in a list you can iterate though the list and do the .setOnAction that way

for (int i = 0; i < buttonList.length; i++)
    button[i].setOnAction(event -> checkId((Button) event.getSource()));

Here is a test program I just wrote to give you an example

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        Button[] buttonList = new Button[10];

        for (int i = 0; i < buttonList.length; i++) {
            buttonList[i] = new Button("Button "+i);
            buttonList[i].setId("Button"+i);
            buttonList[i].setOnAction(event -> checkId((Button) event.getSource()));
        }

        VBox root = new VBox();
        root.setAlignment(Pos.CENTER);
        root.getChildren().addAll(buttonList);
        Scene scene = new Scene(root);
        Stage stage = new Stage();
        stage.setWidth(200);
        stage.setScene(scene);
        stage.show();
    }

    private void checkId(Button button) {
        for (int i = 0; i <= 10; i++) {
            if(button.getId().equals("Button" + i))
                if(!button.getText().equals("Button " + i + " Clicked"))
                    button.setText("Button " + i + " Clicked");
                else
                    button.setText("Button " + i);
        }
    }

    public static void main(String[] args) { launch(args); }
}

Edit: Got carried away


问:
Is `-1` correct for using as maximum value of an unsigned integer?
Is there any c++ standard paragraph which says that using -1 for this is portable and correct way or the only way of doing this correctly is using predefined values?

I have had a conversation with my colleague, what is better: using -1 for a maximum unsigned integer number or using a value from limits.h or std::numeric_limits ?

I have told my colleague that using predefined maximum values from limits.h or std::numeric_limits is the portable and clean way of doing this, however, the colleague objected to -1 being as same portable as numeric limits, and more, it has one more advantage:

```<code>unsigned short i = -1; // unsigned short max
</code>```

can easily be changed to any other type, like

```<code>unsigned long i = -1; // unsigned long max
</code>```

when using the predefined value from the limits.h header file or std::numeric_limits also requires to rewrite it too along with the type to the left.

答:
Is -1 correct for using as maximum value of an unsigned integer?

Yes, it is functionally correct when used as a direct assignment/initialization.  Yet often looks questionable @Ron.

Constants from limits.h or std::numeric_limits convey more code understanding, yet need maintenance should the type of i change.

[Note] OP later drop the C tag.

To add an alternative to assigning a maximum value (available in C11) that helps reduce code maintenance:

Use the loved/hated _Generic

```<code>#define info_max(X) _Generic((X), \
  long double: LDBL_MAX, \
  double: DBL_MAX, \
  float: FLT_MAX, \
  unsigned long long: ULLONG_MAX, \
  long long: LLONG_MAX, \
  unsigned long: ULONG_MAX, \
  long: LONG_MAX, \
  unsigned: UINT_MAX, \
  int: INT_MAX, \
  unsigned short: USHRT_MAX, \
  short: SHRT_MAX, \
  unsigned char: UCHAR_MAX, \
  signed char: SCHAR_MAX, \
  char: CHAR_MAX, \
  _Bool: 1, \
  default: 1/0 \
  )

int main() {
  ...
  some_basic_type i = info_max(i);
  ...
}
</code>```

The above macro info_max() have limitations concerning types like size_t, intmax_t, etc. that may not be enumerated in the above list.  There are more complex macros that can cope with that.   The idea here is illustrative.

Body:
Is there any c++ standard paragraph which says that using -1 for this is portable and correct way or the only way of doing this correctly is using predefined values?

I have had a conversation with my colleague, what is better: using -1 for a maximum unsigned integer number or using a value from limits.h or std::numeric_limits ?

I have told my colleague that using predefined maximum values from limits.h or std::numeric_limits is the portable and clean way of doing this, however, the colleague objected to -1 being as same portable as numeric limits, and more, it has one more advantage:

unsigned short i = -1; // unsigned short max

can easily be changed to any other type, like

unsigned long i = -1; // unsigned long max

when using the predefined value from the limits.h header file or std::numeric_limits also requires to rewrite it too along with the type to the left.

Body:
Is -1 correct for using as maximum value of an unsigned integer?

Yes, it is functionally correct when used as a direct assignment/initialization.  Yet often looks questionable @Ron.

Constants from limits.h or std::numeric_limits convey more code understanding, yet need maintenance should the type of i change.

[Note] OP later drop the C tag.

To add an alternative to assigning a maximum value (available in C11) that helps reduce code maintenance:

Use the loved/hated _Generic

#define info_max(X) _Generic((X), \
  long double: LDBL_MAX, \
  double: DBL_MAX, \
  float: FLT_MAX, \
  unsigned long long: ULLONG_MAX, \
  long long: LLONG_MAX, \
  unsigned long: ULONG_MAX, \
  long: LONG_MAX, \
  unsigned: UINT_MAX, \
  int: INT_MAX, \
  unsigned short: USHRT_MAX, \
  short: SHRT_MAX, \
  unsigned char: UCHAR_MAX, \
  signed char: SCHAR_MAX, \
  char: CHAR_MAX, \
  _Bool: 1, \
  default: 1/0 \
  )

int main() {
  ...
  some_basic_type i = info_max(i);
  ...
}

The above macro info_max() have limitations concerning types like size_t, intmax_t, etc. that may not be enumerated in the above list.  There are more complex macros that can cope with that.   The idea here is illustrative.

ContentLicense: CC BY-SA 4.0


问:
WindowsError when calling sc.parallelize()
I want to use the sc.parallelize() function, but whenever I try to call it, I get the below error:

File "V:/PyCharmProjects/sample.py", line 9, in <module>

input_data = sc.parallelize(sc.textFile("C:\Users\Spider\Desktop\GM_coding\Sample Data.csv"))

 File "V:\spark-2.2.0-bin-hadoop2.7\python\pyspark\context.py", line 497, in parallelize os.unlink(tempFile.name)

WindowsError: [Error 32] The process cannot access the file because it is being used by another process: u'C:\\Users\\Spider\\AppData\\Local\\Temp\\spark-fef6debd-ff91-4fb6-85dc-8c3a1da9690a\\pyspark-6ed523e7-358f-4e3c-ad83-a479fb8ecc52\\tmpxffhfi'
```

答:
Not sure if it's relevant to your error (and cannot test it in Windows), but you are trying to parallelize something that is already an RDD (i.e. "parallelized"); from the docs:

textFile(name, minPartitions=None, use_unicode=True)

Read a text file from HDFS, a local file system (available on all nodes), or any Hadoop-supported file system URI, and return it as an
  RDD of Strings.

You don't need (and shouldn't use) sc.parallelize() here; the output of sc.textFile is already an RDD. You should simply go for

input_data = sc.textFile("C:\Users\Spider\Desktop\GM_coding\Sample Data.csv")
```

See also the example in the quick start guide.

Body:
Not sure if it's relevant to your error (and cannot test it in Windows), but you are trying to parallelize something that is already an RDD (i.e. "parallelized"); from the docs:

textFile(name, minPartitions=None, use_unicode=True)

Read a text file from HDFS, a local file system (available on all nodes), or any Hadoop-supported file system URI, and return it as an
  RDD of Strings.

You don't need (and shouldn't use) sc.parallelize() here; the output of sc.textFile is already an RDD. You should simply go for

input_data = sc.textFile("C:\Users\Spider\Desktop\GM_coding\Sample Data.csv")

See also the example in the quick start guide.


问:
How to set up multiple cron jobs that run one after the other in PHP and Ubuntu
I have a basic understanding of cron jobs, but I need something more complex now. I need to upload around 100 tables in to MySql, each table has around 500 MB data and then run some php cron jobs on each table, one table after the other. I explain it more detail below:

Upload table through load data local infile in php. Tables are to be uploaded from my directory which had CSV files. How do I create a loop to upload all these files?

Run script1.php, then script2.php then script3.php all three as cron jobs

Repeat step 1

Kindly let me know how to do this? I am on Ubuntu 16.04.

答:
Create a script (e.g. bash) that does all of the work you want to do, including updloading the table data, running the php scripts, and repeating as needed.

Sample bash file (/home/spanky/stuffToDo.sh):

```<code>#!/bin/bash
# Simple bash script that does some work

php -f dowork1.php
php -f dowork2.php
php -f dowork3.php
</code>```

Set up your cron job to call that script as needed, something like this:

```<code>10 * * * * /home/spanky/stuffToDo.sh
</code>```

See the answers to this question for more details about calling PHP functions from a bash script, particularly the answers which mention the use of CLI PHP for command-line use of PHP.

There are lots of solid examples out there that demonstrate using bash for this type of thing.  This is a great place to start:  https://linuxconfig.org/bash-scripting-tutorial

Note: If each step absolutely must be a cron job, then you'll have to schedule them accordingly, understanding that they may overlap if one finishes late (or never finishes).  You could get into more complicated scenarios where one cronjob that relies on the completion of a previous job will check a status flag or file before proceeding, but that gets messy quickly.

Body:
Create a script (e.g. bash) that does all of the work you want to do, including updloading the table data, running the php scripts, and repeating as needed.

Sample bash file (/home/spanky/stuffToDo.sh):

#!/bin/bash
# Simple bash script that does some work

php -f dowork1.php
php -f dowork2.php
php -f dowork3.php

Set up your cron job to call that script as needed, something like this:

10 * * * * /home/spanky/stuffToDo.sh

See the answers to this question for more details about calling PHP functions from a bash script, particularly the answers which mention the use of CLI PHP for command-line use of PHP.

There are lots of solid examples out there that demonstrate using bash for this type of thing.  This is a great place to start:  https://linuxconfig.org/bash-scripting-tutorial

Note: If each step absolutely must be a cron job, then you'll have to schedule them accordingly, understanding that they may overlap if one finishes late (or never finishes).  You could get into more complicated scenarios where one cronjob that relies on the completion of a previous job will check a status flag or file before proceeding, but that gets messy quickly.


问:
WPF: Get the real 'logical' position of Child within its parent Panel
Another problem in my WPF questions series :)

I'm creating custom Decorator that will be used to decorate Panels (or it can be Behavior, no difference).

That Decorator deals with elements that are in that Panel (Children property of the Panel). It attaches some RenderTransforms to those elements. Now I need a position of some element ('child' of the Panel) relative to the Panel itself. In other words I need a position if some child element in the Panels coordinate space. in just another words I want the offset that was specified by the ArrangeOverride method of the Panel when calling Arrange method on Children.

That seem to be easy. But I cannot find the way to always get right coordinates.

This code

```<code>VisualTreeHelper.GetOffset(child)
</code>```

does not work when the panel is inside ScrollView - it takes topmost, leftmost visible corner of the Panel as an origin of coordinate space - not the real topmost and leftmost corner of the Panel.

The code

```<code>Point position = child.TransformToAncestor(panel).Transform(new Point(0,0));
</code>```

will not work when some render transforms are already active on the child element of the Panel.  It will return the position of transformed image(by the render transfrom) of child element. The render position.

The same problem is with this aproach:

```<code>Point panelPosition = panel.PointToScreen(new Point(0, 0));
Point childPosition = child.PointToScreen(new Point(0, 0));
Point position = new Point(childPosition.X - panelPosition.X, childsPosition.Y - panelPosition.Y);
</code>```

So this i what I have tryied but it did not work. I have 2 similar questions on this topic that were tying to simplify the problem, so I got some of suggestions above. Now I introduced the problem in its full complexity, I hope to get the right advice.

If something is unclear please leave the comment.
Thank you

答:
You can "undo" the RenderTransform before calling TransformToAncestor:

```<code>Point origin = child.RenderTransform.Inverse.Transform(new Point(0, 0));
Point position = child.TransformToAncestor(listBox).Transform(origin);
</code>```

Body:
Another problem in my WPF questions series :)

I'm creating custom Decorator that will be used to decorate Panels (or it can be Behavior, no difference).

That Decorator deals with elements that are in that Panel (Children property of the Panel). It attaches some RenderTransforms to those elements. Now I need a position of some element ('child' of the Panel) relative to the Panel itself. In other words I need a position if some child element in the Panels coordinate space. in just another words I want the offset that was specified by the ArrangeOverride method of the Panel when calling Arrange method on Children.

That seem to be easy. But I cannot find the way to always get right coordinates.

This code

VisualTreeHelper.GetOffset(child)

does not work when the panel is inside ScrollView - it takes topmost, leftmost visible corner of the Panel as an origin of coordinate space - not the real topmost and leftmost corner of the Panel.

The code

Point position = child.TransformToAncestor(panel).Transform(new Point(0,0));

will not work when some render transforms are already active on the child element of the Panel.  It will return the position of transformed image(by the render transfrom) of child element. The render position.

The same problem is with this aproach:

Point panelPosition = panel.PointToScreen(new Point(0, 0));
Point childPosition = child.PointToScreen(new Point(0, 0));
Point position = new Point(childPosition.X - panelPosition.X, childsPosition.Y - panelPosition.Y);

So this i what I have tryied but it did not work. I have 2 similar questions on this topic that were tying to simplify the problem, so I got some of suggestions above. Now I introduced the problem in its full complexity, I hope to get the right advice.

If something is unclear please leave the comment.
Thank you

Body:
You can "undo" the RenderTransform before calling TransformToAncestor:

Point origin = child.RenderTransform.Inverse.Transform(new Point(0, 0));
Point position = child.TransformToAncestor(listBox).Transform(origin);


问:
How to Exit For Loop without going to Next
I have in my code a For loop that contains an If Else statement.  When the If statement is true, I want to exit the entire For loop.  There will be no further need to loop through the rest of the range.  Will "Exit For" be appropriate for this?

I was looking at the Exit statement on Microsoft's website, and according to them, Exit For continues execution with the statement immediately following the Next statement.  If this is true, Exit For won't work.  I want to proceed past the Next command.

I can take the time to test this using a numerical counter or something, but I'd rather get a quick answer, as I'm sure this is obvious to most people on here.  Thanks!

答:
Yes you can. Using:

```<code>Sub test()

Dim x As Integer
For x = 1 To 10

    If x = 2 Then
        Debug.Print "here"
        Exit For
    Else
        Debug.Print x
    End If

Next x

End Sub
</code>```

I get:

```<code>1
here
</code>```

And with this:

```<code>Sub test4()

Dim x As Integer
For x = 1 To 10

    If x = 2 Then
        Debug.Print "here"
        Exit For
    Else
        Debug.Print x
    End If

Debug.Print "testing"

Next x

End Sub
</code>```

I get:

```<code> 1
testing
here
</code>```

And with this:

```<code>Sub test4()

Dim x As Integer
For x = 1 To 10

    If x = 2 Then
        Debug.Print "here"
        Exit For
        Debug.Print "after here"
    Else
        Debug.Print x
    End If

Debug.Print "testing"

Next x

End Sub
</code>```

you get:

```<code> 1
testing
here
</code>```

Body:
Yes you can. Using:

Sub test()

Dim x As Integer
For x = 1 To 10

    If x = 2 Then
        Debug.Print "here"
        Exit For
    Else
        Debug.Print x
    End If

Next x

End Sub

I get:

1
here

And with this:

Sub test4()

Dim x As Integer
For x = 1 To 10

    If x = 2 Then
        Debug.Print "here"
        Exit For
    Else
        Debug.Print x
    End If

Debug.Print "testing"

Next x

End Sub

I get:

 1
testing
here

And with this:

Sub test4()

Dim x As Integer
For x = 1 To 10

    If x = 2 Then
        Debug.Print "here"
        Exit For
        Debug.Print "after here"
    Else
        Debug.Print x
    End If

Debug.Print "testing"

Next x

End Sub

you get:

 1
testing
here


问:
MYSQL - Self join on already aliased query (alias of alias ?)
Well, my query is :

```<code>SELECT *,
(aliasA.avalue+aliasB.avalue) as mycustomsum

FROM (SELECT bla,bla,bla ...) as aliasA
INNER JOIN (SELECT bla,bla,bla ...) as aliasB
ON aliasA.mydate=aliasB.otherdate
order by month desc
</code>```

Now i would like another column of itself but showing mycustomsum of 12 months before !
Self join of alias doesn't work !

in other words the result of my query is :

```<code>2017-12 | 123
2017-11 | 456
.
.
.
2016-12 | 789
2016-11 | 321
</code>```

and i would like :

```<code>2017-12 | 123 | 789
2017-11 | 456 | 321
.
.
.
2016-12 | 789 | null
2016-11 | 321 | null
</code>```

Just want to compare current year to last year , month by month ,
Its just "show the result from 12 rows ago" !
Any idea ?

答:
As aaron said it in previous comment: LAG function are a(the) way
but with mysql 5.7... no LAG function, so simulating !

So the working solution for -12 rows value compare is :

```<code>SET @back0=-1;
SET @back1=-1;
SET @back2=-1;
SET @back3=-1;
SET @back4=-1;
SET @back5=-1;
SET @back6=-1;
SET @back7=-1;
SET @back8=-1;
SET @back9=-1;
SET @back10=-1;
SET @back11=-1;

Select * ,
(MyvalueA-MyvalueB) as Myresult,
@back0 m0,
@back0:=@back1 m1,
@back1:=@back2 m2,
@back2:=@back3 m3,
@back3:=@back4 m4,
@back4:=@back5 m5,
@back5:=@back6 m6,
@back6:=@back7 m7,
@back7:=@back8 m8,
@back8:=@back9 m9,
@back9:=@back10 m10,
@back10:=@back11 m11,
@back11:=(MyvalueA-MyvalueB) m12

etc....
</code>```

Remember to reverse the original order :)

Why this super-crappy solution ? Because there is no Array type in mysql variable !

If someone has another elegant solution, you are welcome

Body:
Well, my query is :

SELECT *,
(aliasA.avalue+aliasB.avalue) as mycustomsum

FROM (SELECT bla,bla,bla ...) as aliasA
INNER JOIN (SELECT bla,bla,bla ...) as aliasB
ON aliasA.mydate=aliasB.otherdate
order by month desc

Now i would like another column of itself but showing mycustomsum of 12 months before !
Self join of alias doesn't work !

in other words the result of my query is :

2017-12 | 123
2017-11 | 456
.
.
.
2016-12 | 789
2016-11 | 321

and i would like :

2017-12 | 123 | 789
2017-11 | 456 | 321
.
.
.
2016-12 | 789 | null
2016-11 | 321 | null

Just want to compare current year to last year , month by month ,
Its just "show the result from 12 rows ago" !
Any idea ?

Body:
As aaron said it in previous comment: LAG function are a(the) way
but with mysql 5.7... no LAG function, so simulating !

So the working solution for -12 rows value compare is :

SET @back0=-1;
SET @back1=-1;
SET @back2=-1;
SET @back3=-1;
SET @back4=-1;
SET @back5=-1;
SET @back6=-1;
SET @back7=-1;
SET @back8=-1;
SET @back9=-1;
SET @back10=-1;
SET @back11=-1;

Select * ,
(MyvalueA-MyvalueB) as Myresult,
@back0 m0,
@back0:=@back1 m1,
@back1:=@back2 m2,
@back2:=@back3 m3,
@back3:=@back4 m4,
@back4:=@back5 m5,
@back5:=@back6 m6,
@back6:=@back7 m7,
@back7:=@back8 m8,
@back8:=@back9 m9,
@back9:=@back10 m10,
@back10:=@back11 m11,
@back11:=(MyvalueA-MyvalueB) m12

etc....

Remember to reverse the original order :)

Why this super-crappy solution ? Because there is no Array type in mysql variable !

If someone has another elegant solution, you are welcome


问:
LiipImagineBundle error
I'm installing the bundle LiipImagineBundle for my symfony project.
I added it in the kernel, config it :

```<code>liip_imagine:
resolvers:
    default:
        web_path: ~
filter_sets:
    avatar:
        quality: 75
        cache: ~
        filters:
            thumbnail: { size: [120, 120], mode: outbound }
</code>```

When i'm launching a page with a form in it, i got this error :

```<code>Unable to find template "LiipImagineBundle:Form:form_div_layout.html.twig" (looked into: /Users/user/www/html/project/app/Resources/views, /Users/user/www/html/project/vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form).
</code>```

Why ? Can you help me to find the problem ? And when i delete the config and kernel for LiipImagineBundle, it's working again.

Thanks by advance,

Edit :
I'm working on the v3.4.1 of symfony.

```<code>"php": ">=5.5.9",
"doctrine/doctrine-bundle": "^1.6",
"doctrine/orm": "^2.5",
"incenteev/composer-parameter-handler": "^2.0",
"sensio/distribution-bundle": "^5.0.19",
"sensio/framework-extra-bundle": "^5.0.0",
"symfony/monolog-bundle": "^3.1.0",
"symfony/polyfill-apcu": "^1.0",
"symfony/swiftmailer-bundle": "^2.6.4",
"symfony/symfony": "3.4.*",
"twig/twig": "^1.0||^2.0",
"jms/serializer-bundle": "^2.3.0",
"friendsofsymfony/elastica-bundle": "^4.0.1",
"friendsofsymfony/rest-bundle": "^2.3.0",
"friendsofsymfony/user-bundle": "^2.0.2",
"stof/doctrine-extensions-bundle": "^1.2.2",
"doctrine/doctrine-migrations-bundle": "^1.3.1",
"lexik/maintenance-bundle": "^2.1.2",
"liip/imagine-bundle": "^1.9.1",
"nelmio/api-doc-bundle": "^2.13.3",
"nietonfir/google-recaptcha-bundle": "^0.2.1",
"beberlei/DoctrineExtensions": "^1.0.20"
</code>```

答:
I was able to reproduce the problem and found a work around hack.

```<code># LiipImagineExtension.php
$resources = $container->hasParameter('twig.form.resources') ?
$container->getParameter('twig.form.resources') : array();

// The existing line
//$resources[] = 'LiipImagineBundle:Form:form_div_layout.html.twig';

// Change to
$resources[] = '@LiipImagine/Form/form_div_layout.html.twig';

$container->setParameter('twig.form.resources', $resources);
</code>```

So somewhere along the line S3.4 seems to have changed something to only use twig namespaces instead of the colon notation.  Kind of a strange BC break for Symfony.

I checked on liip github.  This is actually fixed in their unreleased 2.0 branch.  Consider updating to "liip/imagine-bundle": "^2.0@dev",

This can also be fixed by configuring the framework to use twig:

```<code># app/config/config.yml
framework:
    templating:
        engines: ['twig']
</code>```

Title: LiipImagineBundle error

Body:
I'm installing the bundle LiipImagineBundle for my symfony project.
I added it in the kernel, config it :

liip_imagine:
resolvers:
    default:
        web_path: ~
filter_sets:
    avatar:
        quality: 75
        cache: ~
        filters:
            thumbnail: { size: [120, 120], mode: outbound }

When i'm launching a page with a form in it, i got this error :

Unable to find template "LiipImagineBundle:Form:form_div_layout.html.twig" (looked into: /Users/user/www/html/project/app/Resources/views, /Users/user/www/html/project/vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form).

Why ? Can you help me to find the problem ? And when i delete the config and kernel for LiipImagineBundle, it's working again.

Thanks by advance,

Edit :
I'm working on the v3.4.1 of symfony.

"php": ">=5.5.9",
"doctrine/doctrine-bundle": "^1.6",
"doctrine/orm": "^2.5",
"incenteev/composer-parameter-handler": "^2.0",
"sensio/distribution-bundle": "^5.0.19",
"sensio/framework-extra-bundle": "^5.0.0",
"symfony/monolog-bundle": "^3.1.0",
"symfony/polyfill-apcu": "^1.0",
"symfony/swiftmailer-bundle": "^2.6.4",
"symfony/symfony": "3.4.*",
"twig/twig": "^1.0||^2.0",
"jms/serializer-bundle": "^2.3.0",
"friendsofsymfony/elastica-bundle": "^4.0.1",
"friendsofsymfony/rest-bundle": "^2.3.0",
"friendsofsymfony/user-bundle": "^2.0.2",
"stof/doctrine-extensions-bundle": "^1.2.2",
"doctrine/doctrine-migrations-bundle": "^1.3.1",
"lexik/maintenance-bundle": "^2.1.2",
"liip/imagine-bundle": "^1.9.1",
"nelmio/api-doc-bundle": "^2.13.3",
"nietonfir/google-recaptcha-bundle": "^0.2.1",
"beberlei/DoctrineExtensions": "^1.0.20"

Body:
I was able to reproduce the problem and found a work around hack.

# LiipImagineExtension.php
$resources = $container->hasParameter('twig.form.resources') ?
$container->getParameter('twig.form.resources') : array();

// The existing line
//$resources[] = 'LiipImagineBundle:Form:form_div_layout.html.twig';

// Change to
$resources[] = '@LiipImagine/Form/form_div_layout.html.twig';

$container->setParameter('twig.form.resources', $resources);

So somewhere along the line S3.4 seems to have changed something to only use twig namespaces instead of the colon notation.  Kind of a strange BC break for Symfony.

I checked on liip github.  This is actually fixed in their unreleased 2.0 branch.  Consider updating to "liip/imagine-bundle": "^2.0@dev",

This can also be fixed by configuring the framework to use twig:

# app/config/config.yml
framework:
    templating:
        engines: ['twig']


问:
Adding multiple rows with the same name pandas
I have a quick question.
If I have multiple rows with the same NAME but different quantities is there a pandas function to just add them? </p>

```<code>NAME     QTY
A         2
A         5

A         6

A total = 13?
</code>```

答:
There are various ways to do it. But in simple terms it is grouping & aggregation.</p>

```<code>from pyspark.sql.functions import sum
df.groupBy('NAME').agg(sum('QTY')).show()
</code>```

Body:
I have a quick question.
If I have multiple rows with the same NAME but different quantities is there a pandas function to just add them?

NAME     QTY
A         2
A         5

A         6

A total = 13?

Body:
There are various ways to do it. But in simple terms it is grouping & aggregation.

from pyspark.sql.functions import sum
df.groupBy('NAME').agg(sum('QTY')).show()


问:
Missing Files in Vagrant Synced Folder Path
My installation of vagrant is not seeing every file within the synced folder path.

From my Mac shell:

```<code>my-mac:seeds pivot$ ls -la BeltContentP*Seeds.php
-rw-rw-r--  1 pivot  staff  3034 Dec  7 11:21 BeltContentPageSeeds.php
-rw-rw-r--  1 pivot  staff  1627 Dec  6 16:54 BeltContentPostSeeds.php
</code>```

From my Vagrant shell:

```<code>vagrant@homestead:~/Code/demo.larabelt/all/database/seeds$ ls -la BeltContentP*Seeds.php
-rw-r--r-- 1 vagrant vagrant 1627 Dec  6 21:54 BeltContentPostSeeds.php
</code>```

If I rename the missing file in my host system, it appears on my guest.

This issue appeared after upgrading my Mac OS to High Sierra 10.13.1. I had otherwise used this setup successfully for probably 2+ years.

I have since tried to upgrade the various related packages, as well as reinstalling various items, but it has not solved the issue so far. Downgrading my Mac OS to the previous version does not appear to be easy or straightforward.

Additional Detail:
 - sync type: NFS
 - VirtualBox: 5.1.30
 - Vagrant: 2.0.1
 - Vagrant Box: laravel/homestead
 - Vagrant Plugins: 'vagrant-bindfs' & 'vagrant-vbguest'

答: Mac OS High Sierra broke NFS file sharing pretty hard. See https://github.com/hashicorp/vagrant/issues/8788 but this should be resolved via MacOS 10.13.2 Have you updated yet today? That should resolve the issue for you.

Body:
My installation of vagrant is not seeing every file within the synced folder path.

From my Mac shell:

my-mac:seeds pivot$ ls -la BeltContentP*Seeds.php
-rw-rw-r--  1 pivot  staff  3034 Dec  7 11:21 BeltContentPageSeeds.php
-rw-rw-r--  1 pivot  staff  1627 Dec  6 16:54 BeltContentPostSeeds.php

From my Vagrant shell:

vagrant@homestead:~/Code/demo.larabelt/all/database/seeds$ ls -la BeltContentP*Seeds.php
-rw-r--r-- 1 vagrant vagrant 1627 Dec  6 21:54 BeltContentPostSeeds.php

If I rename the missing file in my host system, it appears on my guest.

This issue appeared after upgrading my Mac OS to High Sierra 10.13.1. I had otherwise used this setup successfully for probably 2+ years.

I have since tried to upgrade the various related packages, as well as reinstalling various items, but it has not solved the issue so far. Downgrading my Mac OS to the previous version does not appear to be easy or straightforward.

Additional Detail:
 - sync type: NFS
 - VirtualBox: 5.1.30
 - Vagrant: 2.0.1
 - Vagrant Box: laravel/homestead
 - Vagrant Plugins: 'vagrant-bindfs' & 'vagrant-vbguest'


问:
jQuery HTML Anchor Tag Progressive Enhancement
I have jQuery that I have written that is supposed to find a particular  tag and change its behavior.  Before jQuery loads, the  tag has an href attribute that points to another page.  I am using jQuery to change the behavior of the  tag so that rather than directing the browser to load that other page, it instead runs javascript when clicked that loads content dynamically in a
 that is positioned at the location of the mouse pointer.

So, for example, I have the following:
```
<a class="funk" href="http://example.com/page2.html">Link</a>
<div class="hidden bubble">Load this instead.</div>
```
The jQuery I have running does the following:
```
$(document).ready(function(){
        $('.bubble').hide()
        $('.bubble').removeClass('hidden');
        $('.funk').attr('href', '#');</p>

```    $('.funk').click(function(e){
        $('.bubble').show();
    })
```

<p>})
```

The problem I have is: Whenever the user clicks the link, the browser acts on the href="#" attribute and brings scrolls the browser to the top of the page.  What is the most "correct" way to make my site so that the browser does not scroll at all, but instead merely executes the jQuery code that I have written for the click event?

答:
Let the 'click' function return false. That cancels the event, and the browser doesn't follow the link. In this case, you can even let the href attribute at its original value.

```<code>$('.funk').click(function(e){
    $('.bubble').show();
    return false;
//--^
})
</code>```

To be on the save side, you can explicitly cancel the event:

```<code>e.preventDefault(); // no default action
e.stopPropagation(); // event doesn't bubble up or down in the DOM
</code>```

Body:
I have jQuery that I have written that is supposed to find a particular  tag and change its behavior.  Before jQuery loads, the  tag has an href attribute that points to another page.  I am using jQuery to change the behavior of the  tag so that rather than directing the browser to load that other page, it instead runs javascript when clicked that loads content dynamically in a
 that is positioned at the location of the mouse pointer.

So, for example, I have the following:

Link

Load this instead.

The jQuery I have running does the following:

$(document).ready(function(){
        $('.bubble').hide()
        $('.bubble').removeClass('hidden');
        $('.funk').attr('href', '#');

    $('.funk').click(function(e){
        $('.bubble').show();
    })

})

The problem I have is: Whenever the user clicks the link, the browser acts on the href="#" attribute and brings scrolls the browser to the top of the page.  What is the most "correct" way to make my site so that the browser does not scroll at all, but instead merely executes the jQuery code that I have written for the click event?

Body:
Let the 'click' function return false. That cancels the event, and the browser doesn't follow the link. In this case, you can even let the href attribute at its original value.

$('.funk').click(function(e){
    $('.bubble').show();
    return false;
//--^
})

To be on the save side, you can explicitly cancel the event:

e.preventDefault(); // no default action
e.stopPropagation(); // event doesn't bubble up or down in the DOM


问:
Synchronization and Semaphore
I am Looping through a Map , and i have a number of threads.
the queue in the map contains Actions. my goal is to give every thread an Action to do.. but no 2 threads(or more) can run 2 task(or more) from  one queue
it means every thread is gonna search for a queue , and Lock the Queue some how and check if the queue has actions if yes it runs one of them if  no search for another Queue to run fro them actions.
NOTE: number of Queues can be greater than Number of Threads
  e
I tried to synchronize on the 'Map.Entry'

```<code>        public void run() {

            while (true) {
                Action<?> act;
                for (Map.Entry entry :ActionMap.entrySet()) {
                   Synchronized(entry)
                   {
                      act =  ((Queue<Action>)entry.getValue()).poll();
                      if (act == null)
                        break;
                   }
                }

            }
            }
</code>```

the problem is that if another thread is searching for an action to do is gonna be stuck in the synchronized Line And Wait for the first thread to finish the task or to finish waiting and  that is not what i want.
i want all of the threads to search for queues if some a thread reaches a queue that another thread is working on just skip it and continue searching

so I digged around and found semaphore  so I reached this

```<code>Semaphore Gate = new Semaphore(1);

        public void run() {

            while (true) {
                Action<?> act;
                for (Map.Entry entry :ActionMap.entrySet()) {
                   if( Gate.tryAcquire());
                   {
                      act =  ((Queue<Action>)entry.getValue()).poll();
                      if (act == null){
                    Gate.Release();
                    break;

                      }
                      else {
                      act.handle();
                      Gate.Release();
                    }
                   }
                }

            }
            }
</code>```

put the problem with this that  Gate.aquire() is gonna Lock all entries
it means for 2 diffirent entries and 2 different threads only one thread can access the gate and execute the Action

so finally dose any one have a design pattern that can help me ?
thank you ...

答:
You could use java.util.concurrent types of map for this. They are thread safe, so you dont need Syncronize.

Synchronize means : the resource(which is synchronized) can't be modified by multiple threads simultaneously. e.g MAP returned by Collections.synchronizedMap(Map) will be a synchronized map and can be modified by one thread at a time, but Concurrent Collections allows multiple threads to access different parts of a collection at a given time, based on the requirement. e.g we have an overloaded constructor for ConcurentHashMap which takes input concurrencyLevel as number of threads which can access the collection simultaneously.

Title: Synchronization and Semaphore

Body:
I am Looping through a Map , and i have a number of threads.
the queue in the map contains Actions. my goal is to give every thread an Action to do.. but no 2 threads(or more) can run 2 task(or more) from  one queue
it means every thread is gonna search for a queue , and Lock the Queue some how and check if the queue has actions if yes it runs one of them if  no search for another Queue to run fro them actions.
NOTE: number of Queues can be greater than Number of Threads
  e
I tried to synchronize on the 'Map.Entry'

        public void run() {

            while (true) {
                Action<?> act;
                for (Map.Entry entry :ActionMap.entrySet()) {
                   Synchronized(entry)
                   {
                      act =  ((Queue<Action>)entry.getValue()).poll();
                      if (act == null)
                        break;
                   }
                }

            }
            }

the problem is that if another thread is searching for an action to do is gonna be stuck in the synchronized Line And Wait for the first thread to finish the task or to finish waiting and  that is not what i want.
i want all of the threads to search for queues if some a thread reaches a queue that another thread is working on just skip it and continue searching

so I digged around and found semaphore  so I reached this

Semaphore Gate = new Semaphore(1);

        public void run() {

            while (true) {
                Action<?> act;
                for (Map.Entry entry :ActionMap.entrySet()) {
                   if( Gate.tryAcquire());
                   {
                      act =  ((Queue<Action>)entry.getValue()).poll();
                      if (act == null){
                    Gate.Release();
                    break;

                      }
                      else {
                      act.handle();
                      Gate.Release();
                    }
                   }
                }

            }
            }

put the problem with this that  Gate.aquire() is gonna Lock all entries
it means for 2 diffirent entries and 2 different threads only one thread can access the gate and execute the Action

so finally dose any one have a design pattern that can help me ?
thank you ...


问:
ADD a column to SQL table
I am trying to add a column to this query in SQL as below-</p>

答:
You can try do this :</p>

<p>            </p>

```<code>CUSIP=(Select TOP 1 gs.holdingsymbol
           from dbo.holdingsymbol_tbl gs where gs.holdingsymboltypeid=2)
</code>```

Title: ADD a column to SQL table

Body:
You can try do this :

CUSIP=(Select TOP 1 gs.holdingsymbol
           from dbo.holdingsymbol_tbl gs where gs.holdingsymboltypeid=2)


问:
Vectorising a Matlab code to pick specific indices of a matrix
I have a matrix A in Matlab of dimension Nx(N-1), e.g.

```<code>N=5;
A=[1  2  3  4;
   5  6  7  8;
   9  10 11 12;
   13 14 15 16;
   17 18 19 20];
</code>```

I want to rearrange the elements of A in a certain way. Specifically I want to create a matrix B of dimension (N-1)xN such that:

for i=1,...,N,

B(:,i) collects

1) the first i-1 elements of the i-1th column of A and

2) the last N-i elements of the ith column of A.

Notice that for i=1 the i-1th column of A does not exist and therefore 1) is skipped; similarly,  for i=N theith column of A does not exist and therefore 2) is skipped.

In the example above

```<code>B=[5  1  2  3  4
   9  10 6  7  8
   13 14 15 11 12
   17 18 19 20 16];
</code>```

This code does what I want. I am asking your help to vectorise it in an efficient way.

```<code>B=zeros(N-1,N);
for i=1:N
    if i>1 && i<N
    step1=A(1:i-1,i-1);
    step2=A(i+1:N,i);
    B(:,i)=[step1;step2];
    elseif i==1
    B(:,i)=A(i+1:N,i);
    elseif i==N
    B(:,i)=A(1:i-1,i-1);
    end
end
</code>```

答:
Another valid approach using logical indexing combined with tril and triu:

```<code>B = zeros(size(A'));
B(tril(true(size(B)))) = A(tril(true(size(A)), -1));
B(triu(true(size(B)), 1)) = A(triu(true(size(A))));
</code>```

Result:

```<code>>> B

B =

     5     1     2     3     4
     9    10     6     7     8
    13    14    15    11    12
    17    18    19    20    16
</code>```

Body:
I have a matrix A in Matlab of dimension Nx(N-1), e.g.

N=5;
A=[1  2  3  4;
   5  6  7  8;
   9  10 11 12;
   13 14 15 16;
   17 18 19 20];

I want to rearrange the elements of A in a certain way. Specifically I want to create a matrix B of dimension (N-1)xN such that:

for i=1,...,N,

B(:,i) collects

1) the first i-1 elements of the i-1th column of A and

2) the last N-i elements of the ith column of A.

Notice that for i=1 the i-1th column of A does not exist and therefore 1) is skipped; similarly,  for i=N theith column of A does not exist and therefore 2) is skipped.

In the example above

B=[5  1  2  3  4
   9  10 6  7  8
   13 14 15 11 12
   17 18 19 20 16];

This code does what I want. I am asking your help to vectorise it in an efficient way.

B=zeros(N-1,N);
for i=1:N
    if i>1 && i<N
    step1=A(1:i-1,i-1);
    step2=A(i+1:N,i);
    B(:,i)=[step1;step2];
    elseif i==1
    B(:,i)=A(i+1:N,i);
    elseif i==N
    B(:,i)=A(1:i-1,i-1);
    end
end

Body:
Another valid approach using logical indexing combined with tril and triu:

B = zeros(size(A'));
B(tril(true(size(B)))) = A(tril(true(size(A)), -1));
B(triu(true(size(B)), 1)) = A(triu(true(size(A))));

Result:

>> B

B =

     5     1     2     3     4
     9    10     6     7     8
    13    14    15    11    12
    17    18    19    20    16


问:
libcurl with libssh2 - one or more libs available at link-time are not available run-time
I get the following error when trying to ./configure libcurl 7.22.0

one or more libs available at link-time are not available run-time. Libs used at link-time: -lssh2 -lssl -lcrypto -lrt -lz

When I ./configure with --without-libssh2 it works just fine.

Steps I have taken:

```<code>apt-get install libssl-dev
apt-get install libssh-dev

cd /var
wget http://www.libssh2.org/download/libssh2-1.3.0.tar.gz
tar -zxvf libssh2-1.3.0.tar.gz
cd libssh2-1.3.0
./configure
make
make install
</code>```

SSL support works fine, by the way. I must have done something wrong with libssh

I have also tried:

```<code>./configure --with-libssh2
./configure --with-libssh2-path=/usr/local/lib
./configure --with-libssh2=/usr
./configure --with-libssh2=/usr/local/lib
</code>```

But it didn't make a difference. I don't know what else to try.

答:
check while openssl installed successly?

```<code>openssl version
</code>```

if not show version info, set openssl correctly
for example:

```<code>ln -s /usr/local/lib64/libssl.so.1.1 /usr/lib64/libssl.so.1.1
ln -s /usr/local/lib64/libcrypto.so.1.1 /usr/lib64/libcrypto.so.1.1
</code>```

and continue install curl, it work for me

Body:
I get the following error when trying to ./configure libcurl 7.22.0

one or more libs available at link-time are not available run-time. Libs used at link-time: -lssh2 -lssl -lcrypto -lrt -lz

When I ./configure with --without-libssh2 it works just fine.

Steps I have taken:

apt-get install libssl-dev
apt-get install libssh-dev

cd /var
wget http://www.libssh2.org/download/libssh2-1.3.0.tar.gz
tar -zxvf libssh2-1.3.0.tar.gz
cd libssh2-1.3.0
./configure
make
make install

SSL support works fine, by the way. I must have done something wrong with libssh

I have also tried:

./configure --with-libssh2
./configure --with-libssh2-path=/usr/local/lib
./configure --with-libssh2=/usr
./configure --with-libssh2=/usr/local/lib

But it didn't make a difference. I don't know what else to try.

Body:
check while openssl installed successly?

openssl version

if not show version info, set openssl correctly
for example:

ln -s /usr/local/lib64/libssl.so.1.1 /usr/lib64/libssl.so.1.1
ln -s /usr/local/lib64/libcrypto.so.1.1 /usr/lib64/libcrypto.so.1.1

and continue install curl, it work for me


答:
Add this to your click function:

```<code>$('.funk').click(function(e){
    e.preventDefault();
    e.stopPropagation();
    $('.bubble').show();
});
</code>```

This will do what is implied by the method names.

Title: jQuery HTML Anchor Tag Progressive Enhancement

Body:
Add this to your click function:

$('.funk').click(function(e){
    e.preventDefault();
    e.stopPropagation();
    $('.bubble').show();
});

This will do what is implied by the method names.


问:
Getting response from API using Alamofire
I am using Alamofire to get response from API to load data into tableviews however my alamofire functions works but only in some view controllers I dont understand what Im doing wrong. And i know its the alamofire function because i have used debuggers to follow my data and code but I saw the problem where the function never goes ahead of the first line of function.

Alamofire Function

```<code>Alamofire.request("\(baseURL)").responseJSON { response in
            if let dict = response.result.value as? [[String: Any]] {
                for obj in dict {
                    let latest = LatestNews(getLatest: obj)
                    self.moreNews.append(latest)
                }
            }
            self.tableView.reloadData()
        }
</code>```

Array and Model Class

```<code> var latestNews: LatestNews!

 var moreNews = [LatestNews]()
</code>```

答:
The issue that you are having.."it works in some view controllers, but not in others", is the result of the fact that you are reloading your tableView on a background thread.  You have to move it to the Main thread like so:</p>

```<code>    DispatchQueue.main.async {
       self.tableView.reloadData()
    }
</code>```

Body:
I am using Alamofire to get response from API to load data into tableviews however my alamofire functions works but only in some view controllers I dont understand what Im doing wrong. And i know its the alamofire function because i have used debuggers to follow my data and code but I saw the problem where the function never goes ahead of the first line of function.

Alamofire Function

Alamofire.request("\(baseURL)").responseJSON { response in
            if let dict = response.result.value as? [[String: Any]] {
                for obj in dict {
                    let latest = LatestNews(getLatest: obj)
                    self.moreNews.append(latest)
                }
            }
            self.tableView.reloadData()
        }

Array and Model Class

 var latestNews: LatestNews!

 var moreNews = [LatestNews]()

Body:
The issue that you are having.."it works in some view controllers, but not in others", is the result of the fact that you are reloading your tableView on a background thread.  You have to move it to the Main thread like so:

    DispatchQueue.main.async {
       self.tableView.reloadData()
    }


问:
wxpython set sizer background
i am using wxpython and trying to make an background to a sizer without any success, i searched in google without any results.

i try it with this boxsizer

```<code>wx.BoxSizer(wx.HORIZONTAL)
</code>```

答:
I just use panels for this sort of thing. You can set the color of the panel several different ways: you can use a named color, a wx.Color object, a predefined wx.Color object like wx.RED or a tuple of 3 integers.

Here's a simple example:

```<code>import wx

class MyPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        self.SetBackgroundColour('white')

        main_sizer = wx.BoxSizer(wx.VERTICAL)
        for number in range(5):
            btn = wx.Button(self, label='Button {}'.format(number))
            main_sizer.Add(btn, 0, wx.ALL, 5)

        self.SetSizer(main_sizer)

class MyFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title='Background colors')
        panel = MyPanel(self)
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()
</code>```

I wrote a little about this topic here:

https://www.blog.pythonlibrary.org/2009/09/03/wxpython-resetting-the-background-color/

You might also the wxPython wiki helpful:

https://wiki.wxpython.org/GettingStarted

Title: wxpython set sizer background

Body:
i am using wxpython and trying to make an background to a sizer without any success, i searched in google without any results.

i try it with this boxsizer

wx.BoxSizer(wx.HORIZONTAL)

Body:
I just use panels for this sort of thing. You can set the color of the panel several different ways: you can use a named color, a wx.Color object, a predefined wx.Color object like wx.RED or a tuple of 3 integers.

Here's a simple example:

import wx

class MyPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        self.SetBackgroundColour('white')

        main_sizer = wx.BoxSizer(wx.VERTICAL)
        for number in range(5):
            btn = wx.Button(self, label='Button {}'.format(number))
            main_sizer.Add(btn, 0, wx.ALL, 5)

        self.SetSizer(main_sizer)

class MyFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title='Background colors')
        panel = MyPanel(self)
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()

I wrote a little about this topic here:

https://www.blog.pythonlibrary.org/2009/09/03/wxpython-resetting-the-background-color/

You might also the wxPython wiki helpful:

https://wiki.wxpython.org/GettingStarted


问:
Disconnected: No supported authentication methods available (server > send: publickey)
I've launched an EC2 instance with Ubuntu 14 OS.

I'm trying to connect from a Windows 8 computer to my EC2 instance using PuTTY following the instructions, but when I click the Open button I receive the following error:

Disconnected: No supported authentication methods available (server
  send: publickey)

I'm quite sure I've made everything right according to the instructions (the ppk file etc).

This troubleshooting hasn't helped me because I have tried both ubuntu and root as username, e.g. ubuntu@ec2-12-345-678-90.eu-central-1.compute.amazonaws.com

I've also seen many questions on SO with the same error, but in all of them the author missed something that I have not.

I have really no idea what to do. Really hope someone will manage to help me.

答:
I recommend trying another SSH client such as MobaXterm, it supports pem

So you can run your command ssh -i /path/to/key.pem ubuntu@IP


问:
angularjs - Assigned value in controller but select field is still invalid
I have a select item that the values (multi-select) can be populated in the controller. But when I populate the value in the controller, the select still shows as invalid since this field is required.

Markup as per below.

```<code><div ng-controller="host.views.newAnnouncement.index as vm">
<div class="portlet light bordered" id="form_wizard_1">
    <div class="portlet-title">
        <div class="caption">
            <i class=" icon-speech font-blue"></i>
            <span class="caption-subject font-blue bold">
                New Announcement
            </span>
        </div>
    </div>
    <div class="portlet-body">
        <div class="col-md-12">
            <div class="alert alert-danger" ng-show="vm.isInError">
                <p ng-repeat="message in vm.errorMessages">{{message}}</p>
            </div>
            <ng-form name="vm.announcementForm">

                <div class="form-group form-md-line-input form-md-floating-label no-hint"
                     ng-class="{'has-error': (vm.announcementForm.announcementTypes.$dirty || vm.isValidated) && vm.announcementForm.announcementTypes.$invalid}">
                    <select class="form-control" name="announcementTypes" id="announcementTypes"
                            ng-class="{'edited': vm.model.announcementType}"
                            ng-model="vm.model.announcementType"
                            ng-options="announcementType.id as announcementType.name for announcementType in vm.announcementTypes"
                            required></select>
                    <label for="announcementTypes">Announcement Type</label>
                </div>

                <div class="form-group form-md-line-input no-hint"
                     ng-class="{'has-error': (vm.announcementForm.audienceTypes.$dirty || vm.isValidated) && vm.announcementForm.audienceTypes.$invalid}">
                    <select class="form-control" name="audienceTypes" id="audienceTypes"
                            ng-class="{'edited': vm.model.audienceType}"
                            ng-model="vm.model.audienceType"
                            ng-options="audienceType.id as audienceType.name for audienceType in vm.audienceTypes"
                            ng-change="vm.onAudienceTypeChange()"
                            required></select>
                    <label for="audienceTypes">Audience Type</label>
                </div>

                <div class="form-group form-md-line-input no-hint"
                     ng-class="{'has-error': (vm.announcementForm.audiences.$dirty || vm.isValidated) && vm.announcementForm.audiences.$invalid}">
                    <select class="form-control" name="audiences" id="audiences"
                            ng-class="{'edited': vm.model.audiences}"
                            ng-model="vm.model.audiences"
                            ng-options="audience.id as audience.name for audience in vm.audienceList | orderBy:'name'"
                            multiple required
                            style="min-height:300px;"></select>
                    <label for="audiences">Audience List <span ng-if="vm.model.audiences.length > 0">(Selected: {{vm.model.audiences.length}})</span></label>
                </div>

                <div class="form-group form-md-line-input form-md-floating-label no-hint"
                     ng-class="{'has-error': (vm.announcementForm.subject.$dirty || vm.isValidated) && vm.announcementForm.subject.$invalid}">
                    <input type="text" name="subject" class="form-control" ng-class="{'edited':vm.model.subject}" ng-model="vm.model.subject" maxlength="50" required>
                    <label>Subject</label>
                </div>
                <br />
                <div class="form-group">
                    <label>Details</label>
                    <text-angular ta-text-editor-class="form-content" ta-html-editor-class="form-content" ng-model="vm.model.body"></text-angular>
                </div>

                <div class="row form-group col-md-12">
                    <label class="control-label">Attachement (zip)</label>
                    <input name="file" type="file" id="attachements" nv-file-select="" uploader="vm.fileUploader" accept=".zip"/>
                </div>
            </ng-form>
        </div>
        <hr />
        <div class="row">
            <div class="col-md-12">
                <button type="button" class="btn default button-previous" ng-click="vm.back()">
                    <i class="fa fa-angle-left"></i> Back
                </button>
                <button type="button" class="btn green button-submit"
                        button-busy="vm.saving"
                        busy-text="@L("SavingWithThreeDot")"
                        ng-click="vm.submit()"
                        ng-disabled="vm.announcementForm.$invalid">
                    Submit
                    <i class="fa fa-check"></i>
                </button>
            </div>
        </div>
    </div>
</div>
</code>```

Controller

```<code>    (function () {
    appModule.controller('host.views.newAnnouncement.index', [
        '$scope', '$state', 'FileUploader', 'abp.services.app.hostAnnouncement', 'abp.services.app.hostSettings',
        function ($scope, $state, FileUploader, announcementService, hostSettingsService) {
            var vm = this;

            vm.model = {
                subject: '',
                body: '',
                announcementType: null,
                audienceType: 0,
                audiences: [],
                feedbackId: null
            };

            vm.audienceList = [];

            vm.announcementTypes = [
                { id: 0, name: 'General' },
                { id: 1, name: 'Penalty Invoice' },
                { id: 2, name: 'Other' }
            ];

            vm.audienceTypes = [
                { id: 0, name: 'By Tenant' },
                { id: 1, name: 'By Store Category' },
                { id: 2, name: 'By Floor Location' },
                { id: 3, name: 'By Zone' }
            ];

            vm.fileUploader = new FileUploader({
                url: abp.appPath + 'AnnouncementDocument/UploadFileAsync',
                filters: [
                    {
                        'name': 'enforceMaxFileSize',
                        'fn': function (item) {
                            return item.size <= 2097152; // 2 MiB to bytes
                        }
                    }
                ]
            });

            vm.submit = submit;
            vm.back = back;

            vm.onAudienceTypeChange = onAudienceTypeChange;

            initialize();

            vm.errorMessages = [];

            vm.tenants = [];
            vm.storeCategories = [];
            vm.floorLocations = [];
            vm.zones = [];

            vm.announcementData = {
                announcementId: null,
                setAnnouncementId: function (announcementId) {
                    this.announcementId = announcementId;
                }
            }

            function onAudienceTypeChange() {
                vm.model.audiences = [];
                if (vm.model.audienceType === 0) {
                    vm.audienceList = vm.tenants;
                } else if (vm.model.audienceType === 1) {
                    vm.audienceList = vm.storeCategories;
                } else if (vm.model.audienceType === 2) {
                    vm.audienceList = vm.floorLocations;
                } else if (vm.model.audienceType === 3) {
                    vm.audienceList = vm.zones;
                }
            }

            function initialize() {
                vm.loading = true;
                hostSettingsService.getAllSettings()
                    .success(function (result) {
                        _.each(result.storeCategories.split("|"), function (item) {
                            if (item !== "") {
                                vm.storeCategories.push({
                                    name: item,
                                    id: item
                                });
                            }
                        });

                        _.each(result.floorLocations.split("|"), function (item) {
                            if (item !== "") {
                                vm.floorLocations.push({
                                    name: item,
                                    id: item
                                });
                            }
                        });

                        _.each(result.zones.split("|"), function (item) {
                            if (item !== "") {
                                vm.zones.push({
                                    name: item,
                                    id: item
                                });
                            }
                        });

                    }).finally(function () {
                        announcementService.getTenants()
                            .success(function (result) {
                                vm.tenants = result;
                                vm.audienceList = vm.tenants;
                            }).finally(function () {
                                vm.loading = false;
                                autoSelectTenant($state.params);
                            });
                    });
            }

            function autoSelectTenant(stateParams) {
                if (stateParams.tenantId && stateParams.feedbackId) {
                    vm.model.feedbackId = stateParams.feedbackId;
                    vm.model.audienceType = 0;
                    vm.model.audiences.push(stateParams.tenantId);
                }
            }

            function submit() {
                validate();
                if (vm.isInError) return;

                vm.saving = true;
                vm.isValidated = true;

                announcementService.createAnnouncementAsync(vm.model)
                    .success(function (announcementId) {
                        if (vm.fileUploader.queue.length > 0) {
                            vm.announcementData.setAnnouncementId(announcementId);
                            vm.fileUploader.uploadAll();
                        } else {
                            showSuccessNotification();
                        }
                    });
            }

            function back() {
                $state.go('host.announcement');
            }

            function validate() {
                vm.isInError = false;
                vm.errorMessages = [];
                if (vm.model.audiences.length < 1) {
                    vm.errorMessages.push("Please select an audience list.");
                    vm.isInError = true;
                }

                vm.isValidated = true;
            }

            vm.fileUploader.onBeforeUploadItem = function (fileItem) {
                fileItem.formData.push(vm.announcementData);
            };

            vm.fileUploader.onCompleteAll = function () {
                showSuccessNotification();
            };

            function showSuccessNotification() {
                $state.go('host.announcement');
                vm.saving = false;
                abp.notify.success("Announcement has been successfully published.");
            }
        }
    ]);
})();
</code>```

How do I programmatically set the selection values from the controller and make sure that the field is not invalid? The audiences value is being passes through the $state.params and I've added it to the vm.model.audiences array. But in the UI, vm.model.audiences is still marked as required even though it had values already.

EDIT : I've updated my question with full html and controller. For more clear understanding.

答:
Try like this

var app = angular.module("app", []);

app.controller('mainCtrl', function($scope) {
  var vm = this;
  vm.model = {
    audiences: []
  };
  vm.audienceList = [{
    "name": "name1",
    "id": 1
  }, {
    "name": "name2",
    "id": 2
  }, {
    "name": "name3",
    "id": 3
  }];

  vm.stateParams = {};
  vm.stateParams.tenantId = 1;
  vm.stateParams.feedbackId = 1;

  vm.autoSelectTenant = function(stateParams) {
    if (stateParams.tenantId && stateParams.feedbackId) {
      vm.model.feedbackId = stateParams.feedbackId;
      vm.model.audienceType = 0;
      vm.model.audiences.push(stateParams.tenantId);
    }
  }

  vm.autoSelectTenant(vm.stateParams);

  vm.stateParams.tenantId = 2;
  vm.stateParams.feedbackId = 2;

  vm.autoSelectTenant(vm.stateParams);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" />

<div ng-app="app" ng-controller="mainCtrl as vm">
  <select ng-model="vm.model.audiences" ng-options="audience.id as audience.name for audience in vm.audienceList | orderBy:'name'" multiple required></select>
</div></code>```

Body:
I have a select item that the values (multi-select) can be populated in the controller. But when I populate the value in the controller, the select still shows as invalid since this field is required.

Markup as per below.

                New Announcement

{{message}}

            <ng-form name="vm.announcementForm">

                    <select class="form-control" name="announcementTypes" id="announcementTypes"
                            ng-class="{'edited': vm.model.announcementType}"
                            ng-model="vm.model.announcementType"
                            ng-options="announcementType.id as announcementType.name for announcementType in vm.announcementTypes"
                            required></select>
                    Announcement Type

                    <select class="form-control" name="audienceTypes" id="audienceTypes"
                            ng-class="{'edited': vm.model.audienceType}"
                            ng-model="vm.model.audienceType"
                            ng-options="audienceType.id as audienceType.name for audienceType in vm.audienceTypes"
                            ng-change="vm.onAudienceTypeChange()"
                            required></select>
                    Audience Type

                    <select class="form-control" name="audiences" id="audiences"
                            ng-class="{'edited': vm.model.audiences}"
                            ng-model="vm.model.audiences"
                            ng-options="audience.id as audience.name for audience in vm.audienceList | orderBy:'name'"
                            multiple required
                            style="min-height:300px;"></select>
                    Audience List  0">(Selected: {{vm.model.audiences.length}})

                    <input type="text" name="subject" class="form-control" ng-class="{'edited':vm.model.subject}" ng-model="vm.model.subject" maxlength="50" required>
                    Subject

                    Details
                    <text-angular ta-text-editor-class="form-content" ta-html-editor-class="form-content" ng-model="vm.model.body"></text-angular>

                    Attachement (zip)
                    <input name="file" type="file" id="attachements" nv-file-select="" uploader="vm.fileUploader" accept=".zip"/>

            </ng-form>

                <button type="button" class="btn default button-previous" ng-click="vm.back()">
                     Back
                </button>
                <button type="button" class="btn green button-submit"
                        button-busy="vm.saving"
                        busy-text="@L("SavingWithThreeDot")"
                        ng-click="vm.submit()"
                        ng-disabled="vm.announcementForm.$invalid">
                    Submit

                </button>

Controller

    (function () {
    appModule.controller('host.views.newAnnouncement.index', [
        '$scope', '$state', 'FileUploader', 'abp.services.app.hostAnnouncement', 'abp.services.app.hostSettings',
        function ($scope, $state, FileUploader, announcementService, hostSettingsService) {
            var vm = this;

            vm.model = {
                subject: '',
                body: '',
                announcementType: null,
                audienceType: 0,
                audiences: [],
                feedbackId: null
            };

            vm.audienceList = [];

            vm.announcementTypes = [
                { id: 0, name: 'General' },
                { id: 1, name: 'Penalty Invoice' },
                { id: 2, name: 'Other' }
            ];

            vm.audienceTypes = [
                { id: 0, name: 'By Tenant' },
                { id: 1, name: 'By Store Category' },
                { id: 2, name: 'By Floor Location' },
                { id: 3, name: 'By Zone' }
            ];

            vm.fileUploader = new FileUploader({
                url: abp.appPath + 'AnnouncementDocument/UploadFileAsync',
                filters: [
                    {
                        'name': 'enforceMaxFileSize',
                        'fn': function (item) {
                            return item.size <= 2097152; // 2 MiB to bytes
                        }
                    }
                ]
            });

            vm.submit = submit;
            vm.back = back;

            vm.onAudienceTypeChange = onAudienceTypeChange;

            initialize();

            vm.errorMessages = [];

            vm.tenants = [];
            vm.storeCategories = [];
            vm.floorLocations = [];
            vm.zones = [];

            vm.announcementData = {
                announcementId: null,
                setAnnouncementId: function (announcementId) {
                    this.announcementId = announcementId;
                }
            }

            function onAudienceTypeChange() {
                vm.model.audiences = [];
                if (vm.model.audienceType === 0) {
                    vm.audienceList = vm.tenants;
                } else if (vm.model.audienceType === 1) {
                    vm.audienceList = vm.storeCategories;
                } else if (vm.model.audienceType === 2) {
                    vm.audienceList = vm.floorLocations;
                } else if (vm.model.audienceType === 3) {
                    vm.audienceList = vm.zones;
                }
            }

            function initialize() {
                vm.loading = true;
                hostSettingsService.getAllSettings()
                    .success(function (result) {
                        _.each(result.storeCategories.split("|"), function (item) {
                            if (item !== "") {
                                vm.storeCategories.push({
                                    name: item,
                                    id: item
                                });
                            }
                        });

                        _.each(result.floorLocations.split("|"), function (item) {
                            if (item !== "") {
                                vm.floorLocations.push({
                                    name: item,
                                    id: item
                                });
                            }
                        });

                        _.each(result.zones.split("|"), function (item) {
                            if (item !== "") {
                                vm.zones.push({
                                    name: item,
                                    id: item
                                });
                            }
                        });

                    }).finally(function () {
                        announcementService.getTenants()
                            .success(function (result) {
                                vm.tenants = result;
                                vm.audienceList = vm.tenants;
                            }).finally(function () {
                                vm.loading = false;
                                autoSelectTenant($state.params);
                            });
                    });
            }

            function autoSelectTenant(stateParams) {
                if (stateParams.tenantId && stateParams.feedbackId) {
                    vm.model.feedbackId = stateParams.feedbackId;
                    vm.model.audienceType = 0;
                    vm.model.audiences.push(stateParams.tenantId);
                }
            }

            function submit() {
                validate();
                if (vm.isInError) return;

                vm.saving = true;
                vm.isValidated = true;

                announcementService.createAnnouncementAsync(vm.model)
                    .success(function (announcementId) {
                        if (vm.fileUploader.queue.length > 0) {
                            vm.announcementData.setAnnouncementId(announcementId);
                            vm.fileUploader.uploadAll();
                        } else {
                            showSuccessNotification();
                        }
                    });
            }

            function back() {
                $state.go('host.announcement');
            }

            function validate() {
                vm.isInError = false;
                vm.errorMessages = [];
                if (vm.model.audiences.length < 1) {
                    vm.errorMessages.push("Please select an audience list.");
                    vm.isInError = true;
                }

                vm.isValidated = true;
            }

            vm.fileUploader.onBeforeUploadItem = function (fileItem) {
                fileItem.formData.push(vm.announcementData);
            };

            vm.fileUploader.onCompleteAll = function () {
                showSuccessNotification();
            };

            function showSuccessNotification() {
                $state.go('host.announcement');
                vm.saving = false;
                abp.notify.success("Announcement has been successfully published.");
            }
        }
    ]);
})();

How do I programmatically set the selection values from the controller and make sure that the field is not invalid? The audiences value is being passes through the $state.params and I've added it to the vm.model.audiences array. But in the UI, vm.model.audiences is still marked as required even though it had values already.

EDIT : I've updated my question with full html and controller. For more clear understanding.

Body:
Try like this

var app = angular.module("app", []);

app.controller('mainCtrl', function($scope) {
  var vm = this;
  vm.model = {
    audiences: []
  };
  vm.audienceList = [{
    "name": "name1",
    "id": 1
  }, {
    "name": "name2",
    "id": 2
  }, {
    "name": "name3",
    "id": 3
  }];

  vm.stateParams = {};
  vm.stateParams.tenantId = 1;
  vm.stateParams.feedbackId = 1;

  vm.autoSelectTenant = function(stateParams) {
    if (stateParams.tenantId && stateParams.feedbackId) {
      vm.model.feedbackId = stateParams.feedbackId;
      vm.model.audienceType = 0;
      vm.model.audiences.push(stateParams.tenantId);
    }
  }

  vm.autoSelectTenant(vm.stateParams);

  vm.stateParams.tenantId = 2;
  vm.stateParams.feedbackId = 2;

  vm.autoSelectTenant(vm.stateParams);

});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" />

<div ng-app="app" ng-controller="mainCtrl as vm">
  <select ng-model="vm.model.audiences" ng-options="audience.id as audience.name for audience in vm.audienceList | orderBy:'name'" multiple required></select>
</div>


问:
Cannot find "Paste Special" option in Visual Studio 2017
I cannot see the Paste Special option in my Visual Studio 2017 Professional Edition:

Microsoft Visual Studio Professional 2017

Version 15.4.5

VisualStudio.15.Release/15.4.5+27004.2010

Microsoft .NET Framework

Version 4.7.02046

In this blog post it is shown for Visual Studio 2013. On my machine, the edit menu appears as below:

Is there a way to get back the option? Do I need to enable this option somehow?

答: I have missed an important step. There is nothing wrong in Visual Studio 2017. I was not in a .cs file.</p>


问:
Is it safe using `$` as an identifier in C/C++?
Is it safe to use $ character as part of identifier in C/C++?
Like this,

```<code>int $a = 10;
struct $b;
class $c;

void $d();
</code>```

答: No. The C standard only guarantees the use of uppercase and lowercase English letters, digits, _, and Unicode codepoints specified using \u (hex-quad) or \U (hex-quad) (hex-quad) (with a few exceptions). Specific compilers may allow other characters as an extension; however this is highly nonportable. (ISO/IEC 9899:1999 (E) 6.4.2.1, 6.4.3) Further note that the Unicode codepoint method is basically useless in identifiers, even though it is, strictly speaking, permitted (in C99), as it still shows up as a literal \uXXXX in your editor.

Body:
Is it safe to use $ character as part of identifier in C/C++?
Like this,

int $a = 10;
struct $b;
class $c;

void $d();


问:
<input type="radio"> does not line up with <text></text> behind it
My
<input type="radio">

in my form does not line up with my
<text></text>

behind it.

Example of my form

答:
First of all you shouldn't use <text>, as DaFois said. Use  instead

label {
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>
  <input type="radio">
  Label Text
</label></code>```

Body:
First of all you shouldn't use <text>, as DaFois said. Use <label> instead

label {
  display: flex;
}

<label>
  <input type="radio">
  Label Text
</label>


问:
Collection.find({key: any_value in an array }) matching multiple values with mongoose

Hi, I have a "Tweets" Schema, which has a key of "author" and I would like to find all tweets whose author is any value in an array of people. For instance,

if I could do something like:

let people = ['josh','bob','tim'];

```<code>Tweet.find({ author: [people] }).then((tweets) => {
      // tweets = all tweets that have any of the following authors: josh, bob, or time
})
</code>```

Essentially, is there a mongoose specific way to do:

```<code>people.forEach((person)=> {
   Tweet.find({ author: person})
})
</code>```

Also note that the 'people' array changes per user that is logged in/session user.

答:
it's so simple try </p>

```<code> Tweet.find({
// sorry it should be in
    author: {$in:  [people] }
 })
 .then((tweets) => {
})
</code>```

Body:
Hi, I have a "Tweets" Schema, which has a key of "author" and I would like to find all tweets whose author is any value in an array of people. For instance,

if I could do something like:

let people = ['josh','bob','tim'];

Tweet.find({ author: [people] }).then((tweets) => {
      // tweets = all tweets that have any of the following authors: josh, bob, or time
})

Essentially, is there a mongoose specific way to do:

people.forEach((person)=> {
   Tweet.find({ author: person})
})

Also note that the 'people' array changes per user that is logged in/session user.

Body:
it's so simple try

 Tweet.find({
// sorry it should be in
    author: {$in:  [people] }
 })
 .then((tweets) => {
})


问:
How to remove elements in a vector that match some element in another vector
I want to remove elements in a vector v2 that match the elements in another vector v1, where each element in v1 has a corresponding element in v2 but not vice versa.

My idea is to use std::vector::erase, std::remove_if and std::find like this:

```<code>std::vector<int> v1{ 6, 2, 4 };
std::vector<int> v2{ 8, 2, 9, 4, 5, 3, 7, 1, 6 };

v2.erase(
  std::remove_if(v2.begin(), v2.end()
  , [&v1](auto& item)
  {
    return std::find(v1.begin(), v1.end(), item) != v1.end();
  })
);
</code>```

Which works.  However, I wonder if I could do without matching those that have already been matched as this is a 1:1 relationship when going from v1 -> v2.  v1 will be blown away afterwards, so it can be modified.

答:
You can achieve linear complexity for solving your problem but with extra memory.  You can transfer the first vector to hash (unordered_set). So as result you get O(N) complexity ( excluding efforts for creating hash )

```<code>std::vector<int> v1{ 6, 2, 4 };
std::vector<int> v2{ 8, 2, 9, 4, 5, 3, 7, 1, 6 };

std::unordered_set<int> hash_v1( v1.begin(), v1.end() );

// linear complexity for remove_if
v2.erase( std::remove_if( v2.begin(), v2.end(), [&hash_v1] ( auto& item )
{
    return hash_v1.find( item ) != hash_v1.end(); // constant time
}), v2.end());
</code>```

And do not forget about v2.end() as second parameter for ease method.

Body:
I want to remove elements in a vector v2 that match the elements in another vector v1, where each element in v1 has a corresponding element in v2 but not vice versa.

My idea is to use std::vector::erase, std::remove_if and std::find like this:

std::vector<int> v1{ 6, 2, 4 };
std::vector<int> v2{ 8, 2, 9, 4, 5, 3, 7, 1, 6 };

v2.erase(
  std::remove_if(v2.begin(), v2.end()
  , [&v1](auto& item)
  {
    return std::find(v1.begin(), v1.end(), item) != v1.end();
  })
);

Which works.  However, I wonder if I could do without matching those that have already been matched as this is a 1:1 relationship when going from v1 -> v2.  v1 will be blown away afterwards, so it can be modified.

Body:
You can achieve linear complexity for solving your problem but with extra memory.  You can transfer the first vector to hash (unordered_set). So as result you get O(N) complexity ( excluding efforts for creating hash )

std::vector<int> v1{ 6, 2, 4 };
std::vector<int> v2{ 8, 2, 9, 4, 5, 3, 7, 1, 6 };

std::unordered_set<int> hash_v1( v1.begin(), v1.end() );

// linear complexity for remove_if
v2.erase( std::remove_if( v2.begin(), v2.end(), [&hash_v1] ( auto& item )
{
    return hash_v1.find( item ) != hash_v1.end(); // constant time
}), v2.end());

And do not forget about v2.end() as second parameter for ease method.