问:
Selenium.WebDriver 3.0.1 is not compatible with netcoreapp1.1 - C#, VS 2017 Community for Mac
I have a console application using Selenium 3.4.0 and Appium 3.0.0.2 (I do have access to the source code for editing). I am attempting to make a UI using ASP .NET Core Web API, however if I attempt to install the NuGet Selenium and Appium WebDriver packages, I get the following error:
    For Selenium:

```<code>Package Selenium.WebDriver 3.4.0 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1) / win-x86. Package Selenium.WebDriver 3.4.0 supports:
  - net35 (.NETFramework,Version=v3.5)
  - net40 (.NETFramework,Version=v4.0)
</code>```

For Appium

```<code>Package Appium.WebDriver 3.0.0.2 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1). Package Appium.WebDriver 3.0.0.2 supports: net45 (.NETFramework,Version=v4.5)
Package Selenium.WebDriver 3.0.1 is not compatible with netcoreapp1.1   (.NETCoreApp,Version=v1.1) / win-x86. Package Selenium.WebDriver 3.0.1 supports:
  - net35 (.NETFramework,Version=v3.5)
  - net40 (.NETFramework,Version=v4.0)
Checking compatibility for Selenium.Support 3.0.1 with .NETCoreApp,Version=v1.1 (win-x86).
Package Selenium.Support 3.0.1 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1) / win-x86. Package Selenium.Support 3.0.1 supports:
  - net35 (.NETFramework,Version=v3.5)
  - net40 (.NETFramework,Version=v4.0)
Checking compatibility for Castle.Core 3.3.3 with .NETCoreApp,Version=v1.1 (win-x86).
Package Castle.Core 3.3.3 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1) / win-x86. Package Castle.Core 3.3.3 supports:
  - net35 (.NETFramework,Version=v3.5)
  - net40-client (.NETFramework,Version=v4.0,Profile=Client)
  - net45 (.NETFramework,Version=v4.5)
  - sl4 (Silverlight,Version=v4.0)
  - sl5 (Silverlight,Version=v5.0)
</code>```

Is there a way around this error to add the packages? If not, is there a way in which I can have the console application do its own thing while the Web API sends and receives information from it?

I am relatively new to this environment, so please don't assume I know much. From my Googling, I haven't seen many posts similar to this problem, so generality in answering would also be helpful.

Thank you in advance

答: .Net Core is not supported by Selenium at this time, but a Pull Request exists to remedy that. You could try the CoreCompat.Selenium.WebDriver NuGet package in the mean time. The Appium .Net driver uses the official Selenium C# client, so its likely not going to change until the Selenium .Net core PR is accepted.</p>

Body:
I have a console application using Selenium 3.4.0 and Appium 3.0.0.2 (I do have access to the source code for editing). I am attempting to make a UI using ASP .NET Core Web API, however if I attempt to install the NuGet Selenium and Appium WebDriver packages, I get the following error:
    For Selenium:

Package Selenium.WebDriver 3.4.0 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1) / win-x86. Package Selenium.WebDriver 3.4.0 supports:
  - net35 (.NETFramework,Version=v3.5)
  - net40 (.NETFramework,Version=v4.0)

For Appium

Package Appium.WebDriver 3.0.0.2 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1). Package Appium.WebDriver 3.0.0.2 supports: net45 (.NETFramework,Version=v4.5)
Package Selenium.WebDriver 3.0.1 is not compatible with netcoreapp1.1   (.NETCoreApp,Version=v1.1) / win-x86. Package Selenium.WebDriver 3.0.1 supports:
  - net35 (.NETFramework,Version=v3.5)
  - net40 (.NETFramework,Version=v4.0)
Checking compatibility for Selenium.Support 3.0.1 with .NETCoreApp,Version=v1.1 (win-x86).
Package Selenium.Support 3.0.1 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1) / win-x86. Package Selenium.Support 3.0.1 supports:
  - net35 (.NETFramework,Version=v3.5)
  - net40 (.NETFramework,Version=v4.0)
Checking compatibility for Castle.Core 3.3.3 with .NETCoreApp,Version=v1.1 (win-x86).
Package Castle.Core 3.3.3 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1) / win-x86. Package Castle.Core 3.3.3 supports:
  - net35 (.NETFramework,Version=v3.5)
  - net40-client (.NETFramework,Version=v4.0,Profile=Client)
  - net45 (.NETFramework,Version=v4.5)
  - sl4 (Silverlight,Version=v4.0)
  - sl5 (Silverlight,Version=v5.0)

Is there a way around this error to add the packages? If not, is there a way in which I can have the console application do its own thing while the Web API sends and receives information from it?

I am relatively new to this environment, so please don't assume I know much. From my Googling, I haven't seen many posts similar to this problem, so generality in answering would also be helpful.

Thank you in advance


来源: stackexchange

答: Unfortunately, Analytics does not today provide this visualization type. Could you please submit it on our UserVoice? </p>

ContentLicense: CC BY-SA 3.0

Title: MS App Analytics timeline chart

Body:
I have data in the following format. Is it possible to create a time line chart using App Analytics. I am trying to easily identify the calls which overlap in my DataSet.

| Start Time           | End Time             | Call Name           | Duration
|----------------------|----------------------|---------------------|----------
| 17:41:30.5001642Z    | 17:41:30.703291Z     | CreateDraftEnvelope | 203
| 17:41:31.0711234Z    | 17:41:31.0867211Z    | CreateLock          | 21
| 17:41:31.1189342Z    | 17:41:31.1345349Z    | addDocument         | 17
| 17:41:31.1961265Z    | 17:41:31.2117613Z    | addDocument         | 17
| 17:41:31.4243498Z    | 17:41:31.4399953Z    | addDocument         | 19
| 17:41:31.5242518Z    | 17:41:31.5398738Z    | addDocument         | 17

I am looking for a chart as follows


问:
How to get a button element made in the DOM, run a function
I created a button element using javascript, and now would like to know how to find that element or select it and get it to call this function:</p>

```<code>    function test() {
      alert("it works!");
    }
</code>```

答:
```<code>var btn = document.createElement("BUTTON");
btn.onclick = function() { test(); }
var t = document.createTextNode("ok");
btn.appendChild(t);
document.body.appendChild(btn);
</code>```

https://jsfiddle.net/k30nf9oo/

Body:
I created a button element using javascript, and now would like to know how to find that element or select it and get it to call this function:

    function test() {
      alert("it works!");
    }

Body:
var btn = document.createElement("BUTTON");
btn.onclick = function() { test(); }
var t = document.createTextNode("ok");
btn.appendChild(t);
document.body.appendChild(btn);

https://jsfiddle.net/k30nf9oo/


问:
What exactly is the difference between the Xilinx warnings XST:1710 and XST:1895?
Can anyone please explain the difference between the two Xilinx warnings:

Xst:1710 - FF/Latch reg_0 (without init value) has a constant value
  of 0 in block . This FF/Latch will be trimmed during the
  optimization process.

Xst:1895 - Due to other FF/Latch trimming, FF/Latch reg_1 (without
  init value) has a constant value of 0 in block . This FF/Latch
  will be trimmed during the optimization process.

Assuming "reg" is a byte long register.

答:
reg_0 is optimized out (aka trimmed) because it is never assigned but is referenced during the assignment of other registers or nets. Since it does not has a specified init value the synthesizer is defaulting to zero. Therefore the synthesizer can save flop(s) and any use of reg_0 in the design will be treated as logic 0.

reg_1 is optimized out because its value is depended on other flops that were already optimized out. Using the example below: reg_1 is depended on reg_0. Since reg_0 will always be zero (because it is never assigned), reg_1 will also always be zero. Hence why it says "Due to other FF/Latch trimming". The synthesizer saves flop(s) and any use of reg_1 in the design will be treated as logic 0.

```<code>reg [7:0] reg_0;
reg [7:0] reg_1;
always @(posedge clk) begin
  reg_1 <= in & reg_0;
end
</code>```

In summary:

Xst:1710 - trimmed because never assigned

Xst:1895 - trimmed because depended logic was trimmed

Same outcome but for different reasons.

If there is a bug in the design, resolving Xst:1710 issues it could automatically resolve the Xst:1895. If there isn't a bug, then these warnings point to dead code.

Body:
reg_0 is optimized out (aka trimmed) because it is never assigned but is referenced during the assignment of other registers or nets. Since it does not has a specified init value the synthesizer is defaulting to zero. Therefore the synthesizer can save flop(s) and any use of reg_0 in the design will be treated as logic 0.

reg_1 is optimized out because its value is depended on other flops that were already optimized out. Using the example below: reg_1 is depended on reg_0. Since reg_0 will always be zero (because it is never assigned), reg_1 will also always be zero. Hence why it says "Due to other FF/Latch trimming". The synthesizer saves flop(s) and any use of reg_1 in the design will be treated as logic 0.

reg [7:0] reg_0;
reg [7:0] reg_1;
always @(posedge clk) begin
  reg_1 <= in & reg_0;
end

In summary:

Xst:1710 - trimmed because never assigned

Xst:1895 - trimmed because depended logic was trimmed

Same outcome but for different reasons.

If there is a bug in the design, resolving Xst:1710 issues it could automatically resolve the Xst:1895. If there isn't a bug, then these warnings point to dead code.


问:
An exception is thrown if read string from remote url in Xamarin Forms C# with Visual Studio
I met a strange exception while I tried to get data from remote url:

```<code>HttpClient client = new HttpClient(new AndroidClientHandler());
string response = client.GetStringAsync( "url" ).Result;
</code>```

and I got an exception like:

Unable to convert instance of type 'Java.Net.URLConnectionInvoker' to type 'Java.Net.HttpURLConnection'.

I tried to get string by link https://www.pricy.ro/product/pachet-a--suport-tv-23--42----kit-curatare---cablu-hdmi-1-4--3m-582813c69d126a2d3cba8f5c/ (where error occur) but for other link, seems work: https://www.pricy.ro/product/navigatie-gps-serioux-urban-pilot-upq700-7-inchi-5788d87e9d126a5cacfac2bc/

I don't know why.

And the stack trace:

答:
I fixed above issue by using:

```<code>var httpClient = new HttpClient(new NativeMessageHandler());
</code>```

instead of

```<code>var httpClient = new HttpClient(new AndroidClientHandler());
</code>```

For the first line of code, install ModernHttpClient from Nuget.

Body:
I met a strange exception while I tried to get data from remote url:

HttpClient client = new HttpClient(new AndroidClientHandler());
string response = client.GetStringAsync( "url" ).Result;

and I got an exception like:

Unable to convert instance of type 'Java.Net.URLConnectionInvoker' to type 'Java.Net.HttpURLConnection'.

I tried to get string by link https://www.pricy.ro/product/pachet-a--suport-tv-23--42----kit-curatare---cablu-hdmi-1-4--3m-582813c69d126a2d3cba8f5c/ (where error occur) but for other link, seems work: https://www.pricy.ro/product/navigatie-gps-serioux-urban-pilot-upq700-7-inchi-5788d87e9d126a5cacfac2bc/

