问:
mysql uses "on update" and sets a default albeit I never told it to do so
I executed the following query on my mysql server:

```<code>CREATE TABLE user(
  created_at timestamp NOT NULL,
  updated_at timestamp NOT NULL,
  id integer NOT NULL AUTO_INCREMENT PRIMARY KEY,
  count integer NOT NULL,
  name varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci
</code>```

When I looked into phpmyadmin I was suprised.
The created_at column had a default set to CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP was also there.

How can this even happen?
It shouldnt do that, right?

答:
Although this behavior is surprising to me, it is actually explained in the documentation:

For any TIMESTAMP or DATETIME column in a table, you can assign the
  current timestamp as the default value, the auto-update value, or
  both:

An auto-initialized column is set to the current timestamp for inserted rows that specify no value for the column.

An auto-updated column is automatically updated to the current timestamp when the value of any other column in the row is changed
  from its current value. An auto-updated column remains unchanged if
  all other columns are set to their current values. To prevent an
  auto-updated column from updating when other columns change,
  explicitly set it to its current value. To update an auto-updated
  column even when other columns do not change, explicitly set it to the
  value it should have (for example, set it to CURRENT_TIMESTAMP).

Body:
I executed the following query on my mysql server:

CREATE TABLE user(
  created_at timestamp NOT NULL,
  updated_at timestamp NOT NULL,
  id integer NOT NULL AUTO_INCREMENT PRIMARY KEY,
  count integer NOT NULL,
  name varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci

When I looked into phpmyadmin I was suprised.
The created_at column had a default set to CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP was also there.

How can this even happen?
It shouldnt do that, right?


来源: stackexchange

问:
Google PlayStore console 2017 - obb extension file upload
I am using APK with external OBB Extension file.

PlayStore Console UI has changed since I used this feature last.
I can not figure out how to upload the OBB file.

Even the PlayStore help describes the wrong, old way.

https://support.google.com/googleplay/android-developer/answer/2481797?hl=de

Can someone please give me a hint.

Seems to be solved - the small + button was missing in the German UI Version. I changed my language to English and the + button was there. Now in 2018 the + button is also visible in the German UI. Thanx Google

答:
In this case you have tu use the JOBB tool to encapsulate the resource files, having your .APK then you can go to https://play.google.com/apps/publish/

then Release management > App Releases , you have the option to test your app first MANAGE ALPHA or MANAGE BETA or publish directly to producction MANAGE PRODUCTION, create a Draft Release.

And then Add or change expansion files
You can upload new or add existing expansion files to APKs in a draft release.

Go to your Play Console.

Select your app.

On the left menu, click Release management > App releases.

Next to the release type you want to update, select Manage.

Drop or select your app's APK file.

You'll see a list of APKs that are associated with your release. Next to the relevant version code, select the add icon .

Choose whether you want to upload a new file or attach an existing expansion file.

If the APK hasn't been published yet, you can change or remove an expansion file by selecting another file or No expansion file. You
  can't remove expansion files from an existing release.

Select Save.

This is the current documentation for APK Expansion Files

Read the checklist to use Expansion files in your application:

Development checklist

Here's a summary of the tasks you should perform
  to use expansion files with your application:

First determine whether your application absolutely requires more than 100MB per installation. Space is precious and you should keep
  your total application size as small as possible. If your app uses
  more than 100MB in order to provide multiple versions of your graphic
  assets for multiple screen densities, consider instead publishing
  multiple APKs in which each APK contains only the assets required for
  the screens that it targets.

Determine which application resources to separate from your APK and package them in a file to use as the main expansion file. Normally,
  you should only use the second patch expansion file when performing
  updates to the main expansion file. However, if your resources exceed
  the 2GB limit for the main expansion file, you can use the patch file
  for the rest of your assets.

Develop your application such that it uses the resources from your expansion files in the device's shared storage location. Remember that
  you must not delete, move, or rename the expansion files. If your
  application doesn't demand a specific format, we suggest you create
  ZIP files for your expansion files, then read them using the APK
  Expansion Zip Library.

Add logic to your application's main activity that checks whether the expansion files are on the device upon start-up. If the files are
  not on the device, use Google Play's Application Licensing service to
  request URLs for the expansion files, then download and save them. To
  greatly reduce the amount of code you must write and ensure a good
  user experience during the download, we recommend you use the
  Downloader Library to implement your download behavior. If you build
  your own download service instead of using the library, be aware that
  you must not change the name of the expansion files and must save them
  to the proper storage location.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
How to evaluate a JavaScript function from a text input

I have an in-browser particle engine running in THREE.js. I want to add animation functionality, so I have a text input that will contain code, which should be called from my "animate" function which updates the position and other information of the particle emitters.
https://i.imgur.com/vguWZAq.jpg

```<code>function animate() {

    time = Date.now();

    runCustomAnimateScript();

    for(var i = 0; i < emitters.length; i++){
        emitters[i].updateParticles(deltaTime);
    }

    render();

    requestAnimationFrame( animate );
}

function runCustomAnimateScript(){
    //Filled from text input after updateCustomAnimateScript is called
    //Called from within animate (which is run every frame)
}

function updateCustomAnimateScript(){
    //Parse document.querySelectorAll("textarea[name='customAnimateScript']").value
    //into a script, and enter it into runCustomAnimateScript
}
</code>```

Currently I have no way to turn this text input into an executable JavaScript function. I'm surprised that nobody has tried to do this before, or at least posted about it?

Body:
I have an in-browser particle engine running in THREE.js. I want to add animation functionality, so I have a text input that will contain code, which should be called from my "animate" function which updates the position and other information of the particle emitters.
https://i.imgur.com/vguWZAq.jpg

function animate() {

    time = Date.now();

    runCustomAnimateScript();

    for(var i = 0; i < emitters.length; i++){
        emitters[i].updateParticles(deltaTime);
    }

    render();

    requestAnimationFrame( animate );
}

function runCustomAnimateScript(){
    //Filled from text input after updateCustomAnimateScript is called
    //Called from within animate (which is run every frame)
}

function updateCustomAnimateScript(){
    //Parse document.querySelectorAll("textarea[name='customAnimateScript']").value
    //into a script, and enter it into runCustomAnimateScript
}

Currently I have no way to turn this text input into an executable JavaScript function. I'm surprised that nobody has tried to do this before, or at least posted about it?

Body:
For completeness, another way to do this is to create a <script> tag, set the body of the script to the user's code, and attach the script to the DOM:

document.querySelector("button").addEventListener("click", e => {
  e.preventDefault();
  const script = document.createElement("script");
  script.innerHTML = document.querySelector("textarea").value;
  document.body.appendChild(script);
  document.body.removeChild(script);
});

textarea {
  width: 500px;
  height: 10em;
}

<textarea></textarea><button type="button">Run</button>

Just be careful.  Both this method and eval() can open you up to code injection attacks.


问:
MVC: Search by name of the video
Hi I have a question how can I improve my code that I can search through my database by putting at least one letter in textbox not all the title. Now it's searching but I need to put whole title to search something.

My search bar:

```<code>@using (Html.BeginForm("SearchVideo", "Video", FormMethod.Post, new { @class = "navbar-form navbar-left", @role = "search" }))
                    {
                        <div class="form-group">
                            @Html.TextBox("searchVideo", (object)null, new { @class = "form-control", @placeholder = "Wyszukaj film" })
                        </div>
                        <button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
                    }
</code>```

My VideoListViewModel:

```<code>public class VideoListViewModel
{
    public IEnumerable<Video> VideoList { get; set; }
}
</code>```

My searching View:

```<code>    <div class="list-group">
        @foreach (var video in Model.VideoList)
        {
            <a href="/Video/GetVideo?id=@video.Id" class="list-group-item clearfix">
                <img src="~/Images/@video.ImageUrl" style="width: 80px; height: 100px; padding: 5px;" />
                Premiere: @video.Date
                <br/>
            </a>
            <br/>
        }
    </div>
</code>```

答:
You can use the Contains method inside your where clause

```<code>return db.Video.Where(x => x.VideoName.Contains(search));
</code>```

Contains method returns true when a string exist anywhere in the other string. If you are looking to get the records where the VideoName starts with the search parameter value ,you may use StartsWith method.

```<code>return db.Video.Where(x => x.VideoName.StartsWith(search));
</code>```

Title: MVC: Search by name of the video

Body:
Hi I have a question how can I improve my code that I can search through my database by putting at least one letter in textbox not all the title. Now it's searching but I need to put whole title to search something.

My search bar:

@using (Html.BeginForm("SearchVideo", "Video", FormMethod.Post, new { @class = "navbar-form navbar-left", @role = "search" }))
                    {

                            @Html.TextBox("searchVideo", (object)null, new { @class = "form-control", @placeholder = "Wyszukaj film" })

                        <button class="btn btn-default" type="submit"></button>
                    }

My VideoListViewModel:

public class VideoListViewModel
{
    public IEnumerable<Video> VideoList { get; set; }
}

My searching View:

        @foreach (var video in Model.VideoList)
        {

                Premiere: @video.Date

        }

Body:
You can use the Contains method inside your where clause

return db.Video.Where(x => x.VideoName.Contains(search));

Contains method returns true when a string exist anywhere in the other string. If you are looking to get the records where the VideoName starts with the search parameter value ,you may use StartsWith method.

return db.Video.Where(x => x.VideoName.StartsWith(search));


问:
What's Is the Best File Format for Configuration Files
I am creating a framework in PHP and need to have a few configuration files. Some of these files will unavoidably have a large number of entries.

What format would be the best for these config files?

Here is my quantification of best:

Easily parsed by PHP. It would be nice if I didn't have to write any parsing code but this is not a deal breaker.

Remains easily read by humans even when there are a large amount of entries

Is a widely used standard, no custom formats

Succinctness is appreciated

I started out using XML, but quickly gave up for obvious reasons. I've thought of JSON and YAML but wanted to see what else is out there.

答:
Personly I like to do config data in a class.

```<code>class appNameConfig {
    var $dbHost = 'localhost';
    var $dbUser = 'root';
    //...
 }
</code>```

then to use them all you have to do is

```<code>$config = new appNameConfig;
mysql_connect($config->dbHost, $config->dbUser, $config->dbPassword) or die(/*...*/);
</code>```

to change the config all you have to do is read the file with the class in it I use a function like this:

```<code>function updateConfig($parameter, $value) {
    $fh = fopen('config.php', 'w+');
    while(!feof($fh)) {
        $file .= fgets($fh);
     }
    $fileLines = explode("\n", $file);
    for($i=0;$i<count($fileLines);$i++) {
        if(strstr($fileLines[$i], $parameter)) {
            $fileLines[$i] = "$" . $parameter . " = '" . $value . "'";
         }
     }
    $file = implode("\n", $fileLines);
    fwrite($fh, $file);
    fclose($fh);
 }
</code>```

OwnerDisplayName: macinjosh

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: InSciTek Jeff

Body:
Personly I like to do config data in a class.

class appNameConfig {
    var $dbHost = 'localhost';
    var $dbUser = 'root';
    //...
 }

then to use them all you have to do is

$config = new appNameConfig;
mysql_connect($config->dbHost, $config->dbUser, $config->dbPassword) or die(/*...*/);

to change the config all you have to do is read the file with the class in it I use a function like this:

function updateConfig($parameter, $value) {
    $fh = fopen('config.php', 'w+');
    while(!feof($fh)) {
        $file .= fgets($fh);
     }
    $fileLines = explode("\n", $file);
    for($i=0;$i<count($fileLines);$i++) {
        if(strstr($fileLines[$i], $parameter)) {
            $fileLines[$i] = "$" . $parameter . " = '" . $value . "'";
         }
     }
    $file = implode("\n", $fileLines);
    fwrite($fh, $file);
    fclose($fh);
 }

OwnerDisplayName: Unkwntech


问:
What's the difference between 'green threads' and 'user threads'
At the moment, I am dealing with operating systems concepts. However, I have a problem understanding the difference between "kernel thread" and "user thread".

So I surfed the internet and saw this post:
https://stackoverflow.com/a/15984127/5005715

Unfortunately, I do not understand what's the difference between "green threads" and "user threads". For me it is basically the same.

Am I right?

答:
A Linux "user thread" is a thread that

is managed by the operating system,

was created when user mode code (e.g., an application) called the clone system call,

executes both user mode code and kernel code on behalf of the application.

A Linux "kernel thread" is almost the same thing, but

It is created by the kernel for its own purposes, and

It only executes kernel-mode code,

I don't know if "user thread" and "kernel thread" have similar meanings in any other operating system.

A "green thread", in any operating system, is a thread that is managed entirely by a user mode process.  The operating system is unaware of green threads, and there is no way for multiple green threads in the same process to run on different CPUs at the same time.


问:
Temporarily disable an input field if second input field is filled
I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.

The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.

JS

```<code>var inp1 = document.getElementById("input1");
inp1.onchange = function () {
   if (this.value != "" || this.value.length > 0) {
      document.getElementById("input2").disabled = true;
   }
}
</code>```

HTML

```<code><input type="text" id="input1">
<input type="text" id="input2">
</code>```

答:
How about using keyup?

Like this;

```<code>var inp1 = document.getElementById("input1");

var inp2 = document.getElementById("input2");

inp1.onkeyup = function() { inputValidation(this, inp2); }

inp2.onkeyup = function() { inputValidation(this, inp1); }

function inputValidation(origin, lock) {
  var response = hasValue(origin.value);
  lock.disabled = response;
}

function hasValue(value) {
  return value != "" && value.length > 0;
}
</code>```

https://jsfiddle.net/8o3wwp6s/

Body:
I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.

The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.

JS

var inp1 = document.getElementById("input1");
inp1.onchange = function () {
   if (this.value != "" || this.value.length > 0) {
      document.getElementById("input2").disabled = true;
   }
}

HTML

<input type="text" id="input1">
<input type="text" id="input2">

Body:
How about using keyup?

Like this;

var inp1 = document.getElementById("input1");

var inp2 = document.getElementById("input2");

inp1.onkeyup = function() { inputValidation(this, inp2); }

inp2.onkeyup = function() { inputValidation(this, inp1); }

function inputValidation(origin, lock) {
  var response = hasValue(origin.value);
  lock.disabled = response;
}

function hasValue(value) {
  return value != "" && value.length > 0;
}

https://jsfiddle.net/8o3wwp6s/


问:
Webview scrolling weird behavior
I have a webview with a bunch of images in it stacked vertically. When I run it on a nexus 6 emulator the scrolling works how I'd expect from my web-browsing on my phone.

However when I deploy the APK to my actual device, the scrolling behaves totally differently. It lags a bit behind my finger, and seems to have no inertia at all. This is on a Samsung s8+.

This is my current configuration:

```<code>      String html = "<html><head><style>body {margin: 0; padding: 0; overflow: hidden;} img {}</style><body>" + imagesHTML + "</body></html>";
        String mime = "text/html";
        String encoding = "utf-8";

        webView.getSettings().setBuiltInZoomControls(true);
//        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        webView.setPadding(0, 0, 0, 0);
        webView.setInitialScale(100);
        webView.loadDataWithBaseURL(null, html, mime, encoding, null);
</code>```

Any ideas?

答: I figured it out. Overflow: hidden; on the body was causing the weird behavior.</p>

Title: Webview scrolling weird behavior

Body:
I have a webview with a bunch of images in it stacked vertically. When I run it on a nexus 6 emulator the scrolling works how I'd expect from my web-browsing on my phone.

However when I deploy the APK to my actual device, the scrolling behaves totally differently. It lags a bit behind my finger, and seems to have no inertia at all. This is on a Samsung s8+.

This is my current configuration:

      String html = "" + imagesHTML + "";
        String mime = "text/html";
        String encoding = "utf-8";

        webView.getSettings().setBuiltInZoomControls(true);
//        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        webView.setPadding(0, 0, 0, 0);
        webView.setInitialScale(100);
        webView.loadDataWithBaseURL(null, html, mime, encoding, null);

Any ideas?


问:
Spacemacs - How to disable current parentheses highlight
This is probably simple.

But I've couldn't find a way to disable the current parentheses highlight on Spacemacs

At first, I thought this could be fixed by toggling the (show-paren-mode), but it doesn't show any effect.

答:
In your config you can set dotspacemacs-highlight-delimiters, here is its documentation:

dotspacemacs-highlight-delimiters is a variable defined in
  ‘core-dotspacemacs.el’. Its value is ‘all’

Documentation: Select a scope to highlight delimiters. Possible values
  are ‘any’, ‘current’, ‘all’ or ‘nil’. Default is ‘all’ (highlight any
  scope and emphasize the current one.


问:
Python Pandas Set Value in DataFrame where Index has Multiple Identical Label Values
I want to set a value in a row in a pandas dataframe where the row index has duplicate values and the value of a date column is the max value for the selected index value.

My dataframe:

```<code>Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18    np.Nat
  C      2017-10-09   2017-10-30
</code>```

so I want to set the End_Date for index value 'B' where the Start_Date is the Max for 'B'

What is the best way to do this?

EDIT:

My dataframe:

```<code>Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18    np.Nat
  C      2017-10-09   2017-10-30
  D      2017-11-01    np.Nat
  E      2017-11-03   2017-11-09
  E      2017-11-13    np.Nat
</code>```

Through separate processes I come to learn that the End_Date corresponding to row #3 (Index == 'B', Start_Date == '2017-10-18 is 2017-10-25.  I also separately find that row #5(Index == 'D', Start_Date == '2017-11-01'  is 2017-11-03.  So I want to fill those values into End_Date one at a time.  Since I don't have an End_Date value for the last row (Index = 'E', Start_Date == '2017-11-13') that will stay empty.

Note that 'D' is unique while 'B' is not.

Output:

My dataframe:

```<code>Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18   2017-10-25
  C      2017-10-09   2017-10-30
  D      2017-11-01   2017-11-03
  E      2017-11-03   2017-11-09
  E      2017-11-13    np.Nat
</code>```

Not that the values 2017-10-25 in row 3 and 2017-11-03 came from another process and we can assume they are stored in variables - that can then be used to populate the initial dataframe to obtain the output.

答:
Setting the datetime format

```<code>df.End_Date=pd.to_datetime(df.End_Date,errors='coerce')
df.Start_Date=pd.to_datetime(df.Start_Date)
</code>```

Then we do apply + fillna

```<code>df['End_Date']=df.groupby('Index').apply(lambda x : x['End_Date'].fillna(x['Start_Date'].max())).values
df
Out[277]:
  Index Start_Date   End_Date
0     A 2017-10-01 2017-10-13
1     B 2017-10-07 2017-10-15
2     B 2017-10-18 2017-10-18
3     C 2017-10-09 2017-10-30
</code>```

Body:
I want to set a value in a row in a pandas dataframe where the row index has duplicate values and the value of a date column is the max value for the selected index value.

My dataframe:

Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18    np.Nat
  C      2017-10-09   2017-10-30

so I want to set the End_Date for index value 'B' where the Start_Date is the Max for 'B'

What is the best way to do this?

EDIT:

My dataframe:

Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18    np.Nat
  C      2017-10-09   2017-10-30
  D      2017-11-01    np.Nat
  E      2017-11-03   2017-11-09
  E      2017-11-13    np.Nat

Through separate processes I come to learn that the End_Date corresponding to row #3 (Index == 'B', Start_Date == '2017-10-18 is 2017-10-25.  I also separately find that row #5(Index == 'D', Start_Date == '2017-11-01'  is 2017-11-03.  So I want to fill those values into End_Date one at a time.  Since I don't have an End_Date value for the last row (Index = 'E', Start_Date == '2017-11-13') that will stay empty.

Note that 'D' is unique while 'B' is not.

Output:

My dataframe:

Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18   2017-10-25
  C      2017-10-09   2017-10-30
  D      2017-11-01   2017-11-03
  E      2017-11-03   2017-11-09
  E      2017-11-13    np.Nat

Not that the values 2017-10-25 in row 3 and 2017-11-03 came from another process and we can assume they are stored in variables - that can then be used to populate the initial dataframe to obtain the output.

Body:
Setting the datetime format

df.End_Date=pd.to_datetime(df.End_Date,errors='coerce')
df.Start_Date=pd.to_datetime(df.Start_Date)

Then we do apply + fillna

df['End_Date']=df.groupby('Index').apply(lambda x : x['End_Date'].fillna(x['Start_Date'].max())).values
df
Out[277]:
  Index Start_Date   End_Date
0     A 2017-10-01 2017-10-13
1     B 2017-10-07 2017-10-15
2     B 2017-10-18 2017-10-18
3     C 2017-10-09 2017-10-30


问:
Checkbox to select various months
Within a userform, I'm coding a checkbox to select multiple other checkboxes (months). This is to enable the user to select all 12 months rather than clicking through each of them. Following is the code I've written. What have I done wrong now?</p>

```<code>Private Sub Selectbox_AfterUpdate()
Dim x As Integer

If Me.Selectbox.Value = True Then
For x = 0 To 12
Me.Controls("Month" & x).Value = True
Next x
Me.Selectbox.Caption = "Deselect All"

ElseIf Me.Selectbox.Value = False Then
For x = 0 To 12
Me.Controls("Month" & x).Value = False

Next x
Me.Selectbox.Caption = "Select All"

End If

End Sub
</code>```

答:
There are 12 month. Change

```<code>For x = 0 To 12
</code>```

to

```<code>For x = 1 To 12
</code>```

It's depend the name you are using.

Title: Checkbox to select various months

Body:
Within a userform, I'm coding a checkbox to select multiple other checkboxes (months). This is to enable the user to select all 12 months rather than clicking through each of them. Following is the code I've written. What have I done wrong now?

Private Sub Selectbox_AfterUpdate()
Dim x As Integer

If Me.Selectbox.Value = True Then
For x = 0 To 12
Me.Controls("Month" & x).Value = True
Next x
Me.Selectbox.Caption = "Deselect All"

ElseIf Me.Selectbox.Value = False Then
For x = 0 To 12
Me.Controls("Month" & x).Value = False

Next x
Me.Selectbox.Caption = "Select All"

End If

End Sub

Body:
There are 12 month. Change

For x = 0 To 12

to

For x = 1 To 12

It's depend the name you are using.


问:
c# WPF Webbrowser with Highchart, Javascript from external source not working "An error has occurred in the script on this page"
I am trying to find out why my chart is not showing up in my WPF WebBrowser.
When I load my html file, I have the following error:

I think that IE might be blocking Highchart(Javascript from external Source) in the WPF WebBrowser because when I try to load it with IE my page got restricted from running script or ActiveX Control :

I know how to allow IE to run script or ActiveX Control but I don't know how to allow it in my WPF WebBrowser.

I have tried with a Mark Of The Web but I'm not sure if i am using it properly ?

```<code><!-- saved from url=(0016)http://localhost -->
</code>```

I have also tried some desperate method like adding my program in :

HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION\MyProgram.exe and MyProgram.vshost.exe with Value 0x00002af9

I would really appreciate some help.

I don't have find any answer that fix this problem so far.

My html file :

<!DOCTYPE HTML>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Highcharts Example</title>

```
</div>
</div>
</p>

<hr>

<h2>UPDATE</h2>

<p>Request : alert(navigator.userAgent);</p>

<p>Result :</p>

<p><img src="https://i.stack.imgur.com/vtbwl.png" alt="enter image description here"></p>

<p>Signification</p>

<hr>

<h2>SOLUTION</h2>

<p>Without any change in my PC Security Configuration i fixed this problem by adding this in the header of my html file : </p>

```<meta http-equiv="x-ua-compatible" content="IE=11">
```

See Alexander Ryan Baggett Answer for more information or this link.

答:
Okay, this works fine for me.

I added <meta http-equiv="x-ua-compatible" content="IE=11">. I also loaded the HTML file locally in visual studio by adding it to the project and setting it to copy always. I did not end up having to make any registry adjustments on my machine either.

C# file

```<code>        using System;
        using System.IO;
        using System.Windows;

        namespace Stackoverflow_question
        {
            public partial class MainWindow : Window
            {
                public MainWindow()
                {
                    InitializeComponent();
                    string curDir = Directory.GetCurrentDirectory();
                    webbrowser1.Navigate(new Uri(String.Format("file:///{0}/test.html", curDir))) ;
                }
            }
        }
</code>```

HTML file

```<code>        <!DOCTYPE HTML>
        <!-- saved from url=(0016)http://localhost -->
        <html>
        <head>
            <meta http-equiv="x-ua-compatible" content="IE=11">
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
            <title>Highcharts Example</title>
            <style type="text/css">
            </style>
        </head>
        <body>
            <script src="https://code.highcharts.com/highcharts.src.js"></script>
            <script src="https://code.highcharts.com/modules/exporting.js"></script>
            <div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>

            <script type="text/javascript">
                Highcharts.chart("container", {
                    chart: {
                        type: "spline",
                        inverted: true
                    },
                    title: {
                        text: "Atmosphere Temperature by Altitude"
                    },
                    subtitle: {
                        text: "According to the Standard Atmosphere Model"
                    },
                    xAxis: {
                        reversed: false,
                        title: {
                            enabled: true,
                            text: "Altitude"
                        },
                        labels: {
                            formatter: function () {
                                return this.value + "km";
                            }
                        },
                        maxPadding: 0.05,
                        showLastLabel: true
                    },
                    yAxis: {
                        title: {
                            text: "Temperature"
                        },
                        labels: {
                            formatter: function () {
                                return this.value + "°";
                            }
                        },
                        lineWidth: 2
                    },
                    legend: {
                        enabled: false
                    },
                    tooltip: {
                        headerFormat: "<b>{series.name}</b><br/>",
                        pointFormat: "{point.x} km: {point.y}°C"
                    },
                    plotOptions: {
                        spline: {
                            marker: {
                                enable: false
                            }
                        }
                    },
                    series: [{
                        name: "Temperature",
                        data: [[0, 15], [10, -50], [20, -56.5], [30, -46.5], [40, -22.1],
                            [50, -2.5], [60, -27.7], [70, -55.7], [80, -76.5]]
                    }]
                });
            </script>
        </body>
        </html>
</code>```

It gives a nice result too.

If this code doesn't resolve your issue. I would suspect something needs to be changed about your Local Intranet Security Zone settings.

Body:
I am trying to find out why my chart is not showing up in my WPF WebBrowser.
When I load my html file, I have the following error:

I think that IE might be blocking Highchart(Javascript from external Source) in the WPF WebBrowser because when I try to load it with IE my page got restricted from running script or ActiveX Control :

I know how to allow IE to run script or ActiveX Control but I don't know how to allow it in my WPF WebBrowser.

I have tried with a Mark Of The Web but I'm not sure if i am using it properly ?

I have also tried some desperate method like adding my program in :

HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION\MyProgram.exe and MyProgram.vshost.exe with Value 0x00002af9

I would really appreciate some help.

I don't have find any answer that fix this problem so far.

My html file :

<!DOCTYPE HTML>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Highcharts Example</title>

UPDATE

Request : alert(navigator.userAgent);

Result :

Signification

SOLUTION

Without any change in my PC Security Configuration i fixed this problem by adding this in the header of my html file :

<meta http-equiv="x-ua-compatible" content="IE=11">

See Alexander Ryan Baggett Answer for more information or this link.

Body:
Okay, this works fine for me.

I added <meta http-equiv="x-ua-compatible" content="IE=11">. I also loaded the HTML file locally in visual studio by adding it to the project and setting it to copy always. I did not end up having to make any registry adjustments on my machine either.

C# file

        using System;
        using System.IO;
        using System.Windows;

        namespace Stackoverflow_question
        {
            public partial class MainWindow : Window
            {
                public MainWindow()
                {
                    InitializeComponent();
                    string curDir = Directory.GetCurrentDirectory();
                    webbrowser1.Navigate(new Uri(String.Format("file:///{0}/test.html", curDir))) ;
                }
            }
        }

HTML file

        <!DOCTYPE HTML>
        <!-- saved from url=(0016)http://localhost -->
        <html>
        <head>
            <meta http-equiv="x-ua-compatible" content="IE=11">
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
            <title>Highcharts Example</title>
            <style type="text/css">
            </style>
        </head>
        <body>
            <script src="https://code.highcharts.com/highcharts.src.js"></script>
            <script src="https://code.highcharts.com/modules/exporting.js"></script>
            <div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>

            <script type="text/javascript">
                Highcharts.chart("container", {
                    chart: {
                        type: "spline",
                        inverted: true
                    },
                    title: {
                        text: "Atmosphere Temperature by Altitude"
                    },
                    subtitle: {
                        text: "According to the Standard Atmosphere Model"
                    },
                    xAxis: {
                        reversed: false,
                        title: {
                            enabled: true,
                            text: "Altitude"
                        },
                        labels: {
                            formatter: function () {
                                return this.value + "km";
                            }
                        },
                        maxPadding: 0.05,
                        showLastLabel: true
                    },
                    yAxis: {
                        title: {
                            text: "Temperature"
                        },
                        labels: {
                            formatter: function () {
                                return this.value + "°";
                            }
                        },
                        lineWidth: 2
                    },
                    legend: {
                        enabled: false
                    },
                    tooltip: {
                        headerFormat: "<b>{series.name}</b><br/>",
                        pointFormat: "{point.x} km: {point.y}°C"
                    },
                    plotOptions: {
                        spline: {
                            marker: {
                                enable: false
                            }
                        }
                    },
                    series: [{
                        name: "Temperature",
                        data: [[0, 15], [10, -50], [20, -56.5], [30, -46.5], [40, -22.1],
                            [50, -2.5], [60, -27.7], [70, -55.7], [80, -76.5]]
                    }]
                });
            </script>
        </body>
        </html>

It gives a nice result too.

If this code doesn't resolve your issue. I would suspect something needs to be changed about your Local Intranet Security Zone settings.


问:
style fontWeight and fontStyle react-native cannot work together
why fontWeight and fontStyle cannot work together in react-native on ios?

```<code><Text style={{fontSize: 20, fontFamily: 'Century', fontWeight: '900', fontStyle: 'oblique'}}>ASD</Text>
</code>```

the output like "normal italic".
my expect is bold italic

答:
Use italic instead of oblique for your fontStyle. In react native, oblique is not a valid fontStyle.

fontStyle is limited to two values normal and italic. You can see more in the React Native docs.

Body:
why fontWeight and fontStyle cannot work together in react-native on ios?

<Text style={{fontSize: 20, fontFamily: 'Century', fontWeight: '900', fontStyle: 'oblique'}}>ASD</Text>

the output like "normal italic".
my expect is bold italic


问:
LOAD DATA INFILE REPLACE with specific columns
I am currently using LOAD DATA LOCAL INFILE successfully, and typically with REPLACE.  However, I am now trying to use the same command to load a CSV file into a table but only replace specific columns.

For example, table currently looks like:

```<code>ID    date        num1    num2
01    1/1/2017    100     200
01    1/2/2017    101     201
01    1/3/2017    102     202
</code>```

where ID and date are the primary keys.

I have a similar CSV, but one that only has ID, date, num1 as columns.  I want to load that new CSV into the table, but maintain whatever is in num2.

My current code per this post:

```<code>LOAD DATA LOCAL INFILE mycsv.csv
REPLACE INTO TABLE mytable
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(ID, date, num1)
</code>```

Again, my code works flawlessly when I'm replacing all the columns, but when I try to replace only select columns, it fills the other columns with NULL values.  The similar posts (like the one I referenced) haven't helped.

I don't know if this is python specific issue, but I'm using MySQLdb to connect to the database and I'm familiar with the local_infile parameter and that's all working well.  MySQL version 5.6.33.

答:
Simply load csv table into a similarly structured temp table and then run UPDATE JOIN:

CREATE TABLE mytemptable AS SELECT * FROM mytable LIMIT 1;          --- RUN ONLY ONCE

DELETE FROM mytemptable;

LOAD DATA LOCAL INFILE mycsv.csv
INTO TABLE mytemptable
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(ID, date, num1);

UPDATE mytable t1
INNER JOIN mytemptable t2 ON t1.ID = t2.ID AND t1.`date` = t2.`date`
SET t1.num1 = t2.num1;
```

Body:
I am currently using LOAD DATA LOCAL INFILE successfully, and typically with REPLACE.  However, I am now trying to use the same command to load a CSV file into a table but only replace specific columns.

For example, table currently looks like:

ID    date        num1    num2
01    1/1/2017    100     200
01    1/2/2017    101     201
01    1/3/2017    102     202

where ID and date are the primary keys.

I have a similar CSV, but one that only has ID, date, num1 as columns.  I want to load that new CSV into the table, but maintain whatever is in num2.

My current code per this post:

LOAD DATA LOCAL INFILE mycsv.csv
REPLACE INTO TABLE mytable
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(ID, date, num1)

Again, my code works flawlessly when I'm replacing all the columns, but when I try to replace only select columns, it fills the other columns with NULL values.  The similar posts (like the one I referenced) haven't helped.

I don't know if this is python specific issue, but I'm using MySQLdb to connect to the database and I'm familiar with the local_infile parameter and that's all working well.  MySQL version 5.6.33.


问:
How do i reverse each character in a string?
```<code>class Solution {
public String reverseWords(String s) {
    int count = 0;
    int current = 0;
    StringBuilder build = new StringBuilder();
    for(int i = 0; i< s.length(); i++){
        count++;
        current = count;
        if(s.charAt(i) == ' '){
            while(current > 0){
                build.append(s.charAt(current - 1));
                current--;
            }
            build.append(s.charAt(i));
        }

    }
    return build.toString();
}
}
</code>```

I am having trouble understanding why this doesn't work. I went through the
entire code a couple of times but there seems to be an issue.

Input :          "Let's take LeetCode contest"
my answer:       " s'teL  ekat s'teL  edoCteeL ekat s'teL "
correct answer:  "s'teL ekat edoCteeL tsetnoc"
whats going on?

答:
There are several problems:

You set current to the current position, and then iterate down to 0 append characters. Instead of going down to 0, you iterate until the beginning of the last word. Alternative, iterate until the previous ' ' character.

You only append something after seeing a ' ' character. What will happen at the end of the sentences? As i goes over the letters in the last word, there will be no more ' ' characters, and so the last word will never get appended. To handle this case, you would need to add some logic after the for-loop to check if there is an unwritten word, and append it reversed.

A simpler approach is to take advantage of the StringBuilder's ability to insert characters at some position.
You could track the beginning position of the current word,
and as you iterate over the characters,
insert if it's not ' ',
or else append a ' ' and reset the insertion position.

```<code>StringBuilder build = new StringBuilder();
int current = 0;
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    if (c == ' ') {
        build.append(' ');
        current = i + 1;
    } else {
        build.insert(current, c);
    }
}
return build.toString();
</code>```

Body:
class Solution {
public String reverseWords(String s) {
    int count = 0;
    int current = 0;
    StringBuilder build = new StringBuilder();
    for(int i = 0; i< s.length(); i++){
        count++;
        current = count;
        if(s.charAt(i) == ' '){
            while(current > 0){
                build.append(s.charAt(current - 1));
                current--;
            }
            build.append(s.charAt(i));
        }

    }
    return build.toString();
}
}

I am having trouble understanding why this doesn't work. I went through the
entire code a couple of times but there seems to be an issue.

Input :          "Let's take LeetCode contest"
my answer:       " s'teL  ekat s'teL  edoCteeL ekat s'teL "
correct answer:  "s'teL ekat edoCteeL tsetnoc"
whats going on?

Body:
There are several problems:

You set current to the current position, and then iterate down to 0 append characters. Instead of going down to 0, you iterate until the beginning of the last word. Alternative, iterate until the previous ' ' character.

You only append something after seeing a ' ' character. What will happen at the end of the sentences? As i goes over the letters in the last word, there will be no more ' ' characters, and so the last word will never get appended. To handle this case, you would need to add some logic after the for-loop to check if there is an unwritten word, and append it reversed.

A simpler approach is to take advantage of the StringBuilder's ability to insert characters at some position.
You could track the beginning position of the current word,
and as you iterate over the characters,
insert if it's not ' ',
or else append a ' ' and reset the insertion position.

StringBuilder build = new StringBuilder();
int current = 0;
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    if (c == ' ') {
        build.append(' ');
        current = i + 1;
    } else {
        build.insert(current, c);
    }
}
return build.toString();


问:
How do I pass url parameter to form value?
The form has this hidden field

```<code><input type="hidden" name="dir_type" value="tshirt">
</code>```

url parameters are

```<code>/dir?type=tshirt
/dir?type=books
/dir?type=posters
</code>```

and so on.

Now I hard coded value="tshirts" but how do I get parameter for the relevant page?

I found several pages like this dealing with similar topics but I did not understand how this is done.

Thanks for your help.

UPDATE

The answer by systempuntoout works perfectly but I decided to solve the problem without using templates. And for anyone who has a similar question, passing the url parameter to the form like this works well:

```<code><form name="submit_form" action="/directorysubmithandler" method="post" onSubmit="return validate_form()">
title: <input type="text" name="title" size=50><br />
url: <input type="text" name="url" size=50><br />
<input type="hidden" name="dir_type" value="%s")>
<input type="submit" value="submit">
</form>""" % self.request.get("type"))
</code>```

答:
a. pass the type value to the view:

```<code>class Directory(webapp.RequestHandler):
    def get(self):
       ....
       merchandise_type = self.request.get("type", "")
       items = Item.all()
       items.filter("type =", merchandise_type)
       path = os.path.join(os.path.dirname(__file__), 'dir_details.html')
       self.response.out.write(template.render(path,{'type':merchandise_type}))
</code>```

b. add the type value to the hidden field:

```<code><input type="hidden" name="dir_type" value="{{ type }}">
</code>```

c. get the dir_type value in your post handler:

```<code>class DirectorySubmitHandler(webapp.RequestHandler):
    def post(self):
        user = users.get_current_user()
        merchandise_type = self.request.get("dir_type", "")
        dir_type = merchandise_type
        if user:
            item = Item()
            item.title = self.request.get("title")
            item.url = self.request.get("url")
            item.type = self.request.get("dir_type")
            item.user_who_liked_this_item = user
            item.put()
            self.redirect("/dir?type=%s" %
self.request.get("dir_type"))
        else:
            self.redirect(users.create_login_url(self.request.uri))
</code>```

Body:
The form has this hidden field

<input type="hidden" name="dir_type" value="tshirt">

url parameters are

/dir?type=tshirt
/dir?type=books
/dir?type=posters

and so on.

Now I hard coded value="tshirts" but how do I get parameter for the relevant page?

I found several pages like this dealing with similar topics but I did not understand how this is done.

Thanks for your help.

UPDATE

The answer by systempuntoout works perfectly but I decided to solve the problem without using templates. And for anyone who has a similar question, passing the url parameter to the form like this works well:

<form name="submit_form" action="/directorysubmithandler" method="post" onSubmit="return validate_form()">
title: <input type="text" name="title" size=50>

url: <input type="text" name="url" size=50>

<input type="hidden" name="dir_type" value="%s")>
<input type="submit" value="submit">
</form>""" % self.request.get("type"))

Body:
a. pass the type value to the view:

class Directory(webapp.RequestHandler):
    def get(self):
       ....
       merchandise_type = self.request.get("type", "")
       items = Item.all()
       items.filter("type =", merchandise_type)
       path = os.path.join(os.path.dirname(__file__), 'dir_details.html')
       self.response.out.write(template.render(path,{'type':merchandise_type}))

b. add the type value to the hidden field:

<input type="hidden" name="dir_type" value="{{ type }}">

c. get the dir_type value in your post handler:

class DirectorySubmitHandler(webapp.RequestHandler):
    def post(self):
        user = users.get_current_user()
        merchandise_type = self.request.get("dir_type", "")
        dir_type = merchandise_type
        if user:
            item = Item()
            item.title = self.request.get("title")
            item.url = self.request.get("url")
            item.type = self.request.get("dir_type")
            item.user_who_liked_this_item = user
            item.put()
            self.redirect("/dir?type=%s" %
self.request.get("dir_type"))
        else:
            self.redirect(users.create_login_url(self.request.uri))


问:
Vue.js and Vuetify slot-scope
I'm really just not sure how slot-scopes work.  Wondering if somebody could help me out with this (seemingly) pretty simple problem.

```<code><v-data-table>
    <template slot="items" slot-scope="props">
        <tr @click="props.expanded = !props.expanded">
</code>```

What I'm looking to do is manually update "props" to expand this  row based on an external event.  The problem is, I can't figure out how to access this outside of the context noted above.  The props.expanded = !props.expanded works just fine.

Any ideas?

答:
There doesn't seem to be a way built in to the component. As the data table creates it's own expanded object and doesn't use a passed in prop.

You can use a ref. Vue page on child component refs.

This following code will set the ref on the data table to accesshere.

```<code><v-data-table ref="accesshere" :headers="headers" :items="dataTable"
:search="search" item-key="id">
</code>```

Now you'll be able to access that object by using (setting this to false will close the expanded table row) this.$refs.accesshere.expanded['nameofkey'] = false

Here is a codepen showing it in action.

There is an issue with the expanded object and that it isn't populated until you expand a row for the first time. So if you do something like the following. It won't see those changes (unless you force the component to update) and therefore won't expand the row right away.

```<code> methods: {
   itemShow () {
     this.$refs.accesshere.expanded['2'] = true
     this.$forceUpdate() // This works, I don't know if it is recommended though
  }
 }
</code>```

Title: Vue.js and Vuetify slot-scope

Body:
I'm really just not sure how slot-scopes work.  Wondering if somebody could help me out with this (seemingly) pretty simple problem.

<v-data-table>
    <template slot="items" slot-scope="props">

What I'm looking to do is manually update "props" to expand this  row based on an external event.  The problem is, I can't figure out how to access this outside of the context noted above.  The props.expanded = !props.expanded works just fine.

Any ideas?

Body:
There doesn't seem to be a way built in to the component. As the data table creates it's own expanded object and doesn't use a passed in prop.

You can use a ref. Vue page on child component refs.

This following code will set the ref on the data table to accesshere.

<v-data-table ref="accesshere" :headers="headers" :items="dataTable"
:search="search" item-key="id">

Now you'll be able to access that object by using (setting this to false will close the expanded table row) this.$refs.accesshere.expanded['nameofkey'] = false

Here is a codepen showing it in action.

There is an issue with the expanded object and that it isn't populated until you expand a row for the first time. So if you do something like the following. It won't see those changes (unless you force the component to update) and therefore won't expand the row right away.

 methods: {
   itemShow () {
     this.$refs.accesshere.expanded['2'] = true
     this.$forceUpdate() // This works, I don't know if it is recommended though
  }
 }


问:
Getting Image/File Data From WebKitFormBoundary PHP
I am uploading a file via ajax, an image specifically, and in my upload I am getting this information on the php server:

------WebKitFormBoundaryVuxuxnms21f4i1ZX
Content-Disposition: form-data; name="file"; filename="blob"
Content-Type: image/png

�PNG

IHDR,,y}�u IDATx^L�ɓdו�w|v�y�̈���b 8�ɪbUuw���h�Lfj-d2�i!3md���i�fZ���Z&�ꮪ&   �C�������~��"�4gdF�?��s�{�w�sn�ٳ�A�<�Ͽ?��{��o���l4���G�Ջ��'q���x��ftzk�/w���D�������r�l�G�Q���fԪ�hԇ�Z����N7v�:����k����[�뱹�����vkQ���kFt[Q/����lT��x��k���Տ~��V�����N7�v{Q.բT*G�
------WebKitFormBoundaryVuxuxnms21f4i1ZX
Content-Disposition: form-data; name="name"

image
------WebKitFormBoundaryVuxuxnms21f4i1ZX--

I know the charaters inside are the image/file being uploaded, but how do I parse the WebKitFormBoundary to only get the file data?

答: I had this problem, and fix it changing request method to 'POST', i hope this help!</p>


问:
angular/express api/mongodb update issue
working with a full MEAN stack.
trying to write data to a "notes" array in my mongodb document id #1.

mongo document:

```<code>> db.contacts.find().pretty()
{
"_id" : ObjectId("5a294af85e96746421bf35f1"),
"id" : 1,
"type" : "dealer",
"name" : "ken yoder",
"company" : "kens sales",
"phone" : "817-403-9767",
"notes" : [
    {
        "date" : "Thu Dec 07 2017 08:15:37 GMT-0600 (CST)",
        "by" : "@me",
        "note" : "this is a note"
    },
    {
        "date" : "Thu Dec 07 2017 08:16:31 GMT-0600 (CST)",
        "by" : "@donny",
        "note" : "bla bla bla mumford and sons"
    },
    {
        "date" : "Thu Dec 07 2017 08:34:03 GMT-0600 (CST)",
        "by" : "@ken",
        "note" : "test with another note"
    },
    {
        "date" : "Thu Dec 07 2017 08:34:29 GMT-0600 (CST)",
        "by" : "@ken",
        "note" : "test with another notey note note"
    }
],
"setNotes" : {
    "date" : "Thu Dec 07 2017 10:52:09 GMT-0600 (CST)",
    "by" : "@kale",
    "note" : "hhsdihufiudhsiuhdshuifds"
}
}
</code>```

express code:

```<code>app.get('/newNote/:noteFor/:noteCount/:noteBy/:note/', function (req, res) {
        var setNotes = "notes."+req.params.noteCount;
        db.collection('contacts').update({ id:req.params.noteFor }, { $set: { setNotes : {date: Date(), by: req.params.noteBy, note: req.params.note} }}, function(err, res) {
                if (err) throw err;
                console.log("notefor: "+req.params.noteFor+" noteCount: "+setNotes+" noteBy: "+req.params.noteBy+" note: "+req.params.note);
                console.log(res.result.nModified + " for " + req.params.noteFor + " updated");
        });
});
</code>```

if i run this code as it sits, i get nothing, no insert, no errors.
- if i change the update id from "req.params.id" to "1", i get an insert but...
- instead of using my "setNotes" variable (which outputs "notes.4") for the $set identifier, it created a new object called "setNotes".

```<code>API URL: /newNote/1/4/@kale/this is a note test
</code>```

答:
This will just add a new document everytime to notes array:

```<code>db.collection('contacts').update({ id:req.params.noteFor }, {
          $push: {
                   notes : {date: Date(), by: req.params.noteBy, note: req.params.note}
                 }
          }, function(err, res) {
        //code
 }
</code>```

Body:
working with a full MEAN stack.
trying to write data to a "notes" array in my mongodb document id #1.

mongo document:

> db.contacts.find().pretty()
{
"_id" : ObjectId("5a294af85e96746421bf35f1"),
"id" : 1,
"type" : "dealer",
"name" : "ken yoder",
"company" : "kens sales",
"phone" : "817-403-9767",
"notes" : [
    {
        "date" : "Thu Dec 07 2017 08:15:37 GMT-0600 (CST)",
        "by" : "@me",
        "note" : "this is a note"
    },
    {
        "date" : "Thu Dec 07 2017 08:16:31 GMT-0600 (CST)",
        "by" : "@donny",
        "note" : "bla bla bla mumford and sons"
    },
    {
        "date" : "Thu Dec 07 2017 08:34:03 GMT-0600 (CST)",
        "by" : "@ken",
        "note" : "test with another note"
    },
    {
        "date" : "Thu Dec 07 2017 08:34:29 GMT-0600 (CST)",
        "by" : "@ken",
        "note" : "test with another notey note note"
    }
],
"setNotes" : {
    "date" : "Thu Dec 07 2017 10:52:09 GMT-0600 (CST)",
    "by" : "@kale",
    "note" : "hhsdihufiudhsiuhdshuifds"
}
}

express code:

app.get('/newNote/:noteFor/:noteCount/:noteBy/:note/', function (req, res) {
        var setNotes = "notes."+req.params.noteCount;
        db.collection('contacts').update({ id:req.params.noteFor }, { $set: { setNotes : {date: Date(), by: req.params.noteBy, note: req.params.note} }}, function(err, res) {
                if (err) throw err;
                console.log("notefor: "+req.params.noteFor+" noteCount: "+setNotes+" noteBy: "+req.params.noteBy+" note: "+req.params.note);
                console.log(res.result.nModified + " for " + req.params.noteFor + " updated");
        });
});

if i run this code as it sits, i get nothing, no insert, no errors.
- if i change the update id from "req.params.id" to "1", i get an insert but...
- instead of using my "setNotes" variable (which outputs "notes.4") for the $set identifier, it created a new object called "setNotes".

API URL: /newNote/1/4/@kale/this is a note test

Body:
This will just add a new document everytime to notes array:

db.collection('contacts').update({ id:req.params.noteFor }, {
          $push: {
                   notes : {date: Date(), by: req.params.noteBy, note: req.params.note}
                 }
          }, function(err, res) {
        //code
 }


问:
IIS iis_iusrs disappeared on Windows Server 2012R2
I have a .Net service installed on a Windows Server 2012R2.

Today, the users have complain because they couldn not store more files on server, it should be permissions related. Right click on the folder -> secutiry and IIS_IUSRS does not exist anymore.

How can be this group deleted?, is it possible to restore it?

I have restored IIS service and machine with no luck.

thanks

答:
There is nothing special in the IIS_IUSRS group. Its a local group created with NT Authority\IUSR as a member. If its deleted you can just create it with the same name and with the above user in it. That's all. Nothing to restore. You will have to look into restore for folders that might have lost this group when deleted. By default the only place I know this group has permissions is the inetpub\wwwrtoot folder with read permissions.

Normally, as with any other user management feature you need admin privilege to delete this group. Did you check user management to see if the group is actually deleted from local machine or just removed from this folder?


问:
Trying to get a Java function to return an array based on a string parameter passed to it
Here's what I am trying to do; I am trying to write a small program that uses a function to get an array containing the members of a department based on the department selected. There are about 40 departments, and each department has 1 to 4 members. So this what I did, but I can't seem to resolve to a variable:

From main:

```<code>String[]names = initial(department)
</code>```

Departments is the name of the department being passed to the function. In the function I have:

```<code>public static String[] initial (String responsibleDepartment) {

    if (responsibleDepartment.equals("Accounts Receivable")) {
        String[] assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"}
     }

    if (responsibleDepartment.equals("Customer Service")) {
        String[] assignInitial = {"Mary Wexler", "Turd Ferguson"}
     }

   // and 38 more if statements with the rest of the departments. Finally I have:
        return assignInitial;
        }
</code>```

So the way it stands, "assignInitial cannot be resolved to a variable" (that's what it says by the return statement.) If I try to initialize the variable before the first "if" statement, and then remove the initialization of String[] next to the assignInitial in the first "if" statement, then it says "Array constants can only be used in initializers." I am sure there is a better way to do this, but I can't seem to make any headway with what I am found online. Any takers?

Thank you much!
-The Munch

答:
Since no one has suggested it yet, Java supports switches with Strings, you don't need a bunch of if-statements. You can use a switch, which is slightly faster if you have that many if-statements.

```<code>switch(responsibleDepartment) {

  case "Accounts Receivable":
    return new String[]{"Mike Davis", "Ben Jones", "Ann Smith"};
  ...
</code>```

Alternatively you could also create a Map and build the map and just access the map like this

```<code>map.get(responsibleDepartment) // Returns {"Mike Davis", "Ben Jones", "Ann Smith"}
</code>```

If you need it concurrent use ConcurrentHashMap

Body:
Here's what I am trying to do; I am trying to write a small program that uses a function to get an array containing the members of a department based on the department selected. There are about 40 departments, and each department has 1 to 4 members. So this what I did, but I can't seem to resolve to a variable:

From main:

String[]names = initial(department)

Departments is the name of the department being passed to the function. In the function I have:

public static String[] initial (String responsibleDepartment) {

    if (responsibleDepartment.equals("Accounts Receivable")) {
        String[] assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"}
     }

    if (responsibleDepartment.equals("Customer Service")) {
        String[] assignInitial = {"Mary Wexler", "Turd Ferguson"}
     }

   // and 38 more if statements with the rest of the departments. Finally I have:
        return assignInitial;
        }

So the way it stands, "assignInitial cannot be resolved to a variable" (that's what it says by the return statement.) If I try to initialize the variable before the first "if" statement, and then remove the initialization of String[] next to the assignInitial in the first "if" statement, then it says "Array constants can only be used in initializers." I am sure there is a better way to do this, but I can't seem to make any headway with what I am found online. Any takers?

Thank you much!
-The Munch

Body:
Since no one has suggested it yet, Java supports switches with Strings, you don't need a bunch of if-statements. You can use a switch, which is slightly faster if you have that many if-statements.

switch(responsibleDepartment) {

  case "Accounts Receivable":
    return new String[]{"Mike Davis", "Ben Jones", "Ann Smith"};
  ...

Alternatively you could also create a Map and build the map and just access the map like this

map.get(responsibleDepartment) // Returns {"Mike Davis", "Ben Jones", "Ann Smith"}

If you need it concurrent use ConcurrentHashMap


问:
C++ binary file - Writing ints - strange behaviour
I have a simple vector of ints, and I want to write it into a binary file. For example:

```<code>#include <fstream>
#include <vector>

int main () {
    std::vector<uint32_t> myVector{5, 10, 15, 20 };
    // write vector to bin file
    std::ofstream outfile("./binary_ints.data",  std::ios_base::binary|std::ios::trunc);
    std::copy(myVector.begin(), myVector.end(), std::ostreambuf_iterator<char>(outfile));
    outfile.close();
    return 0;
}
</code>```

Then, if I inspect the file "binary_ints.data" in hex mode, I have this:

```<code>00000000: 050a 0f14 0a
</code>```

Thats ok!.

However, If myVector has this data:

```<code>std::vector<uint32_t> myVector{3231748228};
</code>```

Then, the hex stored is weird:

```<code>00000000: 840a
</code>```

84 in Hex doesn't match with the Int 3231748228.

What's happening here?
Thanks.

答:
The problem is that each value in your std::vector<uint32_t> is interpreted as char during your std::copy () invocation. 3231748228 is represented in hex as C0A09084. std::copy () takes uint32_t value, truncates it to single byte which is 0x84 on Little-endian processor. After writing byte 0x84 in file byte 0x0a is added which corresponds to new line character.

A possible solution is to use ofstream::write() instead of std::copy ():

```<code>#include <fstream>
#include <vector>

int main () {
    std::vector<uint32_t> myVector{3231748228 };
    // write vector to bin file
    std::ofstream outfile("./binary_ints.data",  std::ios_base::binary|std::ios::trunc);

    outfile.write (
        (char*)(myVector.data ()),
        myVector.size () * sizeof (decltype (myVector)::value_type));

    outfile.close();
    return 0;
}
</code>```

Note the use of decltype (). The same effect may be achivied by just writing sizeof (uint32_t), but with decltype () you may be sure that the code remains correct even if you change myVector value type.

Body:
I have a simple vector of ints, and I want to write it into a binary file. For example:

#include <fstream>
#include <vector>

int main () {
    std::vector<uint32_t> myVector{5, 10, 15, 20 };
    // write vector to bin file
    std::ofstream outfile("./binary_ints.data",  std::ios_base::binary|std::ios::trunc);
    std::copy(myVector.begin(), myVector.end(), std::ostreambuf_iterator<char>(outfile));
    outfile.close();
    return 0;
}

Then, if I inspect the file "binary_ints.data" in hex mode, I have this:

00000000: 050a 0f14 0a

Thats ok!.

However, If myVector has this data:

std::vector<uint32_t> myVector{3231748228};

Then, the hex stored is weird:

00000000: 840a

84 in Hex doesn't match with the Int 3231748228.

What's happening here?
Thanks.

Body:
The problem is that each value in your std::vector<uint32_t> is interpreted as char during your std::copy () invocation. 3231748228 is represented in hex as C0A09084. std::copy () takes uint32_t value, truncates it to single byte which is 0x84 on Little-endian processor. After writing byte 0x84 in file byte 0x0a is added which corresponds to new line character.

A possible solution is to use ofstream::write() instead of std::copy ():

#include <fstream>
#include <vector>

int main () {
    std::vector<uint32_t> myVector{3231748228 };
    // write vector to bin file
    std::ofstream outfile("./binary_ints.data",  std::ios_base::binary|std::ios::trunc);

    outfile.write (
        (char*)(myVector.data ()),
        myVector.size () * sizeof (decltype (myVector)::value_type));

    outfile.close();
    return 0;
}

Note the use of decltype (). The same effect may be achivied by just writing sizeof (uint32_t), but with decltype () you may be sure that the code remains correct even if you change myVector value type.


问:
Constructor uses the mock object, how do I test a method in isolation?
I have a class that looks like this:

```<code>class MyClass {

  private IDependency dep;

  public MyClass(IDependency dep) {
    this.dep = dep;
    this.dep.Reset();
  }

  public void Clear() {
    this.dep.Reset();
  }
}
</code>```

How do I test that the Reset method gets called properly in the Clear method while ignoring what the constructor does?

My Moq test looks like this:

```<code>MockRepository mocks = new MockRepository(MockBehavior.Default);
var dep = mocks.Create<IDependency>();

dep.Setup(s => s.Reset());

MyClass myclass = new MyClass(dep.Object);
myclass.Clear():

state.Verify(s => s.Reset(), Times.Exactly(1));
</code>```

It fails because Reset has been called twice (once in the constructor, and once in the Clear method).

答:
Instead of using a mock object, you could write a spy. Requires a bit more coding, but the test is easier to read.

```<code>class DependencySpy : IDependency {
    public int ResetCallCount { get; private set; }
    public void Reset() { ResetCallCount++; }
    public void ClearResetCallCount() { ResetCallCount = 0; }
}
</code>```

The test could the be written as

```<code>// Setup
var spy = new DependencySpy;
MyClass myclass = new MyClass(spy);
spy.ClearResetCallCount();
// Exercise
myclass.Clear();
// Validate
Assert.AreEqual(1, spy.ResetCallCount);
</code>```

Body:
I have a class that looks like this:

class MyClass {

  private IDependency dep;

  public MyClass(IDependency dep) {
    this.dep = dep;
    this.dep.Reset();
  }

  public void Clear() {
    this.dep.Reset();
  }
}

How do I test that the Reset method gets called properly in the Clear method while ignoring what the constructor does?

My Moq test looks like this:

MockRepository mocks = new MockRepository(MockBehavior.Default);
var dep = mocks.Create<IDependency>();

dep.Setup(s => s.Reset());

MyClass myclass = new MyClass(dep.Object);
myclass.Clear():

state.Verify(s => s.Reset(), Times.Exactly(1));

It fails because Reset has been called twice (once in the constructor, and once in the Clear method).

Body:
Instead of using a mock object, you could write a spy. Requires a bit more coding, but the test is easier to read.

class DependencySpy : IDependency {
    public int ResetCallCount { get; private set; }
    public void Reset() { ResetCallCount++; }
    public void ClearResetCallCount() { ResetCallCount = 0; }
}

The test could the be written as

// Setup
var spy = new DependencySpy;
MyClass myclass = new MyClass(spy);
spy.ClearResetCallCount();
// Exercise
myclass.Clear();
// Validate
Assert.AreEqual(1, spy.ResetCallCount);


问:
Access object from outer select clause in LINQ statement
Suppose I have the following LINQ Statement. I would like to find a way to use "r.Portfolio" while I am in the 3rd select clause (see comment in the code):

```<code>positionsToOptimize
    .Select(p => p)
    .SelectMany(r => r.Positions)
    .Select(pos => new OptimizedPosition() {
        CalculationType = TCalculationType.Absolute,
        Position = pos.NetPositionAmount,
        SecurityID = pos.SecurityID,
        Portfolio = r.Portfolio        // <- How do I do this? (Portfolio is not in 'pos')
    });
</code>```

Essentially I am trying to replace the following foreach nested loop:

```<code>var lst = new List<OptimizedPosition>();
foreach (var r in positionsToOptimize) {
    foreach (var pos in r.Positions) {
        lst.Add(new OptimizedPosition() {
            CalculationType = TCalculationType.Absolute,
            Position = pos.NetPositionAmount,
            SecurityID = pos.SecurityID,
            SystemCode = r.SystemCode
        });
    }
}

return lst;
</code>```

答:
You can select an anonymous type. Something like this:</p>

```<code>positionsToOptimize
.Select(p => p)
.SelectMany(r => r.Positions.Select(c => new { temp = r, Positions = c }))
.Select(pos => new OptimizedPosition()
{
    CalculationType = TCalculationType.Absolute,
    Position = pos.Positions.NetPositionAmount,
    SecurityID = pos.Positions.SecurityID,
    Portfolio = temp.Portfolio
});
</code>```

Body:
Suppose I have the following LINQ Statement. I would like to find a way to use "r.Portfolio" while I am in the 3rd select clause (see comment in the code):

positionsToOptimize
    .Select(p => p)
    .SelectMany(r => r.Positions)
    .Select(pos => new OptimizedPosition() {
        CalculationType = TCalculationType.Absolute,
        Position = pos.NetPositionAmount,
        SecurityID = pos.SecurityID,
        Portfolio = r.Portfolio        // <- How do I do this? (Portfolio is not in 'pos')
    });

Essentially I am trying to replace the following foreach nested loop:

var lst = new List<OptimizedPosition>();
foreach (var r in positionsToOptimize) {
    foreach (var pos in r.Positions) {
        lst.Add(new OptimizedPosition() {
            CalculationType = TCalculationType.Absolute,
            Position = pos.NetPositionAmount,
            SecurityID = pos.SecurityID,
            SystemCode = r.SystemCode
        });
    }
}

return lst;

Body:
You can select an anonymous type. Something like this:

positionsToOptimize
.Select(p => p)
.SelectMany(r => r.Positions.Select(c => new { temp = r, Positions = c }))
.Select(pos => new OptimizedPosition()
{
    CalculationType = TCalculationType.Absolute,
    Position = pos.Positions.NetPositionAmount,
    SecurityID = pos.Positions.SecurityID,
    Portfolio = temp.Portfolio
});


问:
Version control suffix on all files
In my index.html I have a number of scripts and css files that I have version control suffix on, like so:

```<code><html>
  <head>

    <link rel="stylesheet" type="text/css" href="/framework/compile/css/main.min.css?version=3.0">

  </head>
  <body>

    <script type="text/javascript" src="/framework/compile/js/app.min.js?version=3.0"></script>
    <script type="text/javascript" src="/framework/compile/js/app.min.js?version=3.0"></script>

  </body>
</html>
</code>```

I also have a directory of html views and smaller html files. Whenever I update one of these files, I increase the minor version number. For example, /framework/compile/css/main.min.css?version=3.0 becomes /framework/compile/css/main.min.css?version=3.1 after an update.

However, if I do a major site update and change most files, I will push the version number to 4.0. I don't want to have to manually change the version number on every file. Is there an easy and readable way to do this with a javascript variable or something similar.

I'm looking for something like this:

```<code>    <script>var version = "3.0";</script>
    <link rel="stylesheet" type="text/css" href="/framework/compile/css/main.min.css?version=" + version>

  </head>
  <body>

    <script type="text/javascript" src="/framework/compile/js/app.min.js?version=" + version></script>
    <script type="text/javascript" src="/framework/compile/js/app.min.js?version=" + version></script>

  </body>
</html>
</code>```

The above is obviously incorrect syntax and does not work.

答:
Solution Using Pure Javascript

index.html

```<code><html>
  <head>

  </head>
  <body>

    <div>
      Your main content should come BEFORE your javascript.
      The script to include the files should be immediately after your content,
      but before any other script file includes or in page javascript.
    </div>

    <script>

      /*******************************************************
      / Alternate Solution: If you're only wanting to get the
      / most current version of each file, you can just append
      / a datetime stamp to the script tag's url src
      /*******************************************************/

      //get current datetime in milliseconds
      var version = new Date().valueOf();

      /*******************************************************
      / OR you can use manual version numbers as per your ?
      /*******************************************************/

      //variable to hold version number
      var version = "3.0";

      /*******************************************************
      / Add the following ahead of any other scripts before
      / the closing body tag
      /*******************************************************/

      var cssLnk = document.createElement("link");
      cssLnk.setAttribute("rel", "stylesheet");
      cssLnk.setAttribute("type", "text/css");
      cssLnk.setAttribute("href", "/framework/compile/css/main.min.css?version=" + version);

      document.head.appendChild(cssLnk);

      var scr_A = document.createElement("script");
      scr_A.setAttribute("type", "text/javascript");
      scr_A.setAttribute("src", "/framework/compile/js/app.min.js?version=" + version);

      document.body.appendChild(scr_A);

      var scr_B = document.createElement("script");
      scr_B.setAttribute("type", "text/javascript");
      scr_B.setAttribute("src", "/framework/compile/js/app.min.js?version=" + version);

      document.body.appendChild(scr_B);

    </script>

  </body>
</html>
</code>```

Title: Version control suffix on all files

Body:
In my index.html I have a number of scripts and css files that I have version control suffix on, like so:

    <link rel="stylesheet" type="text/css" href="/framework/compile/css/main.min.css?version=3.0">

I also have a directory of html views and smaller html files. Whenever I update one of these files, I increase the minor version number. For example, /framework/compile/css/main.min.css?version=3.0 becomes /framework/compile/css/main.min.css?version=3.1 after an update.

However, if I do a major site update and change most files, I will push the version number to 4.0. I don't want to have to manually change the version number on every file. Is there an easy and readable way to do this with a javascript variable or something similar.

I'm looking for something like this:

    <link rel="stylesheet" type="text/css" href="/framework/compile/css/main.min.css?version=" + version>

The above is obviously incorrect syntax and does not work.

Body:
Solution Using Pure Javascript

index.html

<html>
  <head>

  </head>
  <body>

    <div>
      Your main content should come BEFORE your javascript.
      The script to include the files should be immediately after your content,
      but before any other script file includes or in page javascript.
    </div>

    <script>

      /*******************************************************
      / Alternate Solution: If you're only wanting to get the
      / most current version of each file, you can just append
      / a datetime stamp to the script tag's url src
      /*******************************************************/

      //get current datetime in milliseconds
      var version = new Date().valueOf();

      /*******************************************************
      / OR you can use manual version numbers as per your ?
      /*******************************************************/

      //variable to hold version number
      var version = "3.0";

      /*******************************************************
      / Add the following ahead of any other scripts before
      / the closing body tag
      /*******************************************************/

      var cssLnk = document.createElement("link");
      cssLnk.setAttribute("rel", "stylesheet");
      cssLnk.setAttribute("type", "text/css");
      cssLnk.setAttribute("href", "/framework/compile/css/main.min.css?version=" + version);

      document.head.appendChild(cssLnk);

      var scr_A = document.createElement("script");
      scr_A.setAttribute("type", "text/javascript");
      scr_A.setAttribute("src", "/framework/compile/js/app.min.js?version=" + version);

      document.body.appendChild(scr_A);

      var scr_B = document.createElement("script");
      scr_B.setAttribute("type", "text/javascript");
      scr_B.setAttribute("src", "/framework/compile/js/app.min.js?version=" + version);

      document.body.appendChild(scr_B);

    </script>

  </body>
</html>


问:
Dagger 2 ContributesAndroidInjector provide activity to module
I'm trying to figure out a less-boilerplate-y way to implement an ActivityModule that is used in all of my app activities. This is my current setup:

ActivityModule:

```<code>@Module
class ActivityModule(private val activity: Activity) {

    @Provides @ActivityScope
    fun providesActivity(): Activity = activity

    @Provides @ActivityContext @ActivityScope
    fun providesContext(): Context = activity

    @Provides @ActivityContext @ActivityScope
    fun providesLayoutInflater(): LayoutInflater = activity.layoutInflater

    @Provides @ActivityContext @ActivityScope
    fun providesResources(): Resources = activity.resources

}
</code>```

AppActivityModule(provides activities for AndroidInjectionModule)

```<code>@Module(subcomponents = [
        AppActivityModule.WelcomeActivityComponent::class
    ])
    internal abstract class AppActivityModule {

        @Binds
        @IntoMap
        @ActivityKey(WelcomeActivity::class)
        abstract fun bindWelcomeActivityInjectorFactory(builder: WelcomeActivityComponent.Builder): AndroidInjector.Factory<out Activity>

        @ActivityScope
        @Subcomponent(modules = [(ActivityModule::class)])
        interface WelcomeActivityComponent : AndroidInjector<WelcomeActivity> {
        @Subcomponent.Builder abstract class Builder : AndroidInjector.Builder<WelcomeActivity>() {
            abstract fun activityModule(myActivityModule: ActivityModule): AndroidInjector.Builder<WelcomeActivity>

            override fun seedInstance(instance: WelcomeActivity) {
                activityModule(ActivityModule(instance))
            }
        }
    }
}
</code>```

What I want AppActivityModule to be instead is:

```<code>@Module
internal abstract class AppActivityModule {
    @ContributesAndroidInjector(modules = [(ActivityModule::class)])
    abstract fun contributeWelcomeActivityInjector(): WelcomeActivity
}
</code>```

But this, quite understandbly, gives me an error /di/AppActivityModule_ContributeWelcomeActivityInjector.java:29: error: @Subcomponent.Builder is missing setters for required modules or subcomponents: [...di.modules.ActivityModule]

My question is - is there a less boilerplate-y way to achieve what I'm trying to do? I know about @Bind and @BindsInstance (from this answer) but this seems to only work if I have a module-per activity and bind the concrete activity type which I don't want in this case - I want ActivityModule to work with all activities.

答:
One way to minimize the boilerplate is to make a generic ActivityModule and then create a small specific Module per Activity.

```<code>// Abstract class so you don't have to provide an instance
@Module
abstract class ActivityModule {

    // No need for ActivityScope: You're always binding to the same Activity, so
    // there's no reason to have Dagger save your Context instance in a Provider.
    @Binds @ActivityContext
    abstract fun providesContext(activity: Activity): Context

    // This doesn't *have* to be in a companion object, but that way
    // Android can do a static dispatch instead of a virtual method dispatch.
    // If you don't need that, just skip the constructor arguments and make these
    // normal methods and you'll be good to go.
    companion object {
        @Provides @ActivityContext
        fun providesLayoutInflater(activity: Activity): LayoutInflater =
            activity.layoutInflater

        @Provides @ActivityContext
        fun providesResources(activity: Activity): Resources = activity.resources
    }
}
</code>```

(In Dagger versions earlier than 2.26, you may need to add @Module on your companion object and @JvmStatic on your @Provides methods as in this previous revision. Since Dagger 2.26 in in January 2020, those are not necessary. Thanks arekolek!)

And your module:

```<code>@Module
internal abstract class AppActivityModule {

    @Module
    internal interface WelcomeActivityModule {
      // The component that @ContributesAndroidInjector generates will bind
      // your WelcomeActivity, but not your Activity. So just connect the two,
      // and suddenly you'll have access via injections of Activity.
      @Binds fun bindWelcomeActivity(activity: WelcomeActivity) : Activity
    }

    @ContributesAndroidInjector(
        modules = [ActivityModule::class, WelcomeActivityModule::class])
    abstract fun contributeWelcomeActivityInjector(): WelcomeActivity
}
</code>```

Note that though this works for Activity, Service, BroadcastReceiver, and others, you might not want to be so quick about it for Fragment. This is because dagger.android handles fragment hierarchies with parent fragments, so from within a child component you might have access to YourApplication, YourActivity, YourParentFragment, and YourChildFragment, and all of their components. If something in YourChildFragmentComponent depends on an unqualified Fragment, it would be ambiguous whether it really wants YourParentFragment or YourChildFragment. That said, this design does make sense for Activities and certain Fragments, so it makes sense to use it (cautiously).

EDIT: What is @ActivityContext doing here?

@ActivityContext here is a qualifier annotation you'd define, which you can use to distinguish bindings of the same type in Dagger and other DI framework, presumably @ApplicationContext Context vs @ActivityContext  Context. It would work to leave it out to try it, but I heavily recommend keeping it and avoiding binding an unqualified Context: Application and Activity contexts may be different, particularly in multi-screen or auto environments, and to get the right resources and data you should be precise about which you use. You can use this one as an example.

Body:
I'm trying to figure out a less-boilerplate-y way to implement an ActivityModule that is used in all of my app activities. This is my current setup:

ActivityModule:

@Module
class ActivityModule(private val activity: Activity) {

    @Provides @ActivityScope
    fun providesActivity(): Activity = activity

    @Provides @ActivityContext @ActivityScope
    fun providesContext(): Context = activity

    @Provides @ActivityContext @ActivityScope
    fun providesLayoutInflater(): LayoutInflater = activity.layoutInflater

    @Provides @ActivityContext @ActivityScope
    fun providesResources(): Resources = activity.resources

}

AppActivityModule(provides activities for AndroidInjectionModule)

@Module(subcomponents = [
        AppActivityModule.WelcomeActivityComponent::class
    ])
    internal abstract class AppActivityModule {

        @Binds
        @IntoMap
        @ActivityKey(WelcomeActivity::class)
        abstract fun bindWelcomeActivityInjectorFactory(builder: WelcomeActivityComponent.Builder): AndroidInjector.Factory<out Activity>

        @ActivityScope
        @Subcomponent(modules = [(ActivityModule::class)])
        interface WelcomeActivityComponent : AndroidInjector<WelcomeActivity> {
        @Subcomponent.Builder abstract class Builder : AndroidInjector.Builder<WelcomeActivity>() {
            abstract fun activityModule(myActivityModule: ActivityModule): AndroidInjector.Builder<WelcomeActivity>

            override fun seedInstance(instance: WelcomeActivity) {
                activityModule(ActivityModule(instance))
            }
        }
    }
}

What I want AppActivityModule to be instead is:

@Module
internal abstract class AppActivityModule {
    @ContributesAndroidInjector(modules = [(ActivityModule::class)])
    abstract fun contributeWelcomeActivityInjector(): WelcomeActivity
}

But this, quite understandbly, gives me an error /di/AppActivityModule_ContributeWelcomeActivityInjector.java:29: error: @Subcomponent.Builder is missing setters for required modules or subcomponents: [...di.modules.ActivityModule]

My question is - is there a less boilerplate-y way to achieve what I'm trying to do? I know about @Bind and @BindsInstance (from this answer) but this seems to only work if I have a module-per activity and bind the concrete activity type which I don't want in this case - I want ActivityModule to work with all activities.

Body:
One way to minimize the boilerplate is to make a generic ActivityModule and then create a small specific Module per Activity.

// Abstract class so you don't have to provide an instance
@Module
abstract class ActivityModule {

    // No need for ActivityScope: You're always binding to the same Activity, so
    // there's no reason to have Dagger save your Context instance in a Provider.
    @Binds @ActivityContext
    abstract fun providesContext(activity: Activity): Context

    // This doesn't *have* to be in a companion object, but that way
    // Android can do a static dispatch instead of a virtual method dispatch.
    // If you don't need that, just skip the constructor arguments and make these
    // normal methods and you'll be good to go.
    companion object {
        @Provides @ActivityContext
        fun providesLayoutInflater(activity: Activity): LayoutInflater =
            activity.layoutInflater

        @Provides @ActivityContext
        fun providesResources(activity: Activity): Resources = activity.resources
    }
}

(In Dagger versions earlier than 2.26, you may need to add @Module on your companion object and @JvmStatic on your @Provides methods as in this previous revision. Since Dagger 2.26 in in January 2020, those are not necessary. Thanks arekolek!)

And your module:

@Module
internal abstract class AppActivityModule {

    @Module
    internal interface WelcomeActivityModule {
      // The component that @ContributesAndroidInjector generates will bind
      // your WelcomeActivity, but not your Activity. So just connect the two,
      // and suddenly you'll have access via injections of Activity.
      @Binds fun bindWelcomeActivity(activity: WelcomeActivity) : Activity
    }

    @ContributesAndroidInjector(
        modules = [ActivityModule::class, WelcomeActivityModule::class])
    abstract fun contributeWelcomeActivityInjector(): WelcomeActivity
}

Note that though this works for Activity, Service, BroadcastReceiver, and others, you might not want to be so quick about it for Fragment. This is because dagger.android handles fragment hierarchies with parent fragments, so from within a child component you might have access to YourApplication, YourActivity, YourParentFragment, and YourChildFragment, and all of their components. If something in YourChildFragmentComponent depends on an unqualified Fragment, it would be ambiguous whether it really wants YourParentFragment or YourChildFragment. That said, this design does make sense for Activities and certain Fragments, so it makes sense to use it (cautiously).

EDIT: What is @ActivityContext doing here?

@ActivityContext here is a qualifier annotation you'd define, which you can use to distinguish bindings of the same type in Dagger and other DI framework, presumably @ApplicationContext Context vs @ActivityContext  Context. It would work to leave it out to try it, but I heavily recommend keeping it and avoiding binding an unqualified Context: Application and Activity contexts may be different, particularly in multi-screen or auto environments, and to get the right resources and data you should be precise about which you use. You can use this one as an example.


问:
how to pass variables inside a <href> tag in the google map's infoWindow
The sample_id shows in the infoWidow but how can it be passed inside the href tag?</p>

```<code>(function (marker, sample) {
    google.maps.event.addListener(marker, "mouseover", function (e) {
    infoWindow.setContent(sample.id+ ' - ' + sample.name + '</br>' +
    '<a href="SampleDetail.aspx?sample_id="'+ sample.id + '> Detail...</a>' );
    infoWindow.open(map, marker);
    });
})(marker, sample);
</code>```

答:
Try something like this:</p>

```<code>"<a href='SampleDetail.aspx?sample_id=" + sample.id + "'> Detail...</a>"
</code>```

Body:
The sample_id shows in the infoWidow but how can it be passed inside the href tag?

(function (marker, sample) {
    google.maps.event.addListener(marker, "mouseover", function (e) {
    infoWindow.setContent(sample.id+ ' - ' + sample.name + '
' +
    ' Detail...' );
    infoWindow.open(map, marker);
    });
})(marker, sample);

Body:
Try something like this:

"<a href='SampleDetail.aspx?sample_id=" + sample.id + "'> Detail...</a>"


问:
AWS S3 auto save folder
Is there a way I can autosave autocad files or changes on the autocad files directly to S3 Bucket?, probably an API I can utilize for this workflow?</p>

答:
While I was not able to quickly find a plug in that does that for you, what you can do is one of the following:

Mount S3 bucket as a drive. You can read more at CloudBerry Drive - Mount S3 bucket as Windows drive

This might create some performance issues with AutoCad.

Sync saved files to S3

You can set a script to run every n minutes that automatically syncs your files to S3 using aws s3 sync. You can read more about AWS S3 Sync here. Your command might look something like

```<code>aws s3 sync /path/to/cad/files s3://bucket-with-cad/project/test
</code>```

Title: AWS S3 auto save folder

Body:
While I was not able to quickly find a plug in that does that for you, what you can do is one of the following:

Mount S3 bucket as a drive. You can read more at CloudBerry Drive - Mount S3 bucket as Windows drive

This might create some performance issues with AutoCad.

Sync saved files to S3

You can set a script to run every n minutes that automatically syncs your files to S3 using aws s3 sync. You can read more about AWS S3 Sync here. Your command might look something like

aws s3 sync /path/to/cad/files s3://bucket-with-cad/project/test


问:
Why is my project building with an unknown Attribute?
So, my code seems to be compiling without errors when it should not compile.

Here, this project has no NuGet packages for AspNetCore.Mvc and hence this should not compile but still it does.

Notice, the ModleBinder is in white color which means it does not recognize this type - still it is compiling.
In another console app of the same VS this behaves fine.

I am using VS 2017 15.4

Some of the things I have already done

restarted VS many times

Deleted the .vs folder

Cleaned and Rebuilt the solution

deleted vs folder and restarted the computer

答:
So, I have found the root cause.

The root cause of the mentioned issue is this line in the .csproj file

```<code> <PropertyGroup>
    <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
 </PropertyGroup>
</code>```

I had to add this line to avoid another error. But it seems this was not the right thing to solve this problem.
Instead this seems to be right fix for my original problem.

Body:
So, I have found the root cause.

The root cause of the mentioned issue is this line in the .csproj file

 <PropertyGroup>
    <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
 </PropertyGroup>

I had to add this line to avoid another error. But it seems this was not the right thing to solve this problem.
Instead this seems to be right fix for my original problem.


问:
PHP users local time
Hey Stackfriends =P
I know about the time() and the date() functuions,
but what I want to achieve is that the user from china gets another time shown than the user from France.
I cannot use JavaScript, because I am also using the local time for some calculations.</p>

答:
Though I've never had to use it, there seems to be some functions enabling you to set a timezone, and other date functions to tell you the difference between the current timezone setting and the GMT. These may help you.

http://php.net/manual/en/datetime.settimezone.php

http://php.net/manual/en/function.date.php

Title: PHP users local time