I don't know why.

And the stack trace:

Body:
I fixed above issue by using:

var httpClient = new HttpClient(new NativeMessageHandler());

instead of

var httpClient = new HttpClient(new AndroidClientHandler());

For the first line of code, install ModernHttpClient from Nuget.


问:
How to change color of toolbar title in Android?
I am developing an android app and I want to make the title of the toolbar white color.

I have removed the default toolbar and added a toolbar to my activities and am unable to figure out how to change the color of the title of the toolbar to white

MainActivity.java

```<code>package com.example.acer.videoapp;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(getResources().getString(R.string.app_name));
        //toolbar.setTitleTextColor(white);
        listView = (ListView) findViewById(R.id.listView);

        ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_expandable_list_item_1,getResources().getStringArray(R.array.subjects));

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                intent.putExtra("Subject", listView.getItemAtPosition(i).toString());
                startActivity(intent);
            }
        });
        listView.setAdapter(mAdapter);

    }
}
</code>```

答:
Modify your styles.xml :

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <resources>
         <style name="MyTheme" parent="@android:style/Theme.Holo.Light">
            <item name="android:actionBarStyle">@style/MyTheme.ActionBarStyle</item>
         </style>

         <style name="MyTheme.ActionBarStyle" parent="@android:style/Widget.Holo.Light.ActionBar">
            <item name="android:titleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
         </style>

         <style name="MyTheme.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title">
            <item name="android:textColor">@color/white</item>
        </style>
    </resources>
</code>```

Then assign the style to your toolbar

```<code><android.support.v7.widget.Toolbar
     ...
     app:theme="@style/MyTheme">

</android.support.v7.widget.Toolbar>
</code>```

Body:
I am developing an android app and I want to make the title of the toolbar white color.

I have removed the default toolbar and added a toolbar to my activities and am unable to figure out how to change the color of the title of the toolbar to white

MainActivity.java

package com.example.acer.videoapp;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(getResources().getString(R.string.app_name));
        //toolbar.setTitleTextColor(white);
        listView = (ListView) findViewById(R.id.listView);

        ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_expandable_list_item_1,getResources().getStringArray(R.array.subjects));

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                intent.putExtra("Subject", listView.getItemAtPosition(i).toString());
                startActivity(intent);
            }
        });
        listView.setAdapter(mAdapter);

    }
}

Body:
Modify your styles.xml :

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
         <style name="MyTheme" parent="@android:style/Theme.Holo.Light">
            <item name="android:actionBarStyle">@style/MyTheme.ActionBarStyle</item>
         </style>

         <style name="MyTheme.ActionBarStyle" parent="@android:style/Widget.Holo.Light.ActionBar">
            <item name="android:titleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
         </style>

         <style name="MyTheme.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title">
            <item name="android:textColor">@color/white</item>
        </style>
    </resources>

Then assign the style to your toolbar

<android.support.v7.widget.Toolbar
     ...
     app:theme="@style/MyTheme">

</android.support.v7.widget.Toolbar>


问:
Show Different type of Data in Same Visual In Power BI
I have a scenario where I have a column in a table which is having multiple project list.
And each project is of different type.
And the types are for ex FP and T&M.
Now as we can see in First image , Charge Ratio is showing for FP type Projects and Second Image showing Bill Utilization for T&M Projects

.

My Requirement is ,I want to show both The Charge Ratio and Bill Utilization in One Visual According to the Project Type.
I have a slicer which user can choose the projects.
If the choosen project is T&M type then it should show visual according to that type.
If it is FP then in that line chart only, i would like to show the visuals according to that type.

Note:- I don't want to use the slicer for TYPE selection

Please Give me suggestion.

Thank You.

答:
You can show both the charge ratio & bill utilization in a single visual.

Simple Solution

A simple solution would be to remove Project from your chart legend and instead have 2 measures on your chart: one for Charge Ratio and one for Bill Utilization. Since only one measure ever applies to any given project, the chart will only ever show one line for any given project. However, you'd need to use the legend to identify what measure is being shown. Further, you'd need to ensure only one project is ever selected at a time: otherwise, it will aggregate the ratios of different projects together.

Alternative Solution

Since the Charge Ratio only applies to FP projects, and Bill Utilization only applies to T&M projects, you can create a single calculated column that identifies the type of project and shows either the Charge Ratio or the Bill Utilization as appropriate. E.g.

```<code>Ratio =
IF (
  RELATED ( 'Project'[Project Type] ) = "FP",
  [Charge Ratio],
  [Bill Utilization]
)
</code>```

You could use the same logic to create a "title" column too:

```<code>Ratio Name =
IF (
    RELATED ( 'Project'[Project Type] ) = "FP",
    "Charge Ratio By Month (FP)",
    "Bill Utilization By Month (T&M)"
)
</code>```

Finally, you can have a title measure to handle when multiple projects are selected (possibly of multiple types):

```<code>Ratio Name Measure =
IF (
    HASONEVALUE ( 'Ratios'[Ratio Name] ),
    MAX ( 'Ratios'[Ratio Name] ),
    "Charge Ratio & Bill Utilization By Month"
)
</code>```

Throw that measure into a multi-row card just above your chart, and it looks like this:

Body:
You can show both the charge ratio & bill utilization in a single visual.

Simple Solution

A simple solution would be to remove Project from your chart legend and instead have 2 measures on your chart: one for Charge Ratio and one for Bill Utilization. Since only one measure ever applies to any given project, the chart will only ever show one line for any given project. However, you'd need to use the legend to identify what measure is being shown. Further, you'd need to ensure only one project is ever selected at a time: otherwise, it will aggregate the ratios of different projects together.

Alternative Solution

Since the Charge Ratio only applies to FP projects, and Bill Utilization only applies to T&M projects, you can create a single calculated column that identifies the type of project and shows either the Charge Ratio or the Bill Utilization as appropriate. E.g.

Ratio =
IF (
  RELATED ( 'Project'[Project Type] ) = "FP",
  [Charge Ratio],
  [Bill Utilization]
)

You could use the same logic to create a "title" column too:

Ratio Name =
IF (
    RELATED ( 'Project'[Project Type] ) = "FP",
    "Charge Ratio By Month (FP)",
    "Bill Utilization By Month (T&M)"
)

Finally, you can have a title measure to handle when multiple projects are selected (possibly of multiple types):

Ratio Name Measure =
IF (
    HASONEVALUE ( 'Ratios'[Ratio Name] ),
    MAX ( 'Ratios'[Ratio Name] ),
    "Charge Ratio & Bill Utilization By Month"
)

Throw that measure into a multi-row card just above your chart, and it looks like this:


问:
pandas / numpy np.where(df['x'].str.contains('y')) vs np.where('y' in df['x'])
As a newb to python and pandas, I tried:

```<code>df_rows = np.where('y' in df['x'])[0]
for i in df_rows:
    print df_rows.iloc[i]
</code>```

returned no rows, but

```<code>df_rows = np.where(df['x'].str.contains('y'))[0]
for i in df_rows:
    print df_rows.iloc[i]
</code>```

did work and returned rows containing 'y' in df['x'].

What am I missing? Why did the first form fail? (Python 2.7)

答:
Pandas requires specific syntax for things to work. Looking for a str y using the operator in checks for membership of the string y in a pandas Series.

```<code>>>> df = pd.DataFrame({'x': ['hiya', 'howdy', 'hello']})
>>> df
       x
0   hiya
1  howdy
2  hello
>>> df_rows = np.where('y' in df['x'])[0]
>>> df_rows
array([], dtype=int64)
>>> df_rows = np.where(df['x'].str.contains('y'))[0]
>>> df_rows
array([0, 1], dtype=int64)
</code>```

Try this and notice it returns one bool instead of three (like we might first think since there are three items in the series):

```<code>>>> 'y' in df['x']
False
>>> 'hiya' in df['x']
False
>>> 'hiya' in df['x'].values
True
</code>```

You always need to think to yourself: "am I looking for items in a series, or am I looking for strings within the items within the series?"

For items in a series, use isin:

```<code>df['x'].isin(['hello'])
</code>```

For strings within an item, use .str.{whatever} (or .apply(lambda s: s)):

```<code>>>> df['x'].str.contains('y')
0     True
1     True
2    False
Name: x, dtype: bool
>>> df['x'].apply(lambda s: 'y' in s)
0     True
1     True
2    False
Name: x, dtype: bool
</code>```

Body:
As a newb to python and pandas, I tried:

df_rows = np.where('y' in df['x'])[0]
for i in df_rows:
    print df_rows.iloc[i]

returned no rows, but

df_rows = np.where(df['x'].str.contains('y'))[0]
for i in df_rows:
    print df_rows.iloc[i]

did work and returned rows containing 'y' in df['x'].

What am I missing? Why did the first form fail? (Python 2.7)

Body:
Pandas requires specific syntax for things to work. Looking for a str y using the operator in checks for membership of the string y in a pandas Series.

>>> df = pd.DataFrame({'x': ['hiya', 'howdy', 'hello']})
>>> df
       x
0   hiya
1  howdy
2  hello
>>> df_rows = np.where('y' in df['x'])[0]
>>> df_rows
array([], dtype=int64)
>>> df_rows = np.where(df['x'].str.contains('y'))[0]
>>> df_rows
array([0, 1], dtype=int64)

Try this and notice it returns one bool instead of three (like we might first think since there are three items in the series):

>>> 'y' in df['x']
False
>>> 'hiya' in df['x']
False
>>> 'hiya' in df['x'].values
True

You always need to think to yourself: "am I looking for items in a series, or am I looking for strings within the items within the series?"

For items in a series, use isin:

df['x'].isin(['hello'])

For strings within an item, use .str.{whatever} (or .apply(lambda s: s)):

>>> df['x'].str.contains('y')
0     True
1     True
2    False
Name: x, dtype: bool
>>> df['x'].apply(lambda s: 'y' in s)
0     True
1     True
2    False
Name: x, dtype: bool


问:
Why is #create failing on this FactoryGirl object?
I am trying to test the Quotes#create controller action but am having trouble understanding a failure. I am using Devise and FactoryGirl and the Quotes model belongs_to :user. The rspec failure message is No route matches {:action=>"show", :controller=>"quotes", :id=>nil} missing required keys: [:id]. The FactoryGirl created Quote object is passed the user:

```<code>let(:user) { FactoryGirl.create(:user) }
let(:quote) { FactoryGirl.create(:quote, user: user) }
</code>```

It seems that neither the record is being saved in the database, nor therfore can the records [:id] be passed back to be rendered to the show action.

Any guidance appreciated.

quotes_controller.rb

```<code>class QuotesController < ApplicationController
  before_action :authenticate_user!, only: [ :new, :create, :edit, :update, :destroy ]
  before_action :owners_only, only: [ :edit, :update, :destroy ]

  def new
    @quote = Quote.new
  end

  def create
    # @quote = @user.quotes.new(quote_params)
    @quote = Quote.new(quote_params)
    if @quote.save
        redirect_to quote_url(@quote), notice: 'Quote request created'
    else
      render :new
    end
  end

  def show
    @quote = Quote.find(params[:id])
  end

  def index
    @quotes = Quote.all
  end

  def edit
  end

  def update
    if @quote.update_attributes(quote_params)
      redirect_to quote_path(@quote)
    else
      render :edit
    end
  end

  def destroy
    @quote.destroy
    redirect_to quotes_path
  end

private

  def quote_params
    params.require(:quote).permit(:gla, :prev_cover, :co_name, :co_number, :postcode, :industry, :lives_overseas,
                                  :scheme_start_date, :payment_frequency, :commission_level)
  end

  def owners_only
    @quote = Quote.find(params[:id])
    if current_user != @quote.user
      redirect_to quotes_path
    end
  end
end
</code>```

quote.rb model:

```<code>class Quote < ApplicationRecord
    belongs_to :user

    enum industry:          [ :financial_services, :architect, :business_consultancy ]
    enum payment_frequency: [ :annually, :monthly ]
end
</code>```

users.rb:

```<code>FactoryGirl.define do
  factory :user do
    sequence(:email) { |n| "test#{}@tes.com" }
    password "12345678"

    factory :user2 do
    end
  end
end
</code>```

quotes.rb

```<code>FactoryGirl.define do
  factory :quote do
    prev_cover true
    sequence(:co_name) { |n| "Acme Co #{n}" }
    co_number 9999
    postcode "al1 1aa"
    industry :financial_services
    lives_overseas true
    scheme_start_date "2018-01-01"
    payment_frequency :monthly
    commission_level 12
    gla 1

    factory :quote2 do
    end
  end
end
</code>```

quote_controller_spec.rb

```<code>RSpec.describe QuotesController, type: :controller do
    describe "signed in user" do

        let(:user) { FactoryGirl.create(:user) }
        let(:quote) { FactoryGirl.create(:quote, user: user) } #user.id not getting through here?

        before do
            sign_in(user)
        end

        describe "POST create" do

            context "valid data" do
                let(:valid_data) { FactoryGirl.attributes_for(:quote) } #user.id not getting through here?
                it "redirects to quote#show" do
                    post :create, params: { quote: valid_data }
                    expect(response).to redirect_to(quote_path(assigns[:quote]))
                end

                it " creates a new quote in the database" do
                    expect {
                        post :create, params: { quote: valid_data }
                    }.to change(Quote, :count).by(1)
                end
            end
        end
    end
end
</code>```

rspec output:

```<code> 1) QuotesController signed in user POST create valid data redirects to quote#show
     Failure/Error: expect(response).to redirect_to(quote_path(assigns[:quote]))

     ActionController::UrlGenerationError:
       No route matches {:action=>"show", :controller=>"quotes", :id=>nil} missing required keys: [:id]
     # ./spec/controllers/quotes_controller_spec.rb:46:in `block (5 levels) in <top (required)>'

  2) QuotesController signed in user POST create valid data  creates a new quote in the database
     Failure/Error:
       expect {
        post :create, params: { quote: valid_data }
       }.to change(Quote, :count).by(1)

       expected #count to have changed by 1, but was changed by 0
     # ./spec/controllers/quotes_controller_spec.rb:50:in `block (5 levels) in <top (required)>'
</code>```

It seems that the user_id is not getting through with the :valid_data object let(:valid_data) { FactoryGirl.attributes_for(:quote) }. Though the :quote object was given the :user object in:

```<code>let(:user) { FactoryGirl.create(:user) }
let(:quote) { FactoryGirl.create(:quote, user: user) }
</code>```

It;s just not getting through, I think this is where the issue lies here, any advice?

答:
Based on your comments, I recommend changing your create action to:

def create
  @quote = current_user.quotes.new(quote_params)
  if @quote.save
      redirect_to quote_url(@quote), notice: 'Quote request created'
  else
    render :new
  end
end

Body:
I am trying to test the Quotes#create controller action but am having trouble understanding a failure. I am using Devise and FactoryGirl and the Quotes model belongs_to :user. The rspec failure message is No route matches {:action=>"show", :controller=>"quotes", :id=>nil} missing required keys: [:id]. The FactoryGirl created Quote object is passed the user:

let(:user) { FactoryGirl.create(:user) }
let(:quote) { FactoryGirl.create(:quote, user: user) }

It seems that neither the record is being saved in the database, nor therfore can the records [:id] be passed back to be rendered to the show action.

Any guidance appreciated.

quotes_controller.rb

class QuotesController < ApplicationController
  before_action :authenticate_user!, only: [ :new, :create, :edit, :update, :destroy ]
  before_action :owners_only, only: [ :edit, :update, :destroy ]

  def new
    @quote = Quote.new
  end

  def create
    # @quote = @user.quotes.new(quote_params)
    @quote = Quote.new(quote_params)
    if @quote.save
        redirect_to quote_url(@quote), notice: 'Quote request created'
    else
      render :new
    end
  end

  def show
    @quote = Quote.find(params[:id])
  end

  def index
    @quotes = Quote.all
  end

  def edit
  end

  def update
    if @quote.update_attributes(quote_params)
      redirect_to quote_path(@quote)
    else
      render :edit
    end
  end

  def destroy
    @quote.destroy
    redirect_to quotes_path
  end

private

  def quote_params
    params.require(:quote).permit(:gla, :prev_cover, :co_name, :co_number, :postcode, :industry, :lives_overseas,
                                  :scheme_start_date, :payment_frequency, :commission_level)
  end

  def owners_only
    @quote = Quote.find(params[:id])
    if current_user != @quote.user
      redirect_to quotes_path
    end
  end
end

quote.rb model:

class Quote < ApplicationRecord
    belongs_to :user

    enum industry:          [ :financial_services, :architect, :business_consultancy ]
    enum payment_frequency: [ :annually, :monthly ]
end

users.rb:

FactoryGirl.define do
  factory :user do
    sequence(:email) { |n| "test#{}@tes.com" }
    password "12345678"

    factory :user2 do
    end
  end
end

quotes.rb

FactoryGirl.define do
  factory :quote do
    prev_cover true
    sequence(:co_name) { |n| "Acme Co #{n}" }
    co_number 9999
    postcode "al1 1aa"
    industry :financial_services
    lives_overseas true
    scheme_start_date "2018-01-01"
    payment_frequency :monthly
    commission_level 12
    gla 1

    factory :quote2 do
    end
  end
end

quote_controller_spec.rb

RSpec.describe QuotesController, type: :controller do
    describe "signed in user" do

        let(:user) { FactoryGirl.create(:user) }
        let(:quote) { FactoryGirl.create(:quote, user: user) } #user.id not getting through here?

        before do
            sign_in(user)
        end

        describe "POST create" do

            context "valid data" do
                let(:valid_data) { FactoryGirl.attributes_for(:quote) } #user.id not getting through here?
                it "redirects to quote#show" do
                    post :create, params: { quote: valid_data }
                    expect(response).to redirect_to(quote_path(assigns[:quote]))
                end

                it " creates a new quote in the database" do
                    expect {
                        post :create, params: { quote: valid_data }
                    }.to change(Quote, :count).by(1)
                end
            end
        end
    end
end

rspec output:

 1) QuotesController signed in user POST create valid data redirects to quote#show
     Failure/Error: expect(response).to redirect_to(quote_path(assigns[:quote]))

     ActionController::UrlGenerationError:
       No route matches {:action=>"show", :controller=>"quotes", :id=>nil} missing required keys: [:id]
     # ./spec/controllers/quotes_controller_spec.rb:46:in `block (5 levels) in <top (required)>'

  2) QuotesController signed in user POST create valid data  creates a new quote in the database
     Failure/Error:
       expect {
        post :create, params: { quote: valid_data }
       }.to change(Quote, :count).by(1)

       expected #count to have changed by 1, but was changed by 0
     # ./spec/controllers/quotes_controller_spec.rb:50:in `block (5 levels) in <top (required)>'

It seems that the user_id is not getting through with the :valid_data object let(:valid_data) { FactoryGirl.attributes_for(:quote) }. Though the :quote object was given the :user object in:

let(:user) { FactoryGirl.create(:user) }
let(:quote) { FactoryGirl.create(:quote, user: user) }

It;s just not getting through, I think this is where the issue lies here, any advice?


问:
How to create IObservable from delegate that does not inherit from EventHandler?
I am using Accord (previously AForge) to capture image frames from a webcam.

These images arrive via a VideoCaptureDevice.NewFrame event:

```<code>public delegate void NewFrameEventHandler(object sender, NewFrameEventArgs eventArgs);

public class NewFrameEventArgs : EventArgs
{
    public Bitmap Frame { get; }

    public NewFrameEventArgs(Bitmap frame);
}
</code>```

The problem is, I tried to use Observable.FromEvent, but got lost in the many possible overloads:

```<code>void Run()
{
    var videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

    VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);

    // regular way
    videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);

    // intended rx way
    var receivedFrames = Observable.FromEvent(????)    /////////// How?
}

void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
    // do something
}
</code>```

I know I cannot use Observable.FromEventPattern, but don't know what to use instead, much less how.

答:
Try the following:

```<code>var receivedFrames = Observable.FromEventPattern<NewFrameEventHandler, NewFrameEventArgs>(
  handler => handler.Invoke,
  h => videoSource.NewFrame += h,
  h => videoSource.NewFrame -= h);
</code>```

When I was first learning Rx, I found the following site very helpful: IntroToRx (link goes to portion where I found this example).

Body:
I am using Accord (previously AForge) to capture image frames from a webcam.

These images arrive via a VideoCaptureDevice.NewFrame event:

public delegate void NewFrameEventHandler(object sender, NewFrameEventArgs eventArgs);

public class NewFrameEventArgs : EventArgs
{
    public Bitmap Frame { get; }

    public NewFrameEventArgs(Bitmap frame);
}

The problem is, I tried to use Observable.FromEvent, but got lost in the many possible overloads:

void Run()
{
    var videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

    VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);

    // regular way
    videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);

    // intended rx way
    var receivedFrames = Observable.FromEvent(????)    /////////// How?
}

void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
    // do something
}

I know I cannot use Observable.FromEventPattern, but don't know what to use instead, much less how.

Body:
Try the following:

var receivedFrames = Observable.FromEventPattern<NewFrameEventHandler, NewFrameEventArgs>(
  handler => handler.Invoke,
  h => videoSource.NewFrame += h,
  h => videoSource.NewFrame -= h);

When I was first learning Rx, I found the following site very helpful: IntroToRx (link goes to portion where I found this example).


问:
Using Win32 TextOut to draw text at an angle
I'm using GDI to draw text onto a device context, and I noticed that the kerning or character placement is different if the angle is exactly 0, 90, 180, or 270. As soon as I increase the angle by 1, the character placement differs noticeably.

Rather than creating an HFONT with the angle, I am using ModifyWorldTransform to transform the device context's world coordinates, and then I use TextOut to draw the text onto the device context.

I think that GDI is using font hints or some other special technique when the text is being drawn at exact multiples of 90 degrees, but not for any other angle.

Is there a way to disable this hinting, so that text rendered at 0 degrees does not differ significantly from text rendered at 1 degree?

Here's an example of what I mean (Monotype Corsiva font):

0 degrees:

1 degree:

For some fonts, such as Arial or Tahoma, it is not as noticeable, but I would like to get rid of the difference entirely, even if it means the text is not rendered as best it can.

答:
I think this is due to anti-aliasing rather than font hints. You could try the following:

Disable (font) AA, but this will not yield acceptable results.

Create font handles for every possible angle and see if the problem persists. I assume it doesn't, but it's not a pretty solution.

Render the text to a bitmap (e.g. using CreateCompatibleBitmap() ) render the text to it and then render the rotated bitmap. This depends on how often you need different rotations / different text.

Play with fdwOutputPrecision and fdwQuality in CreateFont(). This could be the easiest solution, but you'd have to experiment a little bit I guess.

hth

ContentLicense: CC BY-SA 2.5


问:
Divide a rectangle into 2 triangles along diagonal using css
I want to make a div into 2 triangles (as shown in below, no problem if 1 is background of parent) upper one with one color and lower one with another. I dont mind how it is implemented but i want to do it in css (not javascript). I tried with css rotation, (code below), but its not responsive. In smaller or wider screen it is distorted . Any way to implement this in css?

body {
  background: #eee;
}

.darker {
  position: fixed;
  top: -94%;
  left: -10%;
  width: 150%;
  height: 150%;
  background: #dd4f39;
  -webkit-transform: rotate(30deg);
          transform: rotate(30deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="darker"> </div></code>```

答:
You can do that with a skewed pseudo element. The main trick is to keep the aspect ratio the same or else the sloped angle will fail

Fiddle demo

Stack snippet Note 1

body {
  background: #eee;
}
.darker {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  padding-top: 50%;
  background: #dd4f39;
  overflow: hidden;
}
.darker::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: gray;
  transform: skewY(26.5deg);
  transform-origin: left top;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="darker"></div></code>```

Optionally, you can add media query to control the angle at different screen sizes

Fiddle demo 2

With a tiny script running when window resize's, you can control the angle and make it fully responsive both horizontally and vertically.

Note 1 Based on a comment, the Stack snippet might not work properly, and if, try the fiddle demos.

Body:
You can do that with a skewed pseudo element. The main trick is to keep the aspect ratio the same or else the sloped angle will fail

Fiddle demo

Stack snippet Note 1

body {
  background: #eee;
}
.darker {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  padding-top: 50%;
  background: #dd4f39;
  overflow: hidden;
}
.darker::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: gray;
  transform: skewY(26.5deg);
  transform-origin: left top;
}

<div class="darker"></div>

Optionally, you can add media query to control the angle at different screen sizes

Fiddle demo 2

With a tiny script running when window resize's, you can control the angle and make it fully responsive both horizontally and vertically.

Note 1 Based on a comment, the Stack snippet might not work properly, and if, try the fiddle demos.


问:
SharedPreferences Logout not working
I have 2 Activities, Authentication and Mainpage.

In Authentication, it checks if the user is logged in, if the user is logged in, redirect it to Mainpage.class. This is how Authentication checks if the user is logged in and redirect it.

```<code>SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
    Intent intent = new Intent(this, Mainpage.class);
    startActivity(intent);
}
</code>```

In Mainpage, I have a button which is a logout button and onClick event it use the logOut function that I've created. This is how logout button works:

```<code>void logOut(){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.apply();
    finish();

    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);
}
</code>```

The problem here is when I click the logout button, I just kept redirecting to Mainpage.

答:
Replace your this line of code

```<code> blockEdit.apply();
</code>```

with

```<code> blockEdit.commit();
</code>```

Followed by your activity calling intent.Hope it helps.

Title: SharedPreferences Logout not working

Body:
I have 2 Activities, Authentication and Mainpage.

In Authentication, it checks if the user is logged in, if the user is logged in, redirect it to Mainpage.class. This is how Authentication checks if the user is logged in and redirect it.

SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
    Intent intent = new Intent(this, Mainpage.class);
    startActivity(intent);
}

In Mainpage, I have a button which is a logout button and onClick event it use the logOut function that I've created. This is how logout button works:

void logOut(){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.apply();
    finish();

    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);
}

The problem here is when I click the logout button, I just kept redirecting to Mainpage.

Body:
Replace your this line of code

 blockEdit.apply();

with

 blockEdit.commit();

Followed by your activity calling intent.Hope it helps.


问:
How do I compute the frequency/table of categorical variables by group with R data.table?
I have the following data.table with R

```<code>library(data.table)
dt = data.table(ID = c("person1", "person1", "person1", "person2", "person2", "person2", "person2", "person2", ...), category = c("red", "red", "blue", "red", "red", "blue", "green", "green", ...))

dt
ID         category
person1    red
person1    red
person1    blue
person2    red
person2    red
person2    blue
person2    green
person2    green
person3    blue
....
</code>```

I am looking how to create a "frequency" of the categorical variables red, blue, green for each unique ID, and then expand these columns to record the counts for each. The resulting data.table would look like this:

```<code>dt
ID        red    blue    green
person1   2      1       0
person2   2      1       2
...
</code>```

I incorrectly thought the correct way to start this with data.table would be to compute the table() by group, e.g.

```<code>dt[, counts :=table(category), by=ID]
</code>```

But this appears to count the total number of categorical values by group ID. This also doesn't solve my problem of "expanding" the data.table.

What is the correct way to do this?

答:
Like this?

```<code>library(data.table)
library(dplyr)
dt[, .N, by = .(ID, category)] %>% dcast(ID ~ category)
</code>```

If you want to add these columns to the original data.table

```<code>counts <- dt[, .N, by = .(ID, category)] %>% dcast(ID ~ category)
counts[is.na(counts)] <- 0
output <- merge(dt, counts, by = "ID")
</code>```

Body:
I have the following data.table with R

library(data.table)
dt = data.table(ID = c("person1", "person1", "person1", "person2", "person2", "person2", "person2", "person2", ...), category = c("red", "red", "blue", "red", "red", "blue", "green", "green", ...))

dt
ID         category
person1    red
person1    red
person1    blue
person2    red
person2    red
person2    blue
person2    green
person2    green
person3    blue
....

I am looking how to create a "frequency" of the categorical variables red, blue, green for each unique ID, and then expand these columns to record the counts for each. The resulting data.table would look like this:

dt
ID        red    blue    green
person1   2      1       0
person2   2      1       2
...

I incorrectly thought the correct way to start this with data.table would be to compute the table() by group, e.g.

dt[, counts :=table(category), by=ID]

But this appears to count the total number of categorical values by group ID. This also doesn't solve my problem of "expanding" the data.table.

What is the correct way to do this?

Body:
Like this?

library(data.table)
library(dplyr)
dt[, .N, by = .(ID, category)] %>% dcast(ID ~ category)

If you want to add these columns to the original data.table

counts <- dt[, .N, by = .(ID, category)] %>% dcast(ID ~ category)
counts[is.na(counts)] <- 0
output <- merge(dt, counts, by = "ID")


问:
Python/Pandas: Merging Consecutive Rows Only if Matching Columns
I have a large dataset consisting of records of objects travelling within a network. The dataset is stored in a pandas dataset, which roughly looks like this:

```<code>Obj ID | Timestamp | x | y | link ID
-------|-----------|---|---|---------
 123   |  506      |123|456|  ab12
 123   |  517      |129|436|  ab12
 123   |  519      |125|454|  cd34
 126   |  501      |123|426|  gk77
 126   |  505      |153|453|  gk77
 126   |  507      |129|856|  bj88
 126   |  508      |143|496|  bj88
 126   |  512      |125|427|  gk77
 126   |  515      |153|453|  gk77
 126   |  518      |127|256|  ab12
</code>```

The dataframe has been sorted by Obj ID, and each block of records belonging to an object has been sorted by time (the Timestamp field in seconds). Two consecutive rows with the same Obj ID and link ID represent the start and end of an object of that link. The object eventually ends at a link, denoted by a single link ID appearing at the end of the object's record.

Here's the desired output. Condense the start-record and the end-record of one object's visit to one link into one record. For the ending-links of each object, just fill in StartTime for EndTime.

```<code>Obj ID | StartTime | EndTime | link ID
-------|-----------|---------|---------
 123   |  506      |   517   |  ab12
 123   |  519      |   519   |  cd34
 126   |  501      |   505   |  gk77
 126   |  507      |   508   |  bj88
 126   |  512      |   515   |  gk77
 126   |  518      |   518   |  ab12
</code>```

Note:

Cannot guarantee that an object will not travel onto the same link twice. But each visit to the link needs to be a separate record.

A naive loop solution that I implemented ran out of memory, due to the dataset being quite large.

EDIT: I edited the dataset to include the situation mentioned in the first point of my "notes".

答:
Let's try this:

```<code>g =(df['link ID'] != df.shift().fillna(method='bfill')['link ID']).cumsum().rename('group')

df.groupby(['Obj ID','link ID',g])['Timestamp'].agg(['min','max']).reset_index().rename(columns={'min':'StartTime','max':'EndTime'}).drop('group',axis=1)
</code>```

Output:

```<code>    Obj ID link ID    StartTime      EndTime
0   123       ab12    506          517
1   123       cd34    519          519
2   126       ab12    518          518
3   126       bj88    507          508
4   126       gk77    501          505
5   126       gk77    512          515
</code>```

Body:
I have a large dataset consisting of records of objects travelling within a network. The dataset is stored in a pandas dataset, which roughly looks like this:

Obj ID | Timestamp | x | y | link ID
-------|-----------|---|---|---------
 123   |  506      |123|456|  ab12
 123   |  517      |129|436|  ab12
 123   |  519      |125|454|  cd34
 126   |  501      |123|426|  gk77
 126   |  505      |153|453|  gk77
 126   |  507      |129|856|  bj88
 126   |  508      |143|496|  bj88
 126   |  512      |125|427|  gk77
 126   |  515      |153|453|  gk77
 126   |  518      |127|256|  ab12

The dataframe has been sorted by Obj ID, and each block of records belonging to an object has been sorted by time (the Timestamp field in seconds). Two consecutive rows with the same Obj ID and link ID represent the start and end of an object of that link. The object eventually ends at a link, denoted by a single link ID appearing at the end of the object's record.

Here's the desired output. Condense the start-record and the end-record of one object's visit to one link into one record. For the ending-links of each object, just fill in StartTime for EndTime.

Obj ID | StartTime | EndTime | link ID
-------|-----------|---------|---------
 123   |  506      |   517   |  ab12
 123   |  519      |   519   |  cd34
 126   |  501      |   505   |  gk77
 126   |  507      |   508   |  bj88
 126   |  512      |   515   |  gk77
 126   |  518      |   518   |  ab12

Note:

Cannot guarantee that an object will not travel onto the same link twice. But each visit to the link needs to be a separate record.

A naive loop solution that I implemented ran out of memory, due to the dataset being quite large.

EDIT: I edited the dataset to include the situation mentioned in the first point of my "notes".

Body:
Let's try this:

g =(df['link ID'] != df.shift().fillna(method='bfill')['link ID']).cumsum().rename('group')

df.groupby(['Obj ID','link ID',g])['Timestamp'].agg(['min','max']).reset_index().rename(columns={'min':'StartTime','max':'EndTime'}).drop('group',axis=1)

Output:

    Obj ID link ID    StartTime      EndTime
0   123       ab12    506          517
1   123       cd34    519          519
2   126       ab12    518          518
3   126       bj88    507          508
4   126       gk77    501          505
5   126       gk77    512          515


问:
only the first email is being sent in a For Loop of a Window Service
I want to send an email to more than 2 people using my own database.
So I use for loop to send an email. But it is just sent it to a first person.
I also check that the email_data has more than 2, and I bring the email data well.
Here is my code.</p>

```<code>    private void Email()
    {
        DataTable email_data = GetEmailData();
           .....
                String from = "aa@gmail.com";

                for (int i = 0; i <= email_data.Rows.Count; i++)
                {
                    String to = email_data.Rows[i][0].ToString();

                    using (MailMessage mm = new MailMessage(from, to))
                    {

                        SmtpClient smtp = new SmtpClient();
                        mm.Subject = "List";
                        mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "List.xlsx"));
                        mm.IsBodyHtml = true;

                        smtp.Host = "smtp.gmail.com";
                        smtp.EnableSsl = true;
                        System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
                        credentials.UserName = "aa@gmail.com";
                        credentials.Password = "aa";
                        smtp.UseDefaultCredentials = true;
                        smtp.Credentials = credentials;
                        smtp.Port = 587;
   //works well in the first loop, but stops here in the second loop
                        smtp.Send(mm);
                    }
                }
        }
</code>```

答:
check the row count by adding debug prints

And also try putting sleep at the end

```<code>                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = credentials;
                    smtp.Port = 587;
                    smtp.Send(mm);
</code>```

System.Threading.Sleep(1000);

Body:
I want to send an email to more than 2 people using my own database.
So I use for loop to send an email. But it is just sent it to a first person.
I also check that the email_data has more than 2, and I bring the email data well.
Here is my code.

    private void Email()
    {
        DataTable email_data = GetEmailData();
           .....
                String from = "aa@gmail.com";

                for (int i = 0; i <= email_data.Rows.Count; i++)
                {
                    String to = email_data.Rows[i][0].ToString();

                    using (MailMessage mm = new MailMessage(from, to))
                    {

                        SmtpClient smtp = new SmtpClient();
                        mm.Subject = "List";
                        mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "List.xlsx"));
                        mm.IsBodyHtml = true;

                        smtp.Host = "smtp.gmail.com";
                        smtp.EnableSsl = true;
                        System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
                        credentials.UserName = "aa@gmail.com";
                        credentials.Password = "aa";
                        smtp.UseDefaultCredentials = true;
                        smtp.Credentials = credentials;
                        smtp.Port = 587;
   //works well in the first loop, but stops here in the second loop
                        smtp.Send(mm);
                    }
                }
        }

Body:
check the row count by adding debug prints

And also try putting sleep at the end

                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = credentials;
                    smtp.Port = 587;
                    smtp.Send(mm);

System.Threading.Sleep(1000);


问:
In Kotlin How Can I Convert an Int? to an Int
I'm using a HashMap<Int, Int> in Kotlin and when I get out of it the return type is Int?.

How can I convert the Int? to an Int?

So far I've tried using Int?.toInt(), but that seems to be returning an Int?.

I'm writing a Fibonacci function, and my code looks like:

```<code>val fibMemo : Map<Int, Int> = HashMap<Int,Int>()
fun fibN(n:Int) : Int {
    if (n == 0 || n == 1) return 1
    if (fibMemo.containsKey(n))
        // Error here: Type mismatch: inferred type is Int? but Int was expected
        return fibMemo.get(n)?.toInt()
    else {
        val newNum : Int = fibN(n-1) + fibN(n-2)
        fibMemo.put(n, newNum)
        return newNum
    }
}
</code>```

答:
The short answer is you can't unless you emphatically state to the compiler that the nullable int can't and won't be null through the use of two exclamation marks or through the use of an if statement; because int is a subtype of int?

Here is an example.

```<code>val x:Int? = 1
val y: Int =2

x=y // No error
y=x // Error
y=x!! // No error
</code>```

Body:
I'm using a HashMap<Int, Int> in Kotlin and when I get out of it the return type is Int?.

How can I convert the Int? to an Int?

So far I've tried using Int?.toInt(), but that seems to be returning an Int?.

I'm writing a Fibonacci function, and my code looks like:

val fibMemo : Map<Int, Int> = HashMap<Int,Int>()
fun fibN(n:Int) : Int {
    if (n == 0 || n == 1) return 1
    if (fibMemo.containsKey(n))
        // Error here: Type mismatch: inferred type is Int? but Int was expected
        return fibMemo.get(n)?.toInt()
    else {
        val newNum : Int = fibN(n-1) + fibN(n-2)
        fibMemo.put(n, newNum)
        return newNum
    }
}

Body:
The short answer is you can't unless you emphatically state to the compiler that the nullable int can't and won't be null through the use of two exclamation marks or through the use of an if statement; because int is a subtype of int?

Here is an example.

val x:Int? = 1
val y: Int =2

x=y // No error
y=x // Error
y=x!! // No error


问:
indexedDb no events fire on open
I am seeing that sometimes neither of the events are being fired when doing indexedDb.open().
If I set a timeout and observe the state of openRequest, the ready state is set = 'done'. If I do any transaction on the db in the openRequest.result, it works fine.

My guess is that in some cases the openRequest execution is complete before we get to attach onsuccess or other event handlers, in other words it does not get executed in the next event loop.

So, I can inspect the state after an 'x' amount of time if no event is fired. However this approach is hackish and fragile.
Does anyone know of a better way to address this?

```<code> var db;
 var openRequest = window.indexedDB.open("todos", 1);
 openRequest.onerror = function(event) {
    console.error('error in open', event);
 };
 openRequest.onsuccess = (event) => {
     console.log('success ' , event)
 };
 openRequest.onupgradeneeded = (event) => {
     console.log('upgradeneeded ' , event);
     db = event.target.result;
     db.createObjectStore("toDoList", { keyPath: "taskTitle" });
 };
 openRequest.onblocked = (event) => {
     console.log('blocked ' , event);
 };

 setTimeout( () => {
        console.log('timeout');
        console.log(openRequest.readyState) // equals done
 }, 10000)
</code>```

答:
Either a "success" or an "error" event must fire when readyState becomes "done". If that's not happening then you've found a browser bug.

As noted in a comment, you'll want db = event.target.result in the onsuccess handler as well, otherwise db will not be set if an upgrade was not necessary. Are you certain that this isn't the source of your error? (i.e. maybe success was firing, you just weren't capturing the result?)

in some cases the openRequest execution is complete before we get to attach 'onsuccess' or other event handlers

If that happened it would be a browser bug. Are you seeing consistent behavior across browsers? Can you reliable reproduce this?

ContentLicense: CC BY-SA 4.0

Title: indexedDb no events fire on open

Body:
I am seeing that sometimes neither of the events are being fired when doing indexedDb.open().
If I set a timeout and observe the state of openRequest, the ready state is set = 'done'. If I do any transaction on the db in the openRequest.result, it works fine.

My guess is that in some cases the openRequest execution is complete before we get to attach onsuccess or other event handlers, in other words it does not get executed in the next event loop.

So, I can inspect the state after an 'x' amount of time if no event is fired. However this approach is hackish and fragile.
Does anyone know of a better way to address this?

 var db;
 var openRequest = window.indexedDB.open("todos", 1);
 openRequest.onerror = function(event) {
    console.error('error in open', event);
 };
 openRequest.onsuccess = (event) => {
     console.log('success ' , event)
 };
 openRequest.onupgradeneeded = (event) => {
     console.log('upgradeneeded ' , event);
     db = event.target.result;
     db.createObjectStore("toDoList", { keyPath: "taskTitle" });
 };
 openRequest.onblocked = (event) => {
     console.log('blocked ' , event);
 };

 setTimeout( () => {
        console.log('timeout');
        console.log(openRequest.readyState) // equals done
 }, 10000)


问:
CloudFront policy to invalidate only specific distrubution
I'm using S3 bucket to store files and CloudFront to distribute them. I have a tool that handles synchronization automatically and it works great.

However, I want to be able to also create CloudFront invalidations programmatically. What statement do I need to add to the tool's policy in order to allow creating invalidation only for this specific distribution?

Right now, I have this statement:

```<code>{
    "Effect": "Allow",
    "Action": [
        "cloudfront:CreateInvalidation"
    ],
    "Resource": "*"
}
</code>```

But, as you can see, it allows to create invalidations for any distribution in account.

I've tried to use these values for Resource property, but for some reason the tool gave me an error, saying that access is denied:

arn:aws:cloudfront::12345678:distribution/ABCDEFG

arn:aws:cloudfront:::distribution/ABCDEFG

What do I need to specify in Resource property in order to allow creation of invalidation only for the specific distribution?

Its ARN is arn:aws:cloudfront::12345678:distribution/ABCDEFG for example.

答:
Update: As of 2021, the cloudfront:CreateInvalidation action supports resource-level permissions and can be used to allow invalidating only a specific distribution. See @GraphicalDot's answer below. Original answer — as of 2017 — below.

The cloudfront:CreateInvalidation command does not support resource-level permissions. For this reason, only * is supported. Thus, it is not possible to restrict a user/role to only be able to invalidate a specific distribution.

Source: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cf-api-permissions-ref.html

Body:
I'm using S3 bucket to store files and CloudFront to distribute them. I have a tool that handles synchronization automatically and it works great.

However, I want to be able to also create CloudFront invalidations programmatically. What statement do I need to add to the tool's policy in order to allow creating invalidation only for this specific distribution?

Right now, I have this statement:

{
    "Effect": "Allow",
    "Action": [
        "cloudfront:CreateInvalidation"
    ],
    "Resource": "*"
}

But, as you can see, it allows to create invalidations for any distribution in account.

I've tried to use these values for Resource property, but for some reason the tool gave me an error, saying that access is denied:

arn:aws:cloudfront::12345678:distribution/ABCDEFG

arn:aws:cloudfront:::distribution/ABCDEFG

What do I need to specify in Resource property in order to allow creation of invalidation only for the specific distribution?

Its ARN is arn:aws:cloudfront::12345678:distribution/ABCDEFG for example.


问:
Copy and rename previous version to last modified
For batch copy purposes I need to create script that I was thinking will be simple, but no luck.

Use case is: Copy all files from sourcedirectory to targetdirectory where sourcedirectory file is newer of not exists in targetdirectory, but if file already exists in targetdirectory rename it to original_name.B<timestamp_last_modified> before copy/overwrite

What I started with:

```<code>xcopy %sourcedirectory% %targetdirectory% /f /i /s /h /d /y >> W:\Xcopy%datetimefile%.log 2>&1
</code>```

But it can not do the rename part so I started playing around and got here:

```<code>@echo off
rem configuration
set sourcedirectory="d:\Ice"
set targetdirectory="W:\Ice"
set logdirectory="W:"

rem following part only creates timestamp for log file (datetimefile) and log record (datetimecopy)
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetimefile=%%I
set datetimecopy=%datetimefile:~0,8% %datetimefile:~8,2%:%datetimefile:~10,2%:%datetimefile:~12,2%
set datetimefile=%datetimefile:~0,8%_%datetimefile:~8,6%
set "logfile=%logdirectory:~0,-1%\Backup%datetimefile%.log^""

rem logging
echo Log File is %logfile%
echo -----     BACKUP FROM: %sourcedirectory% TO: %targetdirectory% AT: %datetimecopy%     -----
echo -----     BACKUP FROM: %sourcedirectory% TO: %targetdirectory% AT: %datetimecopy%     ----- >> %logfile% 2>&1

rem execution
for /F "tokens=*" %%A in ('xcopy %sourcedirectory% %targetdirectory% /f /i /s /h /d /y /l') do (call :subroutine "%%A")

rem log timestam creation and logging
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetimecopy=%%I
set datetimecopy=%datetimecopy:~0,8% %datetimecopy:~8,2%:%datetimecopy:~10,2%:%datetimecopy:~12,2%
echo -----     BACKUP FINISHED AT: %datetimecopy%     -----
echo -----     BACKUP FINISHED AT: %datetimecopy%     ----- >> %logfile% 2>&1

goto :finish

:subroutine
 set "f=%1"
 set "f=%f:~1,-1%"
 set "filefrom=%f: -> =" & set "fileto=%"
 set "filefrom=^"%filefrom%^""
 set "fileto=^"%fileto%^""
 if NOT EXIST %fileto% GOTO :cpyonly
 set "g=%fileto%"
 call set "newg=%%g:\=\\%%"
 for /f "tokens=2 delims==" %%N in ('wmic datafile where name^=%%newg%% get LastModified /format:list') do set lastmod=%%N
 set "i=%fileto%"
 set "target="%%~ni%%~xi.B%lastmod:~0,14%^""
 echo rename %g% %target%
 echo "rename %g% %target%" >> %logfile% 2>&1
 rename %g% %target% >> %logfile% 2>&1
 goto :cpyonly

:cpyonly
 echo "xcopy %filefrom% %fileto% /f /h /d /y"  >> %logfile% 2>&1
 echo xcopy %filefrom% %fileto% /f /h /d /y
 xcopy %filefrom% %fileto% /f /h /d /y >> %logfile% 2>&1
 GOTO :finish

rem :testing
rem wmic datafile where name="d:\\CopyFrom\\drziaky.txt" get LastModified /format:list
rem d:\Ice\Private\StartBatch\Backup_new.bat

:finish
</code>```

However it did not work and can not move forward, the observed issues:

The filenames contain spaces and it creates splits in the files even when I have used the "tokens=*" I have not found a way how to pass the whole %%A to subroutine

By the file operations I sometimes need to remove or add the "" around, this works on some positions and on some not, again I failed to discover when/why (for example this set "f=%f:~1,-1%" is intended to remove " and this set "fileto=^"%fileto%^"" is intended to add them

To the previous versions (not in this post, but have them on my HDD):

I tried using copy, but copy did not create target directory

The wmic commands are used because of local differences and seems to work (for getting time and also last modification date)

xcopy as list generator works (small issue with last line listing number of files)

Parsing tried first via for /f and then via the set "filefrom=%f: -> =" & set "fileto=%" (copied from here) but none works

Below is last working code (with copy) but:

can not create target directories

Breaks on spaces in file name

Breaks on last line of xcopy (X files copied)

Maybe it breaks on some other cases also, but it is the best I managed to get until now, however get stuck and can not move forward from this point, could somebody help me? Thank you and apologize for long post. If it is already here then I'm really blind because have spend lot of hours searching.

PS: enabledelayedexpansion can not be used :-( Also usage of 3rd parties can not be relyed to so the script can be only 1 file

```<code>set sourcedirectory="d:\Ice"
set targetdirectory="W:\Ice"
set logdirectory="W:"
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetimefile=%%I
set datetimecopy=%datetimefile:~0,8% %datetimefile:~8,2%:%datetimefile:~10,2%:%datetimefile:~12,2%
set datetimefile=%datetimefile:~0,8%_%datetimefile:~8,6%
set "logfile=%logdirectory:~0,-1%\Backup%datetimefile%.log^""
echo -----     BACKUP FROM: %sourcedirectory% TO: %targetdirectory% AT: %datetimecopy%     ----- >> %logfile% 2>&1

for /f "tokens=1,3" %%A in ('xcopy %sourcedirectory% %targetdirectory% /f /i /s /h /d /y /l') do (call :subroutine "%%A" "%%B")

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetimecopy=%%I
set datetimecopy=%datetimecopy:~0,8% %datetimecopy:~8,2%:%datetimecopy:~10,2%:%datetimecopy:~12,2%
echo -----     BACKUP FINISHED AT: %datetimecopy%     ----- >> %logfile% 2>&1

goto :eof

:subroutine
 set "f=%1"
 if NOT EXIST %2 GOTO :cpyonly
 set "g=%2"
 call set "newg=%%g:\=\\%%"
 for /f "tokens=2 delims==" %%N in ('wmic datafile where name^=%%newg%% get LastModified /format:list') do set lastmod=%%N
 set "target="%~n2%~x2.B%lastmod:~0,14%^""
 echo "rename %g% %target%" >> %logfile% 2>&1
 rename %g% %target% >> %logfile% 2>&1
 goto :cpyonly

:cpyonly
 echo "copy %1 %2" >> %logfile% 2>&1
 copy %1 %2 >> %logfile% 2>&1
 GOTO :eof

:eof
</code>```

答:
So finally after several hours I have found solution and now it works as I have expected, also added ziping of older files.
If someone want to use feel free. How it works is that it checks all files and the files that did not exist on target are copied to target, if file exists on target it is renamed to date of last modification and ziped (here you need to setup own zipper and parameters), then new file is copied over, at the end xcopy is once more executed as safety measure in case my script will fail for certain files.</p>

```<code>@echo off

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetimefile=%%I
set datetimecopy=%datetimefile:~0,8% %datetimefile:~8,2%:%datetimefile:~10,2%:%datetimefile:~12,2%
set datetimefile=%datetimefile:~0,8%_%datetimefile:~8,6%
set "logfile=%logdirectory:~0,-1%\Bcopy%datetimefile%.log^""
set "logxcpy=%logdirectory:~0,-1%\Xcopy%datetimefile%.log^""

set sourcedirectory="d:\myDir"
set targetdirectory="w:\myDir"
set logdirectory="W:"
set whereiszip="C:\Program Files\7-Zip\7z.exe"

echo -----   BACKUP FROM: %sourcedirectory% TO: %targetdirectory% AT: %datetimecopy% LOG: %logfile% ZIP: %whereiszip% START   -----
echo -----   BACKUP FROM: %sourcedirectory% TO: %targetdirectory% AT: %datetimecopy% LOG: %logfile% ZIP: %whereiszip% START   ----- >> %logfile% 2>&1

for /f "tokens=*" %%A in ('xcopy %sourcedirectory% %targetdirectory% /f /i /s /h /d /y /l') do (call :subroutine "%%A")
xcopy %sourcedirectory% %targetdirectory% /f /i /s /h /d /y >> %logxcpy% 2>&1

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetimefile=%%I
set datetimecopy=%datetimefile:~0,8% %datetimefile:~8,2%:%datetimefile:~10,2%:%datetimefile:~12,2%
echo -----   BACKUP FROM: %sourcedirectory% TO: %targetdirectory% AT: %datetimecopy% LOG: %logfile% ZIP: %whereiszip% FINISH   -----
echo -----   BACKUP FROM: %sourcedirectory% TO: %targetdirectory% AT: %datetimecopy% LOG: %logfile% ZIP: %whereiszip% FINISH   ----- >> %logfile% 2>&1

if "%1"=="" goto :finish

if "%1"=="S" shutdown /s
if "%1"=="M" goto :outlook
if "%1"=="O" goto :outlook

:subroutine
if "%~1"=="" goto :cannotparse
set str1=%1
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetimefile=%%I
set datetimecopy=%datetimefile:~0,8% %datetimefile:~8,2%:%datetimefile:~10,2%:%datetimefile:~12,2%
if not defined str1 goto :cannotparse
if x%str1: -> =%==x%str1% goto :cannotparse
echo string %str1% contains -^>
set str=%1
@setlocal enableextensions enabledelayedexpansion
set "find= -> "
call set last=%%str:*!find!=%%
call set first=%%str:!last!=%%
call set first=%%first:!find!=%%
call set first=!first!^"
call set last=^"!last!
set nqlast=!last:~1,-1!
@setlocal enableextensions disabledelayedexpansion
for %%A in ("%nqlast%") do (
    call set folder=%%~dpA
    call set file=%%~nxA
)
echo %datetimecopy% INPUT: [%str%] source file: [%first%] destination file: [%last%] path: [%folder%] name: [%file%]
echo %datetimecopy% INPUT: [%str%] source file: [%first%] destination file: [%last%] path: [%folder%] name: [%file%] >> %logfile% 2>&1
if NOT EXIST %last% GOTO :cpyonly
set "g=%last%"
call set "newg=%%g:\=\\%%"
for /f "tokens=2 delims==" %%N in ('wmic datafile where name^=%%newg%% get LastModified /format:list') do set lastmod=%%N
set "target="%file%.B%lastmod:~0,14%^""
echo %datetimecopy% RENAME rename %last% %target%
echo %datetimecopy% RENAME rename %last% %target% >> %logfile% 2>&1
rename %last% %target% >> %logfile% 2>&1
set "target="%folder%%file%.B%lastmod:~0,14%^""
set "ztarget="%folder%%file%.B%lastmod:~0,14%.zip^""
if EXIST %whereiszip% (
    echo %datetimecopy% 7ZIP: %whereiszip% a -tzip -mx9 %ztarget% %target%
    echo %datetimecopy% 7ZIP: %whereiszip% a -tzip -mx9 %ztarget% %target% >> %logfile% 2>&1
    %whereiszip% a -tzip -mx9 %ztarget% %target% >> %logfile% 2>&1
    if %ERRORLEVEL% EQU 0 (
        echo %datetimecopy% DELETE: del %target%
        echo %datetimecopy% DELETE: del %target% >> %logfile% 2>&1
        del %target% >> %logfile% 2>&1
    )
)
goto :cpyonly
endlocal
goto :finish

:cpyonly
set "quotedfolder="%folder%^""
echo %datetimecopy% XCOPY: xcopy %first% %quotedfolder% /f /i /s /h /d /y
echo %datetimecopy% XCOPY: xcopy %first% %quotedfolder% /f /i /s /h /d /y >> %logfile% 2>&1
xcopy %first% %quotedfolder% /f /i /s /h /d /y >> %logfile% 2>&1
goto :finish

:cannotparse
echo %datetimecopy% ERROR: string %str1% did NOT contains -^>
echo %datetimecopy% ERROR: string %str1% did NOT contains -^> >> %logfile% 2>&1
goto :finish

:outlook
c:
cd "\Program Files\Microsoft Office\Office12\"
start OUTLOOK.EXE /recycle
goto :finish

:finish
endlocal
endlocal
</code>```

Body:
For batch copy purposes I need to create script that I was thinking will be simple, but no luck.

Use case is: Copy all files from sourcedirectory to targetdirectory where sourcedirectory file is newer of not exists in targetdirectory, but if file already exists in targetdirectory rename it to original_name.B<timestamp_last_modified> before copy/overwrite

What I started with:

xcopy %sourcedirectory% %targetdirectory% /f /i /s /h /d /y >> W:\Xcopy%datetimefile%.log 2>&1

But it can not do the rename part so I started playing around and got here:

@echo off
rem configuration
set sourcedirectory="d:\Ice"
set targetdirectory="W:\Ice"
set logdirectory="W:"

rem following part only creates timestamp for log file (datetimefile) and log record (datetimecopy)
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetimefile=%%I
set datetimecopy=%datetimefile:~0,8% %datetimefile:~8,2%:%datetimefile:~10,2%:%datetimefile:~12,2%
set datetimefile=%datetimefile:~0,8%_%datetimefile:~8,6%
set "logfile=%logdirectory:~0,-1%\Backup%datetimefile%.log^""

rem logging
echo Log File is %logfile%
echo -----     BACKUP FROM: %sourcedirectory% TO: %targetdirectory% AT: %datetimecopy%     -----
echo -----     BACKUP FROM: %sourcedirectory% TO: %targetdirectory% AT: %datetimecopy%     ----- >> %logfile% 2>&1

rem execution
for /F "tokens=*" %%A in ('xcopy %sourcedirectory% %targetdirectory% /f /i /s /h /d /y /l') do (call :subroutine "%%A")

rem log timestam creation and logging
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetimecopy=%%I
set datetimecopy=%datetimecopy:~0,8% %datetimecopy:~8,2%:%datetimecopy:~10,2%:%datetimecopy:~12,2%
echo -----     BACKUP FINISHED AT: %datetimecopy%     -----
echo -----     BACKUP FINISHED AT: %datetimecopy%     ----- >> %logfile% 2>&1

goto :finish

:subroutine
 set "f=%1"
 set "f=%f:~1,-1%"
 set "filefrom=%f: -> =" & set "fileto=%"
 set "filefrom=^"%filefrom%^""
 set "fileto=^"%fileto%^""
 if NOT EXIST %fileto% GOTO :cpyonly
 set "g=%fileto%"
 call set "newg=%%g:\=\\%%"
 for /f "tokens=2 delims==" %%N in ('wmic datafile where name^=%%newg%% get LastModified /format:list') do set lastmod=%%N
 set "i=%fileto%"
 set "target="%%~ni%%~xi.B%lastmod:~0,14%^""
 echo rename %g% %target%
 echo "rename %g% %target%" >> %logfile% 2>&1
 rename %g% %target% >> %logfile% 2>&1
 goto :cpyonly

:cpyonly
 echo "xcopy %filefrom% %fileto% /f /h /d /y"  >> %logfile% 2>&1
 echo xcopy %filefrom% %fileto% /f /h /d /y
 xcopy %filefrom% %fileto% /f /h /d /y >> %logfile% 2>&1
 GOTO :finish

rem :testing
rem wmic datafile where name="d:\\CopyFrom\\drziaky.txt" get LastModified /format:list
rem d:\Ice\Private\StartBatch\Backup_new.bat

:finish

However it did not work and can not move forward, the observed issues:

The filenames contain spaces and it creates splits in the files even when I have used the "tokens=*" I have not found a way how to pass the whole %%A to subroutine

By the file operations I sometimes need to remove or add the "" around, this works on some positions and on some not, again I failed to discover when/why (for example this set "f=%f:~1,-1%" is intended to remove " and this set "fileto=^"%fileto%^"" is intended to add them

To the previous versions (not in this post, but have them on my HDD):

I tried using copy, but copy did not create target directory

The wmic commands are used because of local differences and seems to work (for getting time and also last modification date)

xcopy as list generator works (small issue with last line listing number of files)

Parsing tried first via for /f and then via the set "filefrom=%f: -> =" & set "fileto=%" (copied from here) but none works

Below is last working code (with copy) but:

can not create target directories

Breaks on spaces in file name

Breaks on last line of xcopy (X files copied)

Maybe it breaks on some other cases also, but it is the best I managed to get until now, however get stuck and can not move forward from this point, could somebody help me? Thank you and apologize for long post. If it is already here then I'm really blind because have spend lot of hours searching.

PS: enabledelayedexpansion can not be used :-( Also usage of 3rd parties can not be relyed to so the script can be only 1 file

set sourcedirectory="d:\Ice"
set targetdirectory="W:\Ice"
set logdirectory="W:"
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetimefile=%%I
set datetimecopy=%datetimefile:~0,8% %datetimefile:~8,2%:%datetimefile:~10,2%:%datetimefile:~12,2%
set datetimefile=%datetimefile:~0,8%_%datetimefile:~8,6%
set "logfile=%logdirectory:~0,-1%\Backup%datetimefile%.log^""
echo -----     BACKUP FROM: %sourcedirectory% TO: %targetdirectory% AT: %datetimecopy%     ----- >> %logfile% 2>&1

for /f "tokens=1,3" %%A in ('xcopy %sourcedirectory% %targetdirectory% /f /i /s /h /d /y /l') do (call :subroutine "%%A" "%%B")

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetimecopy=%%I
set datetimecopy=%datetimecopy:~0,8% %datetimecopy:~8,2%:%datetimecopy:~10,2%:%datetimecopy:~12,2%
echo -----     BACKUP FINISHED AT: %datetimecopy%     ----- >> %logfile% 2>&1

goto :eof

:subroutine
 set "f=%1"
 if NOT EXIST %2 GOTO :cpyonly
 set "g=%2"
 call set "newg=%%g:\=\\%%"
 for /f "tokens=2 delims==" %%N in ('wmic datafile where name^=%%newg%% get LastModified /format:list') do set lastmod=%%N
 set "target="%~n2%~x2.B%lastmod:~0,14%^""
 echo "rename %g% %target%" >> %logfile% 2>&1
 rename %g% %target% >> %logfile% 2>&1
 goto :cpyonly

:cpyonly
 echo "copy %1 %2" >> %logfile% 2>&1
 copy %1 %2 >> %logfile% 2>&1
 GOTO :eof

:eof

Body:
So finally after several hours I have found solution and now it works as I have expected, also added ziping of older files.
If someone want to use feel free. How it works is that it checks all files and the files that did not exist on target are copied to target, if file exists on target it is renamed to date of last modification and ziped (here you need to setup own zipper and parameters), then new file is copied over, at the end xcopy is once more executed as safety measure in case my script will fail for certain files.

@echo off

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetimefile=%%I
set datetimecopy=%datetimefile:~0,8% %datetimefile:~8,2%:%datetimefile:~10,2%:%datetimefile:~12,2%
set datetimefile=%datetimefile:~0,8%_%datetimefile:~8,6%
set "logfile=%logdirectory:~0,-1%\Bcopy%datetimefile%.log^""
set "logxcpy=%logdirectory:~0,-1%\Xcopy%datetimefile%.log^""

set sourcedirectory="d:\myDir"
set targetdirectory="w:\myDir"
set logdirectory="W:"
set whereiszip="C:\Program Files\7-Zip\7z.exe"

echo -----   BACKUP FROM: %sourcedirectory% TO: %targetdirectory% AT: %datetimecopy% LOG: %logfile% ZIP: %whereiszip% START   -----
echo -----   BACKUP FROM: %sourcedirectory% TO: %targetdirectory% AT: %datetimecopy% LOG: %logfile% ZIP: %whereiszip% START   ----- >> %logfile% 2>&1

for /f "tokens=*" %%A in ('xcopy %sourcedirectory% %targetdirectory% /f /i /s /h /d /y /l') do (call :subroutine "%%A")
xcopy %sourcedirectory% %targetdirectory% /f /i /s /h /d /y >> %logxcpy% 2>&1

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetimefile=%%I
set datetimecopy=%datetimefile:~0,8% %datetimefile:~8,2%:%datetimefile:~10,2%:%datetimefile:~12,2%
echo -----   BACKUP FROM: %sourcedirectory% TO: %targetdirectory% AT: %datetimecopy% LOG: %logfile% ZIP: %whereiszip% FINISH   -----
echo -----   BACKUP FROM: %sourcedirectory% TO: %targetdirectory% AT: %datetimecopy% LOG: %logfile% ZIP: %whereiszip% FINISH   ----- >> %logfile% 2>&1

if "%1"=="" goto :finish

if "%1"=="S" shutdown /s
if "%1"=="M" goto :outlook
if "%1"=="O" goto :outlook

:subroutine
if "%~1"=="" goto :cannotparse
set str1=%1
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetimefile=%%I
set datetimecopy=%datetimefile:~0,8% %datetimefile:~8,2%:%datetimefile:~10,2%:%datetimefile:~12,2%
if not defined str1 goto :cannotparse
if x%str1: -> =%==x%str1% goto :cannotparse
echo string %str1% contains -^>
set str=%1
@setlocal enableextensions enabledelayedexpansion
set "find= -> "
call set last=%%str:*!find!=%%
call set first=%%str:!last!=%%
call set first=%%first:!find!=%%
call set first=!first!^"
call set last=^"!last!
set nqlast=!last:~1,-1!
@setlocal enableextensions disabledelayedexpansion
for %%A in ("%nqlast%") do (
    call set folder=%%~dpA
    call set file=%%~nxA
)
echo %datetimecopy% INPUT: [%str%] source file: [%first%] destination file: [%last%] path: [%folder%] name: [%file%]
echo %datetimecopy% INPUT: [%str%] source file: [%first%] destination file: [%last%] path: [%folder%] name: [%file%] >> %logfile% 2>&1
if NOT EXIST %last% GOTO :cpyonly
set "g=%last%"
call set "newg=%%g:\=\\%%"
for /f "tokens=2 delims==" %%N in ('wmic datafile where name^=%%newg%% get LastModified /format:list') do set lastmod=%%N
set "target="%file%.B%lastmod:~0,14%^""
echo %datetimecopy% RENAME rename %last% %target%
echo %datetimecopy% RENAME rename %last% %target% >> %logfile% 2>&1
rename %last% %target% >> %logfile% 2>&1
set "target="%folder%%file%.B%lastmod:~0,14%^""
set "ztarget="%folder%%file%.B%lastmod:~0,14%.zip^""
if EXIST %whereiszip% (
    echo %datetimecopy% 7ZIP: %whereiszip% a -tzip -mx9 %ztarget% %target%
    echo %datetimecopy% 7ZIP: %whereiszip% a -tzip -mx9 %ztarget% %target% >> %logfile% 2>&1
    %whereiszip% a -tzip -mx9 %ztarget% %target% >> %logfile% 2>&1
    if %ERRORLEVEL% EQU 0 (
        echo %datetimecopy% DELETE: del %target%
        echo %datetimecopy% DELETE: del %target% >> %logfile% 2>&1
        del %target% >> %logfile% 2>&1
    )
)
goto :cpyonly
endlocal
goto :finish

:cpyonly
set "quotedfolder="%folder%^""
echo %datetimecopy% XCOPY: xcopy %first% %quotedfolder% /f /i /s /h /d /y
echo %datetimecopy% XCOPY: xcopy %first% %quotedfolder% /f /i /s /h /d /y >> %logfile% 2>&1
xcopy %first% %quotedfolder% /f /i /s /h /d /y >> %logfile% 2>&1
goto :finish

:cannotparse
echo %datetimecopy% ERROR: string %str1% did NOT contains -^>
echo %datetimecopy% ERROR: string %str1% did NOT contains -^> >> %logfile% 2>&1
goto :finish

:outlook
c:
cd "\Program Files\Microsoft Office\Office12\"
start OUTLOOK.EXE /recycle
goto :finish

:finish
endlocal
endlocal


问:
C99: The existence of a strrpbrk (reverse strpbrk)
I am almost sure there is no reverse strpbrk() in C99. But:

Is there a reason for that? I mean, why does strchr() have strrchr() but strpbrk() doesn't hae strrpbrk()?

How do you get the last occurrence in a string of any of the characters in another string?

答:
In my opinion, because no one thinks out of the box, stpcpy isn't part of C99 either :(

Look at glibc's stpbrk implementation to get an inspiration, it's not that hard

```<code>/* Find the first occurrence in S of any character in ACCEPT.  */
char *
strpbrk (s, accept)
     const char *s;
     const char *accept;
{
  while (*s != '\0')
    {
      const char *a = accept;
      while (*a != '\0')
        if (*a++ == *s)
          return (char *) s;
      ++s;
    }
  return NULL;
}
</code>```

Body:
In my opinion, because no one thinks out of the box, stpcpy isn't part of C99 either :(

Look at glibc's stpbrk implementation to get an inspiration, it's not that hard

/* Find the first occurrence in S of any character in ACCEPT.  */
char *
strpbrk (s, accept)
     const char *s;
     const char *accept;
{
  while (*s != '\0')
    {
      const char *a = accept;
      while (*a != '\0')
        if (*a++ == *s)
          return (char *) s;
      ++s;
    }
  return NULL;
}


问:
How to SELECT column value FROM table?
Here's my code:

```<code><?php
//recently added
$result = mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
if ($result == 1){
?>
    <script>
        jQuery(document).ready(function(){
            jQuery(".eltdf-psc-slide").addClass("no-background");
        });
    </script>
<?php
}
//=============
?>
</code>```

Basically what I'm trying to do is checking and see if the value stored in the $shadowless_background_table "DB" is == 1 and I only want that column (background). I have browse the web, but what I see are examples with while loops which I was wondering if I could do something like this instead.

答:
If you want to fetch a single record based on a condition you can do this - </p>

<pre class="lang-php prettyprint-override"><code>$result = mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
if (mysql_num_rows($result)>0){
    $fetchedColum = mysql_result($result, 0, 'COLUMN_NAME');
}
</code>```

Title: How to SELECT column value FROM table?

Body:
Here's my code:

<?php
//recently added
$result = mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
if ($result == 1){
?>

<?php
}
//=============
?>

Basically what I'm trying to do is checking and see if the value stored in the $shadowless_background_table "DB" is == 1 and I only want that column (background). I have browse the web, but what I see are examples with while loops which I was wondering if I could do something like this instead.

Body:
If you want to fetch a single record based on a condition you can do this -

$result = mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
if (mysql_num_rows($result)>0){
    $fetchedColum = mysql_result($result, 0, 'COLUMN_NAME');
}


问:
How to remove all duplicates from an array of objects?
I have an object that contains an array of objects.

```<code>obj = {};

obj.arr = new Array();

obj.arr.push({place:"here",name:"stuff"});
obj.arr.push({place:"there",name:"morestuff"});
obj.arr.push({place:"there",name:"morestuff"});
</code>```

I'm wondering what is the best method to remove duplicate objects from an array.  So for example, obj.arr would become...

```<code>{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}
</code>```

答:
Generic for any array of objects:

```<code>/**
* Remove duplicated values without losing information
*/
const removeValues = (items, key) => {
  let tmp = {};

  items.forEach(item => {
    tmp[item[key]] = (!tmp[item[key]]) ? item : Object.assign(tmp[item[key]], item);
  });
  items = [];
  Object.keys(tmp).forEach(key => items.push(tmp[key]));

  return items;
}
</code>```

Hope it could help to anyone.

Body:
I have an object that contains an array of objects.

obj = {};

obj.arr = new Array();

obj.arr.push({place:"here",name:"stuff"});
obj.arr.push({place:"there",name:"morestuff"});
obj.arr.push({place:"there",name:"morestuff"});

I'm wondering what is the best method to remove duplicate objects from an array.  So for example, obj.arr would become...

{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}

Body:
Generic for any array of objects:

/**
* Remove duplicated values without losing information
*/
const removeValues = (items, key) => {
  let tmp = {};

  items.forEach(item => {
    tmp[item[key]] = (!tmp[item[key]]) ? item : Object.assign(tmp[item[key]], item);
  });
  items = [];
  Object.keys(tmp).forEach(key => items.push(tmp[key]));

  return items;
}

Hope it could help to anyone.


答:
```<code>df.drop_duplicates(subset = ['Obj ID','link ID'],
    keep='first').merge(x.drop_duplicates(subset = ['Obj ID','link ID'],
    keep='last'), on= ['Obj ID','link ID'])
</code>```

Title: Python/Pandas: Merging Consecutive Rows Only if Matching Columns


问:
Setting model attributes for every action within each controller
I would like to set three common attributes on my model for each @RequestMapping within the many controllers in a Spring Boot application. I have read about @ModelAttribute but it needs to be placed within each Controller. I have more than 20 controllers in my application and each having more than 10 @RequestMapping.

Is there a way to set such model attributes in one place which gets initialized at the start of the application?

答:
If you want to execute some code on Spring Boot startup, consider this:

Spring boot startup listener

But I guess that you really want Controller related behavior, I would recommend using a Global Interceptor.

With global interceptor, you can interfere with the request-response lifecycle in Spring.

It lets you add functionality to request-response life cycle in 3 different points:

before a controller handles a request

after a handler finished performing its functionality

when the view is about to render to the end user.

Just create a class which extends from HandlerInterceptorAdapter and override one of three methods, with your desired functionality.

For Example:

```<code>public class MyInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        request.setAttribute("myFirstAttribute", "MyFirstValueHere");
        return super.preHandle(request, response, handler);
    }

}
</code>```

Here's an example on how to do it with Spring Boot:

```<code>@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

  @Autowired
  MyInterceptor myInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(...)
    ...
    registry.addInterceptor(myInterceptor);
  }
}
</code>```

Body:
If you want to execute some code on Spring Boot startup, consider this:

Spring boot startup listener

But I guess that you really want Controller related behavior, I would recommend using a Global Interceptor.

With global interceptor, you can interfere with the request-response lifecycle in Spring.

It lets you add functionality to request-response life cycle in 3 different points:

before a controller handles a request

after a handler finished performing its functionality

when the view is about to render to the end user.

Just create a class which extends from HandlerInterceptorAdapter and override one of three methods, with your desired functionality.

For Example:

public class MyInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        request.setAttribute("myFirstAttribute", "MyFirstValueHere");
        return super.preHandle(request, response, handler);
    }

}

Here's an example on how to do it with Spring Boot:

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

  @Autowired
  MyInterceptor myInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(...)
    ...
    registry.addInterceptor(myInterceptor);
  }
}


问:
Java: Long result = -1: cannot convert from int to long
I'm using eclipse java ee to perform java programming.

I had the following line of code in one of my functions:

```<code>Long result = -1;
</code>```

I got the following error:

Type mismatch: cannot convert from int to Long

I can't quite understand why when i add a number to the variable it provides this error.

How can this issue be resolved and why did it happen in the first place?

答:
First of all, check you Java version: run "java -version" from command line.

In Java version prior to 1.5, the correct syntax is:

Long result = new Long(1L);

In java >1.5 it's done automatically. It's called "autoboxing".

The uppercase "L" tells Java that the number should be interpreted as long.

Body:
I'm using eclipse java ee to perform java programming.

I had the following line of code in one of my functions:

Long result = -1;

I got the following error:

Type mismatch: cannot convert from int to Long

I can't quite understand why when i add a number to the variable it provides this error.

How can this issue be resolved and why did it happen in the first place?


问:
p:autocomplete completemethod isn't fired with copy-pate with mouse events
I am using primefaces autocomplete component.
My problem is when I copy and paste in that component (with mouse) not with ctrl + V , nothing happens , complete method is not fired and no list returns.

Is there a way to make mouse copy-paste behave like keyboard events with p:autocomplete?

This is a piece of code I am working on

```<code><p:autoComplete size="20" minQueryLength="3" id="quickSearch" styleClass="quickSearch"
        value="#{bean.value}" completeMethod="#{bean.searchList}" var="object"
        itemValue="#{object}" itemLabel="#{object.objectCode}" converter="complexConverter"
        style="margin-left: -50;" forceSelection="true" widgetVar="quickSearchVar"
        emptyMessage="No Results Found..">
    <p:ajax event="itemSelect" listener="#{bean.goToObject()}"></p:ajax>
    <p:column>
        ...
        ...
    </p:column>
</p:autoComplete>
</code>```

And this is where I am trying to capture the copy-paste events

```<code>$('.quickSearch').on('paste', function() {
    // alert('hello');
    // here I need to trigger what I am asking for
});
</code>```

And I am wondering if somebody can explain to me what event fires the complete method and returns the suggestions.

Thanks in advance.

答:
PrimeFaces's autoComplete widget has a method called showSuggestions to call it from a javascript function you can use the widgetVar value of your component

```<code>PF('quickSearchVar').showSuggestions(PF('quickSearchVar').input.val())
</code>```

Body:
I am using primefaces autocomplete component.
My problem is when I copy and paste in that component (with mouse) not with ctrl + V , nothing happens , complete method is not fired and no list returns.

Is there a way to make mouse copy-paste behave like keyboard events with p:autocomplete?

This is a piece of code I am working on

        ...
        ...

And this is where I am trying to capture the copy-paste events

$('.quickSearch').on('paste', function() {
    // alert('hello');
    // here I need to trigger what I am asking for
});

And I am wondering if somebody can explain to me what event fires the complete method and returns the suggestions.

Thanks in advance.

Body:
PrimeFaces's autoComplete widget has a method called showSuggestions to call it from a javascript function you can use the widgetVar value of your component

PF('quickSearchVar').showSuggestions(PF('quickSearchVar').input.val())