问:
Unable to select options from the drop down using protractor
I am going to write automation scripts for angular 4 application which uses primeng drop down .

The code is below for the drop down control.

```<code><p-dropdown formcontrolname="CertificationsType" class="ng-tns-c4-13 ng-touched ng-dirty ng-valid" ng-reflect-auto-width="false" ng-reflect-options="[object Object],[object Object" ng-reflect-name="CertificationsType">
     <div class="ng-tns-c4-13 ui-dropdown ui-widget ui-state-default ui-corner-all ui-helper-clearfix ui-dropdown-open" ng-reflect-ng-class="[object Object]">
        <div class="ui-helper-hidden-accessible">
            <input class="ng-tns-c4-13" readonly="" role="listbox" type="text" aria-label="Other Programming">
        </div>
       <label class="ng-tns-c4-13 ui-dropdown-label ui-inputtext ui-corner-all" ng-reflect-ng-class="[object Object]">Other Programming</label>
        <div class="ui-dropdown-trigger ui-state-default ui-corner-right">
            <span class="ui-clickable fa fa-fw fa-caret-down" ng-reflect-klass="ui-clickable" ng-reflect-ng-class="fa fa-fw fa-caret-down"></span>
        </div>
        <div class="ng-tns-c4-13 ui-dropdown-panel ui-widget-content ui-corner-all ui-shadow ng-trigger ng-trigger-panelState" ng-reflect-ng-class="ui-dropdown-panel ui-widget-co" style="display: block; z-index: 1008; top: 32px; left: 0px; opacity: 1;">
            <div class="ui-dropdown-items-wrapper" style="max-height: 200px;">
               <ul class="ui-dropdown-items ui-dropdown-list ui-widget-content ui-widget ui-corner-all ui-helper-reset ng-tns-c4-13">
                   <li class="ng-tns-c4-13 ui-dropdown-item ui-corner-all" ng-reflect-ng-class="[object Object]">
                       <span class="ng-tns-c4-13">Select Type</span>
                   </li>
           <li class="ng-tns-c4-13 ui-dropdown-item ui-corner-all ui-state-highlight" ng-reflect-ng-class="[object Object]">
                        <span class="ng-tns-c4-13">Other Programming</span>
                        </li><li class="ng-tns-c4-13 ui-dropdown-item ui-corner-all" ng-reflect-ng-class="[object Object]">
                            <span class="ng-tns-c4-13">Source Programming</span>
                        </li><li class="ng-tns-c4-13 ui-dropdown-item ui-corner-all" ng-reflect-ng-class="[object Object]">
                            <span class="ng-tns-c4-13">Techinical programming</span>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </p-dropdown>
</code>```

My Page Object file code is below.

```<code>//To return "Type" drop down field options
getTypeFieldData(){

let type_dropdown = element(by.css('p-dropdown[formcontrolname="CertificationsType"]'));
let ul_element = type_dropdown.element(by.tagName('ul'));
let li_elements= ul_element.all(by.tagName('li'));
    return li_elements;
}
</code>```

My Spec file code is below.

```<code>//Testcase 19 : To click on every option in the
    //"Type" drop down
    it('To click on every option in the Type drop down',()=>{
        //To click on every element of the "Type" drop down field content
        let list=page.getTypeFieldData();

                 list.each(function(options,index){

                             options[index].click();
                            browser.driver.sleep(5000);
                })
        });
</code>```

After executing the code it is displaying below error message.

```<code>should test certificate tab To click on every option in the Type drop down
</code>```

- Failed: Cannot read property 'click' of undefined

Can any one help me in solving this issue

答:
Usually one needs first to click the element, that holds the dropdown, to open the selection list.

Also because of your stale element reference error I'll add Expected Conditions

Try this code:

```<code>//Testcase 19 : To click on every option in the
//"Type" drop down
it('To click on every option in the Type drop down',()=>{
    var EC = protractor.ExpectedConditions;
    var dropdownElement = $('p-dropdown[formcontrolname="CertificationsType"] div.ui-dropdown');
    //To click on every element of the "Type" drop down field content
    let list=page.getTypeFieldData();
    list.each(function(option){
        //wait for the element to be visible and click the dropdown element to open selection
        browser.wait(EC.visibilityOf(dropdownElement),5000);
        dropdownElement.click();
        //wait for selection to be visible and click the value to select
        browser.wait(EC.visibilityOf(option), 5000);
        option.click();
        browser.driver.sleep(5000);
        })
    });
</code>```

UPDATE

There was a typo in my "dropdownElement" selector. Instead of ui-dropdown it should be div.ui-dropdown (was a wrong use of CSS Selectors - fixed now in above code).

Should there be a message like "element not clickable, other element would receive the click", adjust "dropdownElement" to select that element.

Body:
I am going to write automation scripts for angular 4 application which uses primeng drop down .

The code is below for the drop down control.

            <input class="ng-tns-c4-13" readonly="" role="listbox" type="text" aria-label="Other Programming">

       Other Programming

                       Select Type

                        Other Programming

                            Source Programming

                            Techinical programming

My Page Object file code is below.

//To return "Type" drop down field options
getTypeFieldData(){

let type_dropdown = element(by.css('p-dropdown[formcontrolname="CertificationsType"]'));
let ul_element = type_dropdown.element(by.tagName('ul'));
let li_elements= ul_element.all(by.tagName('li'));
    return li_elements;
}

My Spec file code is below.

//Testcase 19 : To click on every option in the
    //"Type" drop down
    it('To click on every option in the Type drop down',()=>{
        //To click on every element of the "Type" drop down field content
        let list=page.getTypeFieldData();

                 list.each(function(options,index){

                             options[index].click();
                            browser.driver.sleep(5000);
                })
        });

After executing the code it is displaying below error message.

should test certificate tab To click on every option in the Type drop down

- Failed: Cannot read property 'click' of undefined

Can any one help me in solving this issue

Body:
Usually one needs first to click the element, that holds the dropdown, to open the selection list.

Also because of your stale element reference error I'll add Expected Conditions

Try this code:

//Testcase 19 : To click on every option in the
//"Type" drop down
it('To click on every option in the Type drop down',()=>{
    var EC = protractor.ExpectedConditions;
    var dropdownElement = $('p-dropdown[formcontrolname="CertificationsType"] div.ui-dropdown');
    //To click on every element of the "Type" drop down field content
    let list=page.getTypeFieldData();
    list.each(function(option){
        //wait for the element to be visible and click the dropdown element to open selection
        browser.wait(EC.visibilityOf(dropdownElement),5000);
        dropdownElement.click();
        //wait for selection to be visible and click the value to select
        browser.wait(EC.visibilityOf(option), 5000);
        option.click();
        browser.driver.sleep(5000);
        })
    });

UPDATE

There was a typo in my "dropdownElement" selector. Instead of ui-dropdown it should be div.ui-dropdown (was a wrong use of CSS Selectors - fixed now in above code).

Should there be a message like "element not clickable, other element would receive the click", adjust "dropdownElement" to select that element.


来源: stackexchange

问:
Classify a language as Turing-recognizable or co-Turing-recognizable
I have this language

```<code>L = {<M> | M is a TM that accepts w whenever it accepts w^R}
</code>```

I was able to prove that this language is undecidable.

But is this language Turing-recognizable or co-Turing-recognizable?

答:
A language is RE if a TM can halt-accept on all strings in the language. A language is coRE if a TM can halt-reject on all strings not in the language. For L to be RE, we would need to be able to tell that TM always accepts w^R when it accepts w. For L to be coRE, we would need to be able to tell that TM accepts some w but not the corresponding w^R. It is neither RE nor coRE.

It is not RE because if a particular TM happens to accept the empty language, and therefore belongs to L, there is no way to recognize this fact. A recognizer for our language would allow us to recognize TMs that accept the empty language, an impossibility.

It is not coRE because if a particular TM happens to accept a language consisting of a single non-palindromic string, and therefore doesn't belong to L, there is no way to recognize this fact. A recognizer for our language would allow us to recognize TMs that accept a single non-palindromic string, an impossibility.

ContentLicense: CC BY-SA 3.0

Body:
I have this language

L = {<M> | M is a TM that accepts w whenever it accepts w^R}

I was able to prove that this language is undecidable.

But is this language Turing-recognizable or co-Turing-recognizable?


问:
Trouble writing a query for two tables using these tables (below)
MySQL

I am trying to fetch value's from a table Province that has a foreign key of country table.

```<code>SELECT *
  FROM province
  JOIN country
    ON country.Country_Id = province.Province_Id
</code>```

country table

province table

What I am trying to do: I want all the entries to shown in one single table on my PHP web page.

Error is : warning page

答:
Do a simple LEFT JOIN like below :

```<code>SELECT * FROM province
LEFT JOIN country ON province.country_Id = country.country_Id
</code>```

Body:
MySQL

I am trying to fetch value's from a table Province that has a foreign key of country table.

SELECT *
  FROM province
  JOIN country
    ON country.Country_Id = province.Province_Id

country table

province table

What I am trying to do: I want all the entries to shown in one single table on my PHP web page.

Error is : warning page

Body:
Do a simple LEFT JOIN like below :

SELECT * FROM province
LEFT JOIN country ON province.country_Id = country.country_Id


问:
extract list of string from list of complex type
How can I obtain from List<ComplexObject> a List<string>, supposing ComplexObject has two properties: prop1 of type string and prop2 of type int. And I am interested to extract a List<string> (list of prop1).

With an example, maybe it's clearer.

Imagine you have List<Country> where Country is the complex object with Id and Name. And I am interested to extract from countryList just a nameList with all the names.

I know I can do something like:

```<code>            List<string> nameList = new List<string>();

            foreach (var country in countryList)
            {
                nameList.Add(country.Name);
            }
</code>```

...but I am wondering if there is a simpler and quicker way to extract nameList from countryList. Maybe with lambda or something.

And also can that list of strings be easily then converted into a DataTable?

Thank you.

答:
That's a common use case for a LINQ select that converts the result enumeration into a list. It's easier done than said:

```<code>var nameList = countryList.Select(c => c.Name).ToList();
</code>```

Conversion to a DataTable doesn't come so conveniently packaged. Here's an answer about doing that.

Body:
How can I obtain from List<ComplexObject> a List<string>, supposing ComplexObject has two properties: prop1 of type string and prop2 of type int. And I am interested to extract a List<string> (list of prop1).

With an example, maybe it's clearer.

Imagine you have List<Country> where Country is the complex object with Id and Name. And I am interested to extract from countryList just a nameList with all the names.

I know I can do something like:

            List<string> nameList = new List<string>();

            foreach (var country in countryList)
            {
                nameList.Add(country.Name);
            }

...but I am wondering if there is a simpler and quicker way to extract nameList from countryList. Maybe with lambda or something.

And also can that list of strings be easily then converted into a DataTable?

Thank you.

Body:
That's a common use case for a LINQ select that converts the result enumeration into a list. It's easier done than said:

var nameList = countryList.Select(c => c.Name).ToList();

Conversion to a DataTable doesn't come so conveniently packaged. Here's an answer about doing that.


问:
Kivy Gaussian blur
It is a Kivy user.
The other day I found something interesting in Github.
I definitely want to realize it, but I do not know why this happend even if I read the code.
It is the URL below. What kind of code can I use to apply this Gaussian blur?

In GitHub

Also found in youtube

答: The important parts are lines 60 and 61 in the linked code, plus line 42 to import the MaskEffect. You can do exactly the same thing in your own code, with an appropriate import and setting an EffectWidget's effect to MaskEffect.

Title: Kivy Gaussian blur


问:
How to create Three-Line Listview Items?
I have three-line items on my Listview ( like this one ), but I want to change it like this other. What I want to do is to have this "--" divider between the subheader (the black one) and the complementary text (the grayish one), and I want the complementary text to be in the second and third line.

This is the code I'm using for my items (doesn't include avatar's code)

```<code><TextView
        android:id="@+id/txtNombrePDV"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="La bendición"
        android:textColor="@color/colorPrimaryText"
        android:ellipsize="marquee"
        android:lines="1"
        android:scrollHorizontally="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:textSize="@dimen/list_primary_text" />

    <TextView
        android:id="@+id/txtNombreMunicipio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stack Overflow"
        android:textColor="@color/colorPrimaryText"
        android:ellipsize="marquee"
        android:lines="1"
        android:scrollHorizontally="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:textSize="@dimen/list_secondary_text"
        />

    <TextView
        android:id="@+id/txtDireccion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit"
        android:textColor="@color/colorSecondaryText"
        android:ellipsize="marquee"
        android:lines="1"
        android:scrollHorizontally="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:textSize="@dimen/list_secondary_text"
        />
</LinearLayout>
</code>```

答:
Combine the text for Subheader & Complimentary text,use Spannable String to set the colors to respective text.
Refer this spannable string example for better understanding</p>

Body:
I have three-line items on my Listview ( like this one ), but I want to change it like this other. What I want to do is to have this "--" divider between the subheader (the black one) and the complementary text (the grayish one), and I want the complementary text to be in the second and third line.

This is the code I'm using for my items (doesn't include avatar's code)

<TextView
        android:id="@+id/txtNombrePDV"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="La bendición"
        android:textColor="@color/colorPrimaryText"
        android:ellipsize="marquee"
        android:lines="1"
        android:scrollHorizontally="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:textSize="@dimen/list_primary_text" />

    <TextView
        android:id="@+id/txtNombreMunicipio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stack Overflow"
        android:textColor="@color/colorPrimaryText"
        android:ellipsize="marquee"
        android:lines="1"
        android:scrollHorizontally="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:textSize="@dimen/list_secondary_text"
        />

    <TextView
        android:id="@+id/txtDireccion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit"
        android:textColor="@color/colorSecondaryText"
        android:ellipsize="marquee"
        android:lines="1"
        android:scrollHorizontally="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:textSize="@dimen/list_secondary_text"
        />
</LinearLayout>


问:
why checkbox is hidden even using my htmlhelper?
I've read a lot of links about hidden filed bout checkbox I've decided use custom htmlhelper but at the moment, I can't see checkbox in my page when I remove checkbox word in type="checkbox" it's shown as a textbox I think it's sensitive about type of control that is name checkbox.

Update :
I didn't have any input filed with hidden value
Picture

```<code> public static class HelperUI
{
    public static MvcHtmlString CheckBoxSimpleFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, object htmlAttributes)
    {
        string checkBoxWithHidden = htmlHelper.CheckBoxFor(expression, htmlAttributes).ToHtmlString().Trim();
        string pureCheckBox = checkBoxWithHidden.Substring(0, checkBoxWithHidden.IndexOf("<input", 1));
        return new MvcHtmlString(pureCheckBox);
    }
}

 <div class="col-md-6">
     <div class="form-group row">
         <label class="text-right col-md-3">وضعیت</label>

         <div class="col-md-9">

             @Html.CheckBoxSimpleFor(model => model.Status, new { @class = "form-control filled-in" })

         </div>
     </div>
 </div>
</code>```

答:
Hi @joe if you using bootstrap for html designing, then the checkbox will be shows as hidden because of bootstrap checkbox html sysntax or designing is different make change as per it

```<code>  <div class="checkbox">
     <input id="checkbox1" type="checkbox">
     <label for="checkbox1">
      Default
  </label>
       </div>
</code>```

this is the checkbox designing sysntax or code in bootstrap, so you need to make change as per

```<code>    <div class="checkbox col-md-9">
         @Html.CheckBoxSimpleFor(model => model.Status, new { @class = " filled-in" })
    </div>
</code>```

Body:
I've read a lot of links about hidden filed bout checkbox I've decided use custom htmlhelper but at the moment, I can't see checkbox in my page when I remove checkbox word in type="checkbox" it's shown as a textbox I think it's sensitive about type of control that is name checkbox.

Update :
I didn't have any input filed with hidden value
Picture

 public static class HelperUI
{
    public static MvcHtmlString CheckBoxSimpleFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, object htmlAttributes)
    {
        string checkBoxWithHidden = htmlHelper.CheckBoxFor(expression, htmlAttributes).ToHtmlString().Trim();
        string pureCheckBox = checkBoxWithHidden.Substring(0, checkBoxWithHidden.IndexOf("<input", 1));
        return new MvcHtmlString(pureCheckBox);
    }
}

         وضعیت

             @Html.CheckBoxSimpleFor(model => model.Status, new { @class = "form-control filled-in" })

Body:
Hi @joe if you using bootstrap for html designing, then the checkbox will be shows as hidden because of bootstrap checkbox html sysntax or designing is different make change as per it

  <div class="checkbox">
     <input id="checkbox1" type="checkbox">
     <label for="checkbox1">
      Default
  </label>
       </div>

this is the checkbox designing sysntax or code in bootstrap, so you need to make change as per

    <div class="checkbox col-md-9">
         @Html.CheckBoxSimpleFor(model => model.Status, new { @class = " filled-in" })
    </div>


问:
Visual Studio Setup project should not delete file during uninstall
I created Visual Studio 2005 Setup project for my application. Windows Installer during installation put one xml file into AppData/myCustomFolder. I used File System Editor and added special folder - user's app data folder, then included that xml there.

When I uninstall application from Control Panel folder from Program Files is deleted, but also my xml file from AppData is deleted too. I need to leave this xml file in the AppData always, even when user re-install application.

How I could do it?

答:
Set the Permanent property to True

Permanent Property

ContentLicense: CC BY-SA 2.5


问:
C program not entering for loop
I am currently writing a compiler for a piece of University coursework. It takes X language and transpiles it into C. One of the outputs in C is this:

```<code>#include <stdio.h>
int main(void) {
    int integer,i;
    scanf("%d",&integer);
    if(integer <= 5 || integer >= 12)
    {
        printf("%d",integer);
    }
    printf("%d",(36 - 1));
    printf("\n");
    for(integer = -1;integer <= -5;integer += -1)
    {
        printf("%d",integer);
        printf("\n");
    }
    i = -1;
    for(integer = i * i * i;integer <= i * i * (i + i + i + i + i);integer += i * i * i * i * i)
    {
        printf("%d",integer);
        printf("\n");
    }
}
</code>```

When running this code after compiling with gcc v5.4.0 and inputting 12345 for the first scanf, the program doesn't enter either of the for loops when it seems that it should.

I have a feeling it's to do with the pointer passed to scanf, but I'm not really sure since I'm new to C.

答:
Your code doesn't enter the loops because the loop conditions are never met.

In the case of the first loop:

```<code>for(integer = -1;integer <= -5;integer += -1)
</code>```

integer starts out as -1.  You then check integer <= -5.  -1 is not less than -5, so the condition is false and the loop is not entered.

For the second loop:

```<code>i = -1;
for(integer = i * i * i;integer <= i * i * (i + i + i + i + i);integer += i * i * i * i * i)
</code>```

integer starts out as i * i * i == -1 * -1 * -1 == -1.  You then compare this against i * i * (i + i + i + i + i) == -1 * -1 * ( -1 + -1 + -1 + -1 + -1) == 1 * ( -5 ) == -5.  So your comparison becomes -1 < -5, which is false, so the loop is not entered.

Title: C program not entering for loop

Body:
I am currently writing a compiler for a piece of University coursework. It takes X language and transpiles it into C. One of the outputs in C is this:

#include <stdio.h>
int main(void) {
    int integer,i;
    scanf("%d",&integer);
    if(integer <= 5 || integer >= 12)
    {
        printf("%d",integer);
    }
    printf("%d",(36 - 1));
    printf("\n");
    for(integer = -1;integer <= -5;integer += -1)
    {
        printf("%d",integer);
        printf("\n");
    }
    i = -1;
    for(integer = i * i * i;integer <= i * i * (i + i + i + i + i);integer += i * i * i * i * i)
    {
        printf("%d",integer);
        printf("\n");
    }
}

When running this code after compiling with gcc v5.4.0 and inputting 12345 for the first scanf, the program doesn't enter either of the for loops when it seems that it should.

I have a feeling it's to do with the pointer passed to scanf, but I'm not really sure since I'm new to C.

Body:
Your code doesn't enter the loops because the loop conditions are never met.

In the case of the first loop:

for(integer = -1;integer <= -5;integer += -1)

integer starts out as -1.  You then check integer <= -5.  -1 is not less than -5, so the condition is false and the loop is not entered.

For the second loop:

i = -1;
for(integer = i * i * i;integer <= i * i * (i + i + i + i + i);integer += i * i * i * i * i)

integer starts out as i * i * i == -1 * -1 * -1 == -1.  You then compare this against i * i * (i + i + i + i + i) == -1 * -1 * ( -1 + -1 + -1 + -1 + -1) == 1 * ( -5 ) == -5.  So your comparison becomes -1 < -5, which is false, so the loop is not entered.


问:
Cassandra add column after particular column
I need to alter the table to add a new column after a particular column or as last column, I have been through the document but no luck.</p>

答:
Let's say I'm starting with a table that has this definition:

```<code>CREATE TABLE mykeyspace.letterstable (
    column_n TEXT,
    column_b TEXT,
    column_c TEXT,
    column_z TEXT,
    PRIMARY KEY (column_n));
</code>```

1- Adding a column is a simple matter.

```<code>ALTER TABLE mykeyspace.letterstable ADD column_j TEXT;
</code>```

2- After adding the new column, my table definition will look like this:

```<code>desc table mykeyspace.letterstable;

CREATE TABLE mykeyspace.letterstable (
    column_n TEXT,
    column_b TEXT,
    column_c TEXT,
    column_j TEXT,
    column_z TEXT,
    PRIMARY KEY (column_n));
</code>```

This is because columns in Cassandra are stored by ASCII-betical order, after the keys (so column_n will always be first, because it is the  only key).  I can't tell Cassandra that I want my new column_j to go after column_z.  It's going to put it between column_c and column_z on its own.

Body:
Let's say I'm starting with a table that has this definition:

CREATE TABLE mykeyspace.letterstable (
    column_n TEXT,
    column_b TEXT,
    column_c TEXT,
    column_z TEXT,
    PRIMARY KEY (column_n));

1- Adding a column is a simple matter.

ALTER TABLE mykeyspace.letterstable ADD column_j TEXT;

2- After adding the new column, my table definition will look like this:

desc table mykeyspace.letterstable;

CREATE TABLE mykeyspace.letterstable (
    column_n TEXT,
    column_b TEXT,
    column_c TEXT,
    column_j TEXT,
    column_z TEXT,
    PRIMARY KEY (column_n));

This is because columns in Cassandra are stored by ASCII-betical order, after the keys (so column_n will always be first, because it is the  only key).  I can't tell Cassandra that I want my new column_j to go after column_z.  It's going to put it between column_c and column_z on its own.


问:
database in restore state
I tired to restore my database but I saw that I am restoring a wrong one, so I immediately kill the process. Unfortunately the database was in restoring state and is not accessible anymore.

Can anyone help me to return back to normal state?

Thanks in advance

答:
Try using the following query to return your database online

```<code>RESTORE DATABASE MyDatabase
WITH RECOVERY
</code>```

If it throws an exception so you need to restore from a latest backup

```<code>RESTORE DATABASE MyDatabase
FROM DISK = 'C:\MyDatabase.bak'
WITH REPLACE,RECOVERY
</code>```

Title: database in restore state

Body:
Try using the following query to return your database online

RESTORE DATABASE MyDatabase
WITH RECOVERY

If it throws an exception so you need to restore from a latest backup

RESTORE DATABASE MyDatabase
FROM DISK = 'C:\MyDatabase.bak'
WITH REPLACE,RECOVERY


问:
Javascript to check whether a checkbox is being checked or unchecked
I have a javascript routine that is performing actions on a group of checkboxes, but the final action I want to set the clicked checkbox to checked or unchecked based on if the user was checking the box or unchecking.

Unfortunately, every time I check for whether it is being checked or unchecked, it returns "on" indicating the user is always checking the box!  Any help would be appreciated, I've also included the javascript.

```<code>// Uncheck all the checkboxs with the same Tax Credit
for (i=0; i<arrChecks.length; i++)
{
    var attribute = arrChecks[i].getAttribute("xid")
    if (attribute == elementName)
    {
        // if the current state is checked, unchecked and vice-versa
        if (arrChecks[i].value == "on")   // <-- This is always returning true, even if the box is being unchecked
        {
            arrChecks[i].checked = 1;
        } else {
            arrChecks[i].checked = 0;
        }

    } else {
        arrChecks[i].checked = 0;
    }
}
</code>```

答:
The value attribute of a checkbox is what you set by:

```<code><input type='checkbox' name='test' value='1'>
</code>```

So when someone checks that box, the server receives a variable named test with a value of 1 - what you want to check for is not the value of it (which will never change, whether it is checked or not) but the checked status of the checkbox.

So, if you replace this code:

```<code>if (arrChecks[i].value == "on")
{
    arrChecks[i].checked = 1;
} else {
    arrChecks[i].checked = 0;
}
</code>```

With this:

```<code>arrChecks[i].checked = !arrChecks[i].checked;
</code>```

It should work. You should use true and false instead of 0 and 1 for this.

OwnerDisplayName: Mark K.

Body:
I have a javascript routine that is performing actions on a group of checkboxes, but the final action I want to set the clicked checkbox to checked or unchecked based on if the user was checking the box or unchecking.

Unfortunately, every time I check for whether it is being checked or unchecked, it returns "on" indicating the user is always checking the box!  Any help would be appreciated, I've also included the javascript.

// Uncheck all the checkboxs with the same Tax Credit
for (i=0; i<arrChecks.length; i++)
{
    var attribute = arrChecks[i].getAttribute("xid")
    if (attribute == elementName)
    {
        // if the current state is checked, unchecked and vice-versa
        if (arrChecks[i].value == "on")   // <-- This is always returning true, even if the box is being unchecked
        {
            arrChecks[i].checked = 1;
        } else {
            arrChecks[i].checked = 0;
        }

    } else {
        arrChecks[i].checked = 0;
    }
}

Body:
The value attribute of a checkbox is what you set by:

<input type='checkbox' name='test' value='1'>

So when someone checks that box, the server receives a variable named test with a value of 1 - what you want to check for is not the value of it (which will never change, whether it is checked or not) but the checked status of the checkbox.

So, if you replace this code:

if (arrChecks[i].value == "on")
{
    arrChecks[i].checked = 1;
} else {
    arrChecks[i].checked = 0;
}

With this:

arrChecks[i].checked = !arrChecks[i].checked;

It should work. You should use true and false instead of 0 and 1 for this.

OwnerDisplayName: Paolo Bergantino

LastEditorDisplayName: Paolo Bergantino


答:
Using LINQ: </p>

```<code>var names = countryList.Select(c => c.Name).ToList();
</code>```

Title: extract list of string from list of complex type

Body:
Using LINQ:

var names = countryList.Select(c => c.Name).ToList();


问:
R: for loop error
I'm trying to remove NA values in the columns of a data frame and trying to cbind the resulting vectors another data frame. Here's the code I'm using:

```<code>for (x in df_wide[4:8]) {
  a <- df_wide[[x]][!is.na(df_wide[[x]])]
  df <- cbind(df, a)
}
</code>```

But I'm getting this error:

```<code>`Error in .subset2(x, i, exact = exact) : no such index at level 1`
</code>```

I've also tried using apply function, but I got the same error.

```<code>`Error in .subset2(x, i, exact = exact) : no such index at level 1`
function (x, i, exact)
if (is.matrix(i)) as.matrix(x)[[i]] else .subset2(x, i, exact = exact)
</code>```

Can anyone please explain me why I'm getting this error and how can I fix it?

If you want to see the data frame, please refer to my previous question.

Thanks in advance.

答:
You only need to specify for (x in 4:8). Or you can can reference the column names, but right now you are using columns as indexes, which is only useful for integer columns (if that's your goal).

I don't think this way is the best way to go about solving your problem, though.

Title: R: for loop error

Body:
I'm trying to remove NA values in the columns of a data frame and trying to cbind the resulting vectors another data frame. Here's the code I'm using:

for (x in df_wide[4:8]) {
  a <- df_wide[[x]][!is.na(df_wide[[x]])]
  df <- cbind(df, a)
}

But I'm getting this error:

`Error in .subset2(x, i, exact = exact) : no such index at level 1`

I've also tried using apply function, but I got the same error.

`Error in .subset2(x, i, exact = exact) : no such index at level 1`
function (x, i, exact)
if (is.matrix(i)) as.matrix(x)[[i]] else .subset2(x, i, exact = exact)

Can anyone please explain me why I'm getting this error and how can I fix it?

If you want to see the data frame, please refer to my previous question.

Thanks in advance.


答:
Cassandra will store table data based on partition & clustering key.

Standard CQL for adding column:

```<code>ALTER TABLE keyspace.table ADD COLUMN column1 columnType;
</code>```

Running DESC table for a given table via CQLSH does not portray how the data is stored. It will always list the partition key & clustering key first; then the remaining columns in alphabetical order.

https://docs.datastax.com/en/cql/3.1/cql/cql_reference/alter_table_r.html

Cassandra create table won't keep column order

Title: Cassandra add column after particular column

Body: I need to alter the table to add a new column after a particular column or as last column, I have been through the document but no luck.

Body:
Cassandra will store table data based on partition & clustering key.

Standard CQL for adding column:

ALTER TABLE keyspace.table ADD COLUMN column1 columnType;

Running DESC table for a given table via CQLSH does not portray how the data is stored. It will always list the partition key & clustering key first; then the remaining columns in alphabetical order.

https://docs.datastax.com/en/cql/3.1/cql/cql_reference/alter_table_r.html

Cassandra create table won't keep column order


问:
Targeting instances of JQuery UI Accordion without knowing what they are
I have a site that uses jquery UI accordions on different pages. The script for these accordions is on the page in each case.

We're looking into daily site prints for all pages so we need those accordions to be fully expanded when we do the site print (we'll be doing this by detecting the site printer's userAgent string because they can issue a custom one).

The site printer can halt execution of javascript on a page to keep content fully expanded but we also use AJAX scripts so that would prevent content from loading.

So we need a script that targets any jquery accordions on a page and makes them fully expand. We have a custom.js file that is present on all pages so we could place a command there.

My question is, is it possible to target all instances of accordion objects without already knowing what they are? I'm looking at the possibility of putting a script in the custom.js file rather than having to rewrite all the JQuery accordion calls page by page (and trying to get everybody that adds stuff to the site to also remember to write a conditional userAgent based expand everytime they use an accordion).

答:
Without seeing your code or knowing anything about your current HTML, you can try something like this:

```<code>$(".ui-widget.ui-accordion").each(function(index, elem){
  // Code that you want to execute on each Accordion
  // For example, we could disable each one:
  $(elem).accordion("disable");
});
</code>```

I don't see a method to expand all panels at once. Likely, you would have to activate each panel.

Found this: jQuery UI Accordion Expand/Collapse All

It advises using the theming to make the accordion look correct, and then roll your own ability to expand all.

Body:
Without seeing your code or knowing anything about your current HTML, you can try something like this:

$(".ui-widget.ui-accordion").each(function(index, elem){
  // Code that you want to execute on each Accordion
  // For example, we could disable each one:
  $(elem).accordion("disable");
});

I don't see a method to expand all panels at once. Likely, you would have to activate each panel.

Found this: jQuery UI Accordion Expand/Collapse All

It advises using the theming to make the accordion look correct, and then roll your own ability to expand all.


问:
Grab view from touch event
i have a quick question,

I have a view with multiple subviews.

In my view i have touches began etc..

is there a way to retrieve a subview from the touches began without having to detect the location from the touch and then have a big if else to c which subview is in that specific area.

Thanks.

答:
The method you want is the UIView instance method -(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event. That will return you the lowest-level subview containing point.

So you get the point of your touch, pass it to that method of your biggest container UIView, and get back a handle to the frontmost subview that got touched. Easy peasy.

Title: Grab view from touch event


问:
Suppress screen share permission dialog in Chrome App
We are implementing a Chrome App that runs in a controlled environment on a specific machine under Windows. We have complete control over the environment, including using command-line args to run Chrome, changing registry settings, etc.

Part of the functionality of the app is to take screen captures and stream them to a remote machine. When this feature is initiated, Chrome displays the permission dialog ("Chrome wants to share your screen...") and requires validation by the user.

In the context of our app, this is poor user experience and we would like to find a way to suppress this dialog. As I mentioned, we have complete control over the host machine. Is there any way to do this short of making our own custom Chrome build?

答:
Try running Chrome with the command line argument --auto-select-desktop-capture-source="Entire screen". Source: Chromium issue. Also related: Issue about force-installed extensions and desktop sharing.

In case you want to compile chrome yourself, this would be a good starting point for whitelisting your own extension


问:
Determine if unicode character has a glyph in UIFont
I want to find out if a certain unicode character has a glyph representation even if by a cascading font.  For example, let's say I am using UIFont.systemFont(withSize:18) and a string \u{1CDA} and would like to find out if this font will display the graphical representation of this character, and not a default question mark representation (ie there's no graphical representation, even by the supporting cascade fonts).

答:
This may work too, it doesn't check the glyph, but it checks the character set

```<code>import CoreText
func isSupported(unicode: UnicodeScalar, font: UIFont) -> Bool {
    let coreFont: CTFont = font
    let characterSet: CharacterSet = CTFontCopyCharacterSet(coreFont) as CharacterSet
    return characterSet.contains(unicode)
 }
</code>```

Example test:

```<code>let testString = "R"
let font = UIFont.boldSystemFont(ofSize: 10.0)
print("\(isSupported(unicode: testString.unicodeScalars.first!, font: font))")
</code>```

Body:
This may work too, it doesn't check the glyph, but it checks the character set

import CoreText
func isSupported(unicode: UnicodeScalar, font: UIFont) -> Bool {
    let coreFont: CTFont = font
    let characterSet: CharacterSet = CTFontCopyCharacterSet(coreFont) as CharacterSet
    return characterSet.contains(unicode)
 }

Example test:

let testString = "R"
let font = UIFont.boldSystemFont(ofSize: 10.0)
print("\(isSupported(unicode: testString.unicodeScalars.first!, font: font))")


问:
Remove & sort "using" statements in Visual Studio 2008?
Is there a way to automate the "Removal & Sorting" of "using" statements in Visual Studio 2008?</p>

答: The only way I'm aware of is using a third party tool like CodeRush & Refactor Pro! or Resharper.</p>


问:
Preventing a Div From Expanding - Used as an Input
I have a div that s being used as an input box.

```<code><div class="div_input" contentEditable="true" onkeyup="DoThing()" id="an_id_value">455</div>
</code>```

This is the CSS

```<code>.div_input {
    background-color: white;
    outline:1px solid darkgray;
    font: -moz-field;
    font: -webkit-small-control;
    margin-top: 5px;
    padding: 2px 3px;
    width: 100px;
}
</code>```

When you type in the box with characters that are longer than the width the following happens:

On Chrome it acts just like I would like it expands but retains it visual text. On Firefox Quantum it will overrun the other elements to the right.

How can I prevent this behavior? I have tried wrapping it in a fix of fixed width but that does not change anything.

答:
Use word-break: break-all; so all words break when they hit the limit. Something like this:

.div_input {
    background-color: white;
    outline:1px solid darkgray;
    font: -moz-field;
    font: -webkit-small-control;
    margin-top: 5px;
    padding: 2px 3px;
    width: 100px;
    word-break: break-all;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="div_input" contentEditable="true" onkeyup="DoThing()" id="an_id_value">455</div></code>```

Here you have it on JSFiddle: https://jsfiddle.net/c61askwy/1/

Thanks to VXp for pointing out the snippet didn't have the solution hehe

Body:
I have a div that s being used as an input box.

455

This is the CSS

.div_input {
    background-color: white;
    outline:1px solid darkgray;
    font: -moz-field;
    font: -webkit-small-control;
    margin-top: 5px;
    padding: 2px 3px;
    width: 100px;
}

When you type in the box with characters that are longer than the width the following happens:

On Chrome it acts just like I would like it expands but retains it visual text. On Firefox Quantum it will overrun the other elements to the right.

How can I prevent this behavior? I have tried wrapping it in a fix of fixed width but that does not change anything.

Body:
Use word-break: break-all; so all words break when they hit the limit. Something like this:

.div_input {
    background-color: white;
    outline:1px solid darkgray;
    font: -moz-field;
    font: -webkit-small-control;
    margin-top: 5px;
    padding: 2px 3px;
    width: 100px;
    word-break: break-all;
}

<div class="div_input" contentEditable="true" onkeyup="DoThing()" id="an_id_value">455</div>

Here you have it on JSFiddle: https://jsfiddle.net/c61askwy/1/

Thanks to VXp for pointing out the snippet didn't have the solution hehe


问:
Redirection in aspx page of MVC application?
I am replacing a website that was written in conventional asp.net with an MVC system

A third party system we use and cannot easily change is expecting to be able to use a url of the format

http://website url here/?searchtype=both&param1=value1&param2=value2

I need to redirect this to

http://website url here/Home/FindByIdentifier?searchtype=both&param1=value1&param2=value2

How can I do this?  Its kind of a redirect to action?

If this is complicated, is this kind of thing possible within Azure which is where the system will now be hosted, as an app service?

Its basically a case of making the third party system still function as though nothing has been changed

My new application uses C# MVC5 with Razor views

Paul

答:
Something like this added to your home controller</p>

```<code>public ActionResult Here()
{
   var url = $"Home/FindByIdentifier{Request.Url.Query}";
   return Redirect(url);
}
</code>```

Body:
Something like this added to your home controller

public ActionResult Here()
{
   var url = $"Home/FindByIdentifier{Request.Url.Query}";
   return Redirect(url);
}


问:
Dynamically generate query with diff number of "where"?
How can I dynamically generate query to the db if I don't know how much filter and update -  values will be in the $filters and $updates arrays?
Template of the query is below:

```<code>$model::where($key_1, '=', $filter1)
    ->where($key_2, '=', $filter_2)
    ->where($key_n, '=', $filter_n)
    ->update([$key_1 => $update_1,
        $key_2 => $update_2,
        $key_n => $update_n
    ]);
</code>```

答:
You can use parameter grouping:

```<code>$model::where(function ($query) use ($filters) {
            foreach($filters as $filter) {
                $query->where($filter->column, '>', $filter->value);
            }
            return $query;
        })
</code>```

...

Body:
How can I dynamically generate query to the db if I don't know how much filter and update -  values will be in the $filters and $updates arrays?
Template of the query is below:

$model::where($key_1, '=', $filter1)
    ->where($key_2, '=', $filter_2)
    ->where($key_n, '=', $filter_n)
    ->update([$key_1 => $update_1,
        $key_2 => $update_2,
        $key_n => $update_n
    ]);

Body:
You can use parameter grouping:

$model::where(function ($query) use ($filters) {
            foreach($filters as $filter) {
                $query->where($filter->column, '>', $filter->value);
            }
            return $query;
        })

...


问:
Saving an EF instance which has multiple parents
When mapping back from business logic objects to EF objects, one of the main problems I have is cases where the same instance has 2 parents:

(Objects are yellow, properties are orange)

In the business logic world, there is only one instance of the Tree object here (which appears as a child of multiple parents: Forest and Section)

When I map everything back into EF objects with AutoMapper, EF thinks there are 2 separate instances of tree (despite them having the same ID). It therefore creates a duplicate in the DB.

What is the correct way to manage this scenario so that both Forest and Section point to the same record of Tree in the DB?

Do we have to go through and manually make sure everything is attached which might be considered a duplicate?

答: I believe that if you don't want duplicates here, both children must not only reference the ID but also the specific instance in memory so EF knows it should be the same record (navigation property).  Otherwise, you have to save the parent record first and then assign the key to each child after the fact.  If this isn't a GUID but an auto generated id, then you probably need to use the same reference.</p>


问:
How to format a moment date with angularjs
I am using angularjs with moment.

I need format a moment date.

Moment is installed correctly and working.

I have a variable mydate showing below.

My code is:

```<code>$scope.mylabel= moment(date).format('YYYY-MM-DD');
</code>```

After that, I get $scope.mylabel= 'invalid date'

What am I doing wrong?

mydate is:

```<code>{date: r, mdp: {…}, selectable: true, $$hashKey: "object:156"}
$$hashKey:
"object:156"
date:
r
_d:Fri Nov 10 2017 00:00:00 GMT-0200 (Horário brasileiro de verão) {}
_isAMomentObject:true
_isUTC:false
_isValid:true
</code>```

The complete code is:

I am using the next widget:

```<code>https://github.com/arca-computing/MultipleDatePicker
</code>```

//markup

```<code><div class="col-sm-3">
    <multiple-date-picker  calendar-id="'myId2'" ng-model="myDate"
    day-click="oneDaySelectionOnly"></multiple-date-picker>
</div>
</code>```

//controller

```<code>angular.module("clinang")
.controller('agendaGeralController'......
 $scope.myDate = [];
 $scope.myDate.push(moment());
 $scope.oneDaySelectionOnly = function (event, date) {
    $scope.mylabel= moment(date).format('YYYY-MM-DD')
    //I also tried date.format('YYYY-MM-DD') and both result in "invalid date")
    $scope.myDate.length = 0;
};
]);
</code>```

答:
If you moment.js is added and date is a valid date, you should get the desired output as

var app = angular.module('app', [])
function Ctrl($scope) {
    $scope.date = '2012-11-20';
    $scope.formattedDate = moment($scope.date).format('YYYY/MM/DD');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.19.2/moment.js"></script>
<div ng-app="app">
    <div ng-controller="Ctrl">
        <div>
            Non-Formatted Date : {{date}}
            <br><br>
            Formatted Date: {{formattedDate}}
        </div>

    </div>
</div></code>```

Body:
I am using angularjs with moment.

I need format a moment date.

Moment is installed correctly and working.

I have a variable mydate showing below.

My code is:

$scope.mylabel= moment(date).format('YYYY-MM-DD');

After that, I get $scope.mylabel= 'invalid date'

What am I doing wrong?

mydate is:

{date: r, mdp: {…}, selectable: true, $$hashKey: "object:156"}
$$hashKey:
"object:156"
date:
r
_d:Fri Nov 10 2017 00:00:00 GMT-0200 (Horário brasileiro de verão) {}
_isAMomentObject:true
_isUTC:false
_isValid:true

The complete code is:

I am using the next widget:

https://github.com/arca-computing/MultipleDatePicker

//markup

    <multiple-date-picker  calendar-id="'myId2'" ng-model="myDate"
    day-click="oneDaySelectionOnly"></multiple-date-picker>

//controller

angular.module("clinang")
.controller('agendaGeralController'......
 $scope.myDate = [];
 $scope.myDate.push(moment());
 $scope.oneDaySelectionOnly = function (event, date) {
    $scope.mylabel= moment(date).format('YYYY-MM-DD')
    //I also tried date.format('YYYY-MM-DD') and both result in "invalid date")
    $scope.myDate.length = 0;
};
]);

Body:
If you moment.js is added and date is a valid date, you should get the desired output as

var app = angular.module('app', [])
function Ctrl($scope) {
    $scope.date = '2012-11-20';
    $scope.formattedDate = moment($scope.date).format('YYYY/MM/DD');
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.19.2/moment.js"></script>
<div ng-app="app">
    <div ng-controller="Ctrl">
        <div>
            Non-Formatted Date : {{date}}
            <br><br>
            Formatted Date: {{formattedDate}}
        </div>

    </div>
</div>


问:
.NET / .NET Core and SQL Server connection mismatch issue
I am developing C# application which is executing ~30 sql queries every second... I have multiple threads which do that. My problem is that when I try to query the sql server with SELECT .... it returns different results.

Example:
If run both SELECT * FROM Users and SELECT * FROM Jobs at the same time from different threads i get responses like:

SELECT * FROM Users -> Job colums with Job values

SELECT * FROM Jobs -> User colums with User values

I am using Dapper like this:

```<code>using (var connection = new SqlConnection(_msSqlProvider.ConnectionString))
            {
                connection.Open();
                return connection.Query<User>(
                    @"SELECT JobId
                        FROM Users
                        WHERE Id = @userId
                        ORDER BY Id ASC",
                    new {userId});
            }
</code>```

My application logs look like (i.e. the query is returning not User model data):

An exception occured while getting user's job: A parameterless
  default constructor or one matching signature (System.Int32 Id,
  System.Int32 UserId, System.Decimal Salary, System.DateTime UpdatedAt)
  is required for SampleApp.User materialization

My application is very different from this and complex but this should be good as example...

Solution:
If anyone reading this question is interested in what was the solution - enabling MARS and connection pooling resolved my issue...

答:
Must use different sql reader or sql command for right solution.
Try this;</p>

```<code>        double vId;
        SqlDataReader dr = null;
        if (db.OpenDR(ref dr, string.Format("select JobId from dbo.Users where Id={0}", vUSERID)))
        {
            if (dr.Read()) vId = dr["JobId"].dToDouble();
            dr.Close();
        }
        return vId;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am developing C# application which is executing ~30 sql queries every second... I have multiple threads which do that. My problem is that when I try to query the sql server with SELECT .... it returns different results.

Example:
If run both SELECT * FROM Users and SELECT * FROM Jobs at the same time from different threads i get responses like:

SELECT * FROM Users -> Job colums with Job values

SELECT * FROM Jobs -> User colums with User values

I am using Dapper like this:

using (var connection = new SqlConnection(_msSqlProvider.ConnectionString))
            {
                connection.Open();
                return connection.Query<User>(
                    @"SELECT JobId
                        FROM Users
                        WHERE Id = @userId
                        ORDER BY Id ASC",
                    new {userId});
            }

My application logs look like (i.e. the query is returning not User model data):

An exception occured while getting user's job: A parameterless
  default constructor or one matching signature (System.Int32 Id,
  System.Int32 UserId, System.Decimal Salary, System.DateTime UpdatedAt)
  is required for SampleApp.User materialization

My application is very different from this and complex but this should be good as example...

Solution:
If anyone reading this question is interested in what was the solution - enabling MARS and connection pooling resolved my issue...

Body:
Must use different sql reader or sql command for right solution.
Try this;

        double vId;
        SqlDataReader dr = null;
        if (db.OpenDR(ref dr, string.Format("select JobId from dbo.Users where Id={0}", vUSERID)))
        {
            if (dr.Read()) vId = dr["JobId"].dToDouble();
            dr.Close();
        }
        return vId;


问:
Django 1.11.7: How do I call a Class method in Views?
In my models.py I have a Class (Paths) with a method, validate_time that tries to access two fields of the Paths model (time_start, time_end):

```<code>class Paths(m.Model):

  time_start: m.TimeField()
  time_end: m.TimeField()

  def validate_time(self):
     start = self.time_start
     end = self.time_end
     print start #print start to test it out
     #...some function that returns True or False
</code>```

I call validate_time in my views.py:

```<code>from .models import Paths

def paths_data(request):
  ps = Paths()
  valid_times = ps.validate_time()
  if valid_times == False:
     ....
</code>```

I see the method, validate_time, is hit because I see the print statement

But it appears the print out says: None

But time_start and time_end have already been saved to the model as strings. How can I get them as their string value in validate_time?

答: You can use either @classmethod or @staticmethod decorator for validate_time

Body:
In my models.py I have a Class (Paths) with a method, validate_time that tries to access two fields of the Paths model (time_start, time_end):

class Paths(m.Model):

  time_start: m.TimeField()
  time_end: m.TimeField()

  def validate_time(self):
     start = self.time_start
     end = self.time_end
     print start #print start to test it out
     #...some function that returns True or False

I call validate_time in my views.py:

from .models import Paths

def paths_data(request):
  ps = Paths()
  valid_times = ps.validate_time()
  if valid_times == False:
     ....

I see the method, validate_time, is hit because I see the print statement

But it appears the print out says: None

But time_start and time_end have already been saved to the model as strings. How can I get them as their string value in validate_time?


问:
How to import module or provide service conditionally? (AOT)
My problem is that one of Angular modules, does not work correctly with the Safari browser.

I have following code :

```<code>@NgModule({
    bootstrap: [ AppComponent ],
    imports: [
        BrowserAnimationsModule,
        BrowserModule.withServerTransition({
            appId: 'app'
        }),
        AppModule,
        'navigator' in window && 'serviceWorker' in navigator ? ServiceWorkerModule.register('./ngsw-worker.js') : ServiceWorkerModuleMock
    ]
})
</code>```

As you can see I want to conditionally import module. When I am using JIT compilation, this mechanism works well. Unfortunately, it is not working with AOT - ServiceWorkerModuleMock is imported regardless condition.

As a solution I was trying to play a little bit with ngDoBootstrap method:

```<code>@NgModule({
    entryComponents: [ AppComponent ],
    imports: [
        BrowserAnimationsModule,
        BrowserModule.withServerTransition({
            appId: 'app'
        }),
        AppModule,
        ServiceWorkerModule.register('./ngsw-worker.js')
    ]
})
export class BrowserAppModule {
    constructor(private injector: Injector) {}

    public ngDoBootstrap(appRef: ApplicationRef): void {
        // console.log('navigator' in window && 'serviceWorker' in navigator);

        appRef.bootstrap(AppComponent);
    }
}
</code>```

But so far I don't know how can I change module imported in @NgModule annotation here. Which method of which class should I use?

Maybe it is possible to change an instance of given service in the Injector? That solution would also satisfy me.

答:
You'll probably want to use another module or function to wrap this logic. This is not ready solution and requires some work, but it is still good enough to show you the idea:

```<code>@NgModule({
    ...
})
export class MyBootstrapModule {
    static getModule() {
        if ('navigator' in window && 'serviceWorker' in navigator) {
            return ServiceWorkerModule.register('./ngsw-worker.js')
        } else {
            return ServiceWorkerModuleMock;
        }
    }
}

@NgModule({
    bootstrap: [ AppComponent ],
    imports: [
        BrowserAnimationsModule,
        BrowserModule.withServerTransition({
            appId: 'app'
        }),
        AppModule,
        MyBootstrapModule.getModule()
    ]
})
</code>```

Also, you can take a look at some other examples of more sophisticated module setup, for example ngrx effects module. It is pretty simple (see below part of it). Please pay attention at how they use ngModule. You may also need to redefine and re-import/re-export some stuff from your modules depending on what you exactly need to do.

```<code>@NgModule({
  providers: [
    Actions,
    EffectsSubscription,
    {
      provide: APP_BOOTSTRAP_LISTENER,
      multi: true,
      deps: [ Injector, EffectsSubscription ],
      useFactory: runAfterBootstrapEffects
    }
  ]
})
export class EffectsModule {
  static run(type: Type<any>) {
    return {
      ngModule: EffectsModule,
      providers: [
        EffectsSubscription,
        type,
        { provide: effects, useExisting: type, multi: true }
      ]
    };
  }
....
</code>```

Body:
My problem is that one of Angular modules, does not work correctly with the Safari browser.

I have following code :

@NgModule({
    bootstrap: [ AppComponent ],
    imports: [
        BrowserAnimationsModule,
        BrowserModule.withServerTransition({
            appId: 'app'
        }),
        AppModule,
        'navigator' in window && 'serviceWorker' in navigator ? ServiceWorkerModule.register('./ngsw-worker.js') : ServiceWorkerModuleMock
    ]
})

As you can see I want to conditionally import module. When I am using JIT compilation, this mechanism works well. Unfortunately, it is not working with AOT - ServiceWorkerModuleMock is imported regardless condition.

As a solution I was trying to play a little bit with ngDoBootstrap method:

@NgModule({
    entryComponents: [ AppComponent ],
    imports: [
        BrowserAnimationsModule,
        BrowserModule.withServerTransition({
            appId: 'app'
        }),
        AppModule,
        ServiceWorkerModule.register('./ngsw-worker.js')
    ]
})
export class BrowserAppModule {
    constructor(private injector: Injector) {}

    public ngDoBootstrap(appRef: ApplicationRef): void {
        // console.log('navigator' in window && 'serviceWorker' in navigator);

        appRef.bootstrap(AppComponent);
    }
}

But so far I don't know how can I change module imported in @NgModule annotation here. Which method of which class should I use?

Maybe it is possible to change an instance of given service in the Injector? That solution would also satisfy me.

Body:
You'll probably want to use another module or function to wrap this logic. This is not ready solution and requires some work, but it is still good enough to show you the idea:

@NgModule({
    ...
})
export class MyBootstrapModule {
    static getModule() {
        if ('navigator' in window && 'serviceWorker' in navigator) {
            return ServiceWorkerModule.register('./ngsw-worker.js')
        } else {
            return ServiceWorkerModuleMock;
        }
    }
}

@NgModule({
    bootstrap: [ AppComponent ],
    imports: [
        BrowserAnimationsModule,
        BrowserModule.withServerTransition({
            appId: 'app'
        }),
        AppModule,
        MyBootstrapModule.getModule()
    ]
})

Also, you can take a look at some other examples of more sophisticated module setup, for example ngrx effects module. It is pretty simple (see below part of it). Please pay attention at how they use ngModule. You may also need to redefine and re-import/re-export some stuff from your modules depending on what you exactly need to do.

@NgModule({
  providers: [
    Actions,
    EffectsSubscription,
    {
      provide: APP_BOOTSTRAP_LISTENER,
      multi: true,
      deps: [ Injector, EffectsSubscription ],
      useFactory: runAfterBootstrapEffects
    }
  ]
})
export class EffectsModule {
  static run(type: Type<any>) {
    return {
      ngModule: EffectsModule,
      providers: [
        EffectsSubscription,
        type,
        { provide: effects, useExisting: type, multi: true }
      ]
    };
  }
....


问:
How to upload a Folder using az dls fs upload
I'm trying to upload a folder (which contains ~100 files) to Azure Data Lake Store.
However, when using

```<code>az dls fs upload --account $adls_account --source-path $src_dir --destination-path $dest_dir --overwrite --thread-count $thread_count --debug
</code>```

My source folder is:

```<code>Test1/Testfolder2
</code>```

Testfolder2 contains close to 100 files. So i would like to upload the folder Testfolder2 as such.

Rather than uploading the folder, it is going inside the folder Testfolder2 and upload the files altogether rather than the folder itself.

can someone help on how to resolve this.

Thasnk,
Arjun

答:
You can upload data to Data Lake Store directly at the root level or to a folder that you created within the account.

For more details, refer "Upload data to a Data Lake Store account".

Body:
I'm trying to upload a folder (which contains ~100 files) to Azure Data Lake Store.
However, when using

az dls fs upload --account $adls_account --source-path $src_dir --destination-path $dest_dir --overwrite --thread-count $thread_count --debug

My source folder is:

Test1/Testfolder2

Testfolder2 contains close to 100 files. So i would like to upload the folder Testfolder2 as such.

Rather than uploading the folder, it is going inside the folder Testfolder2 and upload the files altogether rather than the folder itself.

can someone help on how to resolve this.

Thasnk,
Arjun


问:
Removing One Negative Margin and replacing it with a different value
How would I remove this negative margin and replace it?

What are the ways in which this can be done?

Click on the image to see the links.

You have to Click on the image to see the links.

https://jsfiddle.net/j8fL15s5/15/

Screenshot

```<code>.link a {
        display: block;
        width: 50px;
        height: 50px;
        margin: -50px 0 0;
        background: black;
        box-Shadow: inset 0 0 0 3px #0059dd;
      }
</code>```

One way is by using:

display: flex;

https://jsfiddle.net/j8fL15s5/18/

Are there any other ways to do this?

Can this be accomplished 'without' the use of flex?

答:
Adjusted Styles:

```<code>.link div {
  margin: 0 0 12px 0;
  font-size: 0; /* Remove whitespace created by inline-block */
}

.link a:first-child {
    margin-left: 0px;
}

.link a {
    width: 50px;
    height: 50px;
    margin: 0px;
    background: black;
    box-Shadow: inset 0 0 0 3px #0059dd;
    display: inline-block;
    margin-left: 4px;
}
</code>```

Summary:

Reset margin property values and display them as inline-block

Remove individual anchor link margin-left styles

Add an additional anchor link element (.x3) in 2nd row

Code Snippet Demonstration:

(function iife() {
      "use strict";
      document.querySelector(".myLink").classList.add("hide");

      function playButtonClickHandler() {
        document.querySelector(".myLink").classList.remove("hide");
        var button = document.querySelector(".playButton");
        var player = document.querySelector("#player");
        document.querySelector(".playButton .initial").style.display = "none";
        player.volume = 1.0;
        if (player.paused) {
          button.classList.add("playing");
          document.querySelector(".playButton .play").style.display = "none";
          document.querySelector(".playButton .pause").style.display = "inline-block";
          player.play();
        } else {
          document.querySelector(".playButton .play").style.display = "inline-block";
          document.querySelector(".playButton .pause").style.display = "none";
          player.pause();
        }
      }
      var playButton = document.querySelector(".playButton");
      playButton.addEventListener("click", playButtonClickHandler);
    }());```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrap {
    position: relative;
    display: table;
    background:red;
  }

  .initial {
    width: 260px;
    height: 168px;
    cursor: pointer;
    background-image: linear-gradient( to right, transparent, transparent 83px, #0059dd 83px, #0059dd 86px, transparent 86px, transparent 174px, #0059dd 174px, #0059dd 177px, transparent 177px, transparent 260px), url("https://i.imgur.com/BBYxKcf.jpg");
    border: 3px solid #0059dd;
    font-family: Tahoma;
    font-weight: bold;
    font-size: 30px;
    color: #0059dd;
    cursor: pointer;
    line-height: 100px;
    text-align: center;
  }

  .playButton.playing {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 50px;
    height: 50px;
    cursor: pointer;
    background-color: #000000;
    box-Shadow: inset 0 0 0 3px #0059dd;
    fill: #aaff00;

  }

  .link div {
    margin: 0 0 12px 0;
    font-size: 0; /* Remove whitespace created by inline-block */
  }

.link a:first-child {
    margin-left: 0px;
}

.link a {
    width: 50px;
    height: 50px;
    margin: 0px;
    background: black;
    box-Shadow: inset 0 0 0 3px #0059dd;
    display: inline-block;
    margin-left: 4px;
}

  /*a.x1 {
    margin: 0;
  }

  a.x2 {
    margin-left: 54px;
  }

  a.x3 {
    margin-left: 108px;
  }

  a.x4 {
    margin-left: 162px;
  }

  a.x5 {
    margin-left: 216px;
  }*/

  .hide,.play {
    display: none;
  }

  .link div:last-child {
    margin-bottom: 0;
  }</code>```

Links

      <svg class="pause" style="display: none;margin:5px 7px;" width="36" height="40" viewbox="0 0 60 100">
        <path d="M0 8c0-5 3-8 8-8s9 3 9 8v84c0 5-4 8-9 8s-8-3-8-8V8zm43 0c0-5 3-8 8-8s8 3 8 8v84c0 5-3 8-8 8s-8-3-8-8V8z"></path>
      </svg>

      <svg class="play" style="margin:5px 9px;" width="38" height="40" viewbox="0 0 85 100">
        <path d="M81 44.6c5 3 5 7.8 0 10.8L9 98.7c-5 3-9 .7-9-5V6.3c0-5.7 4-8 9-5l72 43.3z"></path>
      </svg>

    <audio id="player" preload="none">
      <source src="http://hi5.1980s.fm/;" type="audio/mpeg">
      </source>
    </audio>

```

Updated JSFiddle

Body:
How would I remove this negative margin and replace it?

What are the ways in which this can be done?

Click on the image to see the links.

You have to Click on the image to see the links.

https://jsfiddle.net/j8fL15s5/15/

Screenshot

.link a {
        display: block;
        width: 50px;
        height: 50px;
        margin: -50px 0 0;
        background: black;
        box-Shadow: inset 0 0 0 3px #0059dd;
      }

One way is by using:

display: flex;

https://jsfiddle.net/j8fL15s5/18/

Are there any other ways to do this?

Can this be accomplished 'without' the use of flex?

Body:
Adjusted Styles:

.link div {
  margin: 0 0 12px 0;
  font-size: 0; /* Remove whitespace created by inline-block */
}

.link a:first-child {
    margin-left: 0px;
}

.link a {
    width: 50px;
    height: 50px;
    margin: 0px;
    background: black;
    box-Shadow: inset 0 0 0 3px #0059dd;
    display: inline-block;
    margin-left: 4px;
}

Summary:

Reset margin property values and display them as inline-block

Remove individual anchor link margin-left styles

Add an additional anchor link element (.x3) in 2nd row

Code Snippet Demonstration:

(function iife() {
      "use strict";
      document.querySelector(".myLink").classList.add("hide");

      function playButtonClickHandler() {
        document.querySelector(".myLink").classList.remove("hide");
        var button = document.querySelector(".playButton");
        var player = document.querySelector("#player");
        document.querySelector(".playButton .initial").style.display = "none";
        player.volume = 1.0;
        if (player.paused) {
          button.classList.add("playing");
          document.querySelector(".playButton .play").style.display = "none";
          document.querySelector(".playButton .pause").style.display = "inline-block";
          player.play();
        } else {
          document.querySelector(".playButton .play").style.display = "inline-block";
          document.querySelector(".playButton .pause").style.display = "none";
          player.pause();
        }
      }
      var playButton = document.querySelector(".playButton");
      playButton.addEventListener("click", playButtonClickHandler);
    }());

.wrap {
    position: relative;
    display: table;
    background:red;
  }

  .initial {
    width: 260px;
    height: 168px;
    cursor: pointer;
    background-image: linear-gradient( to right, transparent, transparent 83px, #0059dd 83px, #0059dd 86px, transparent 86px, transparent 174px, #0059dd 174px, #0059dd 177px, transparent 177px, transparent 260px), url("https://i.imgur.com/BBYxKcf.jpg");
    border: 3px solid #0059dd;
    font-family: Tahoma;
    font-weight: bold;
    font-size: 30px;
    color: #0059dd;
    cursor: pointer;
    line-height: 100px;
    text-align: center;
  }

  .playButton.playing {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 50px;
    height: 50px;
    cursor: pointer;
    background-color: #000000;
    box-Shadow: inset 0 0 0 3px #0059dd;
    fill: #aaff00;

  }

  .link div {
    margin: 0 0 12px 0;
    font-size: 0; /* Remove whitespace created by inline-block */
  }

.link a:first-child {
    margin-left: 0px;
}

.link a {
    width: 50px;
    height: 50px;
    margin: 0px;
    background: black;
    box-Shadow: inset 0 0 0 3px #0059dd;
    display: inline-block;
    margin-left: 4px;
}

  /*a.x1 {
    margin: 0;
  }

  a.x2 {
    margin-left: 54px;
  }

  a.x3 {
    margin-left: 108px;
  }

  a.x4 {
    margin-left: 162px;
  }

  a.x5 {
    margin-left: 216px;
  }*/

  .hide,.play {
    display: none;
  }

  .link div:last-child {
    margin-bottom: 0;
  }

<div class="wrap">
    <div class="myLink">
      <div class="link">
        <div>
          <a class="x1" href="#" target="_blank"></a>
          <a class="x2" href="#" target="_blank"></a>
          <a class="x3" href="#" target="_blank"></a>
          <a class="x4" href="#" target="_blank"></a>
          <a class="x5" href="#" target="_blank"></a>
        </div>

        <div>
          <a class="x1" href="#" target="_blank"></a>
          <a class="x2" href="#" target="_blank"></a>
          <a class="x3" href="#" target="_blank"></a>
          <a class="x4" href="#" target="_blank"></a>
          <a class="x5" href="#" target="_blank"></a>
        </div>

        <div>
          <a class="x1" href="#" target="_blank"></a>
          <a class="x2" href="#" target="_blank"></a>
          <a class="x3" href="#" target="_blank"></a>
          <a class="x4" href="#" target="_blank"></a>
          <a class="x5" href="#" target="_blank"></a>
        </div>
      </div>
    </div>

    <div class="playButton">
      <div class="initial">Links</div>
      <svg class="pause" style="display: none;margin:5px 7px;" width="36" height="40" viewbox="0 0 60 100">
        <path d="M0 8c0-5 3-8 8-8s9 3 9 8v84c0 5-4 8-9 8s-8-3-8-8V8zm43 0c0-5 3-8 8-8s8 3 8 8v84c0 5-3 8-8 8s-8-3-8-8V8z"></path>
      </svg>

      <svg class="play" style="margin:5px 9px;" width="38" height="40" viewbox="0 0 85 100">
        <path d="M81 44.6c5 3 5 7.8 0 10.8L9 98.7c-5 3-9 .7-9-5V6.3c0-5.7 4-8 9-5l72 43.3z"></path>
      </svg>
    </div>

    <audio id="player" preload="none">
      <source src="http://hi5.1980s.fm/;" type="audio/mpeg">
      </source>
    </audio>
  </div>

Updated JSFiddle


问:
How to inject CDI dependency into JAX-RS ClientRequestFilter provider
I have a @Provider that implements a ClientRequestFilter. The provider itself is not discovered at all. When I register it manually, then it is discovered.

```<code>ClientBuilder.newBuilder().register(Somefilter.class);
</code>```

This way however, CDI doesn't inject dependencies into Somefilter.

AS: WildFly 10

JAX-RS : Resteasy (built in WildFly)

The code of my Somefilter class looks like this.

```<code>@Provider
public class Somefilter implements ClientRequestFilter {

@Inject
private AccountService accountService;

@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    System.out.println(accountService);

}
</code>```

}

The application also has a server part, configured with @Application annotation, using some classes implementing ContainerRequestFilter. These are discovered by Resteasy and even CDI injection works.

So the question is, how can I make client-api related providers inject CDI dependencies.

答:
Make sure you are importing the correct package javax.enterprise.context for declaring the @RequestScoped scope for your service class:

```<code>import javax.enterprise.context.RequestScoped;

@Named
@RequestScoped
public class AccountService {

}
</code>```

I was having this problem and found out I was erroneously using the Faces (JSF) package instead which was javax.faces.bean.RequestScoped.

Body:
I have a @Provider that implements a ClientRequestFilter. The provider itself is not discovered at all. When I register it manually, then it is discovered.

ClientBuilder.newBuilder().register(Somefilter.class);

This way however, CDI doesn't inject dependencies into Somefilter.

AS: WildFly 10

JAX-RS : Resteasy (built in WildFly)

The code of my Somefilter class looks like this.

@Provider
public class Somefilter implements ClientRequestFilter {

@Inject
private AccountService accountService;

@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    System.out.println(accountService);

}

}

The application also has a server part, configured with @Application annotation, using some classes implementing ContainerRequestFilter. These are discovered by Resteasy and even CDI injection works.

So the question is, how can I make client-api related providers inject CDI dependencies.

Body:
Make sure you are importing the correct package javax.enterprise.context for declaring the @RequestScoped scope for your service class:

import javax.enterprise.context.RequestScoped;

@Named
@RequestScoped
public class AccountService {

}

I was having this problem and found out I was erroneously using the Faces (JSF) package instead which was javax.faces.bean.RequestScoped.


问:
How to send google script sender email to no-reply@entreprise.com?
I send 200 emails to a community of students via a google-spreadsheet attached google script.

My mailing call is as follow :

```<code>MailApp.sendEmail(
  "toto@gmail.com",             // targetEmail
  "HELLO FROM KING OF NIGERIA", // emailTitle
  "",                           // something
  // emailContentHTML
  { htmlBody:  "<b>Hello John</b><br><p>I'am king of Nigeria.<br>Got gold everywhere.<br>Need your help I'am in danger.<br>Want to share with you.<br>Could you send me 50$<br>Sinceraly, your friend.</p>"}
);
</code>```

The script being run by my google account john.Doe@entreprise.com, the 200+ participants see the email as coming from me (john.Doe@entreprise.com). I understand this is fair game to limit spamming and co, but my company has a gmail entreprise.com domain name and I would like a solution so to not get dozens of "Thanks you" alerts in the following days. For sure, I do NOT want them to keep me in their following discussion.

So I look for something such as create a no-reply@entreprise.com account, and then a js thing so the script sign email with this no-reply@entreprise.com email.

Also, is there a way to programatically sign the google-script mailing from an other account of my company (no-reply@entreprise.com) ?

Note : google-script-manual

答:
Since the script is being run under your Gmail account, the easiest way to do this is to add noReply: true to the message object. This will result in the email being sent from a generic noreply@enterprise.com email. The noreply email account does not need to be created for this to work.

Note that this does not work for personal Gmail accounts.

The documentation for this is at this link as noted in Edward Wall's answer.

MailApp.sendEmail(
  "toto@gmail.com",             // targetEmail
  "HELLO FROM KING OF NIGERIA", // emailTitle
  "",                           // something
  // emailContentHTML
  { htmlBody:  "Hello John

I'am king of Nigeria.
Got gold everywhere.
Need your help I'am in danger.
Want to share with you.
Could you send me 50$
Sinceraly, your friend.
",
  //send from generic noReply@enterprise.com address
  noReply: true}
);```

Body:
I send 200 emails to a community of students via a google-spreadsheet attached google script.

My mailing call is as follow :

MailApp.sendEmail(
  "toto@gmail.com",             // targetEmail
  "HELLO FROM KING OF NIGERIA", // emailTitle
  "",                           // something
  // emailContentHTML
  { htmlBody:  "Hello John

I'am king of Nigeria.
Got gold everywhere.
Need your help I'am in danger.
Want to share with you.
Could you send me 50$
Sinceraly, your friend.
"}
);

The script being run by my google account john.Doe@entreprise.com, the 200+ participants see the email as coming from me (john.Doe@entreprise.com). I understand this is fair game to limit spamming and co, but my company has a gmail entreprise.com domain name and I would like a solution so to not get dozens of "Thanks you" alerts in the following days. For sure, I do NOT want them to keep me in their following discussion.

So I look for something such as create a no-reply@entreprise.com account, and then a js thing so the script sign email with this no-reply@entreprise.com email.

Also, is there a way to programatically sign the google-script mailing from an other account of my company (no-reply@entreprise.com) ?

Note : google-script-manual

Body:
Since the script is being run under your Gmail account, the easiest way to do this is to add noReply: true to the message object. This will result in the email being sent from a generic noreply@enterprise.com email. The noreply email account does not need to be created for this to work.

Note that this does not work for personal Gmail accounts.

The documentation for this is at this link as noted in Edward Wall's answer.

MailApp.sendEmail(
  "toto@gmail.com",             // targetEmail
  "HELLO FROM KING OF NIGERIA", // emailTitle
  "",                           // something
  // emailContentHTML
  { htmlBody:  "<b>Hello John</b><br><p>I'am king of Nigeria.<br>Got gold everywhere.<br>Need your help I'am in danger.<br>Want to share with you.<br>Could you send me 50$<br>Sinceraly, your friend.</p>",
  //send from generic noReply@enterprise.com address
  noReply: true}
);


问:
Sass watch will not compile - tried everything
I spent all day trying to track this down yesterday. I upgraded to High Sierra and Sass watched stopped compiling. It appears to be listening getting here:

Change detected to: test.scss

But never compiles when I update a scss file. It used to work fine. Here are some of the things I have tried.

Uninstall Sass / Reinstall

Try older version of Sass

Try older version of Listen

Update Xcode

Delete sass-cache

Try to watch simple scss file

Really stumped here and need to get some changes ready - Any ideas or workarounds? Any help greatly appreciated.

答: I got this working. I think I was just a little bleary-eyed. I did all of these things - learned a bit about gems along the way. Uninstalled Sass and Sass-listen, reinstalled, rebooted and back in biz.</p>


问:
Wordpress redirecting https to http with a 301 redirect from unknown source
I am trying to redirect all http traffic to https in wordpress. But I don't know why the website is making exactly the inverse process just in front-end. I haven't modified .htaccess file and if I try to install a plugin or to insert any new line to redirect the traffic the website goes in a infinite loop. As you can see here: https://gyazo.com/24c54632e151194a2ad58ce2fb8dbf4b https://gyazo.com/2e64095e3e3895e53aa3f82b77f12003

Do someone know how to find the source of this redirect ?

If you are curious that's the website address: https://gazzettadegliesports.it

UPDATE: .htaccess file

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
</IfModule>

# END WordPress
</code>```

答:
My next instinct was to check if your SSL certificate was active and indeed it is: https://www.sslshopper.com/ssl-checker.html#hostname=gazzettadegliesports.it

Next check was Sucuri, and as suspected, you have some malware:
https://sitecheck.sucuri.net/results/gazzettadegliesports.it

Best to clean up that first. Then, I suggest Really Simple SSL plugin for WordPress.

Body:
I am trying to redirect all http traffic to https in wordpress. But I don't know why the website is making exactly the inverse process just in front-end. I haven't modified .htaccess file and if I try to install a plugin or to insert any new line to redirect the traffic the website goes in a infinite loop. As you can see here: https://gyazo.com/24c54632e151194a2ad58ce2fb8dbf4b https://gyazo.com/2e64095e3e3895e53aa3f82b77f12003

Do someone know how to find the source of this redirect ?

If you are curious that's the website address: https://gazzettadegliesports.it

UPDATE: .htaccess file

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
</IfModule>

# END WordPress


问:
"Cannot insert explicit value for identity column in table 'Movies' when IDENTITY_INSERT is set to OFF."
I'm using code first with entity framework. I have been getting the error below and can't figure out how to fix it:

"Cannot insert explicit value for identity column in table 'Movies' when IDENTITY_INSERT is set to OFF."

I've read that setting Sql("SET IDENTITY_INSERT Movies ON") and OFF around my migration query should fix this however I did not run any queries on the Movies table.

Movies table:

```<code>{
    public class Movies
    {
        public byte Id { get; set; }

        [Display (Name = "Movie Name")]
        public string MovieName { get; set; }

        public Genre Genre { get; set; }

        [Required]
        public byte GenreId { get; set; }

        [Display (Name = "Release Date")]
        public DateTime ReleaseDate { get; set; }

        public DateTime DateAdded { get; set; }

        [Display (Name = "Numbers in Stock")]
        public int NumberInStock { get; set; }
    }
}
</code>```

My Movies controller:

```<code>public ActionResult Save(Movies movies) {
        if (movies.Id == 0)
        {
            _context.Movies.Add(movies);
        }
        else {
            var moviesInDb = _context.Movies.Single(c => c.Id == movies.Id);
            moviesInDb.MovieName = movies.MovieName;
            moviesInDb.ReleaseDate = movies.ReleaseDate;
            moviesInDb.GenreId = movies.GenreId;
            moviesInDb.NumberInStock = movies.NumberInStock;
        }

        _context.SaveChanges();

        return RedirectToAction("Index, Movies");
    }
</code>```

I am getting the error on _context.SaveChanges();

I do have queries for my Genre table which is as below

```<code>public partial class PopulateGenreTable : DbMigration
{
    public override void Up()
    {
        Sql("INSERT INTO Genres (Id, Name) VALUES (1, 'Action')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (2, 'Thriller')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (3, 'Family')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (4, 'Romance')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (5, 'Comedy')");
    }

    public override void Down()
    {
    }
}
</code>```

That's the only place I've seeded the dabase

How do I fix this? Please explain clearly as I am an absolute beginner. Thanks

答:
You could easily avoid this error by not specifying the Id, when you insert a record to the Genres table. As it seems Id is an IDENTITY COLUMN. Hence you don't have to specify a value when you insert there a record. The database would generate always the correct Id value based on the IDENTITY you have defined. Usually we have Columns of type INT and IDENTITY(1,1). That means that the first row that would be inserted would have as an Id the value of 1. The second row the value of 2 and so on and so forth.

For further info please have a look here.

Regarding the error message you get about to IDENTITY_INSERT..., the command SET IDENTITY_INSERT can be used when we want to insert one (or more) explicit value(s) to a column with an IDENTITY. A detailed explanation on how to use this command you can find here.

Body:
I'm using code first with entity framework. I have been getting the error below and can't figure out how to fix it:

"Cannot insert explicit value for identity column in table 'Movies' when IDENTITY_INSERT is set to OFF."

I've read that setting Sql("SET IDENTITY_INSERT Movies ON") and OFF around my migration query should fix this however I did not run any queries on the Movies table.

Movies table:

{
    public class Movies
    {
        public byte Id { get; set; }

        [Display (Name = "Movie Name")]
        public string MovieName { get; set; }

        public Genre Genre { get; set; }

        [Required]
        public byte GenreId { get; set; }

        [Display (Name = "Release Date")]
        public DateTime ReleaseDate { get; set; }

        public DateTime DateAdded { get; set; }

        [Display (Name = "Numbers in Stock")]
        public int NumberInStock { get; set; }
    }
}

My Movies controller:

public ActionResult Save(Movies movies) {
        if (movies.Id == 0)
        {
            _context.Movies.Add(movies);
        }
        else {
            var moviesInDb = _context.Movies.Single(c => c.Id == movies.Id);
            moviesInDb.MovieName = movies.MovieName;
            moviesInDb.ReleaseDate = movies.ReleaseDate;
            moviesInDb.GenreId = movies.GenreId;
            moviesInDb.NumberInStock = movies.NumberInStock;
        }

        _context.SaveChanges();

        return RedirectToAction("Index, Movies");
    }

I am getting the error on _context.SaveChanges();

I do have queries for my Genre table which is as below

public partial class PopulateGenreTable : DbMigration
{
    public override void Up()
    {
        Sql("INSERT INTO Genres (Id, Name) VALUES (1, 'Action')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (2, 'Thriller')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (3, 'Family')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (4, 'Romance')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (5, 'Comedy')");
    }

    public override void Down()
    {
    }
}

That's the only place I've seeded the dabase

How do I fix this? Please explain clearly as I am an absolute beginner. Thanks


问:
What exactly is "broken" with Microsoft Visual C++'s two-phase template instantiation?
Reading questions, comments and answers on SO, I hear all the time that MSVC doesn't implement two-phase template lookup / instantiation correctly.

From what I understand so far, MSVC++ is only doing a basic syntax check on template classes and functions and doesn't check that names used in the template have atleast been declared or something along those lines.

Is this correct? What am I missing?

答: Now that MSVC has most of two-phase name lookup implemented, I'm hoping this blog post answers this question completely: Two-phase name lookup comes to MSVC (VC++ blog)</p>


问:
How do I change the version of Python being used in my RMakrdown code chunks?
I apologise first as I am very new to much of this.

I am working in Markdown and I want to use the python package tweepy. Now this requires a more updated version of Python than my current one:

```<code>import sys
print(sys.version)
</code>```

which gives me

```<code>2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)]
</code>```

Because I get

```<code>ImportError: No module named tweepy
</code>```

when I try to import it.

So I have downloaded Python version 2.7.14 to my laptop, and I find it as a folder in Applications ( I am on a Mac using OS X 10.11.6 ).

This has updated the Python used when I open terminal, but the code chunks still use the old version. I am unsure of how to save this version of Python to a different location. I feel like what I need to do is change the engine.path parameter in the code chunk, but I am not sure how I move this version of Python and refer to it in the engine.path.

Any help would be greatly appreciated!!

Best wishes

B

答:
This is a common problem when using knitr and RMarkdown. You need to set the engine.path variable in your chunk. If you are using Anaconda, it might look like this...

```<code>```{python, engine.path="~/anaconda3/bin/python"}
your code here...
```
</code>```

If you open python in your terminal and run...

```<code>import sys
print(sys.executable)
</code>```

It should point you to the location of the python executable you should pass as an argument to engine.path in RMarkdown/knitr.

Body:
I apologise first as I am very new to much of this.

I am working in Markdown and I want to use the python package tweepy. Now this requires a more updated version of Python than my current one:

import sys
print(sys.version)

which gives me

2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)]

Because I get

ImportError: No module named tweepy

when I try to import it.

So I have downloaded Python version 2.7.14 to my laptop, and I find it as a folder in Applications ( I am on a Mac using OS X 10.11.6 ).

This has updated the Python used when I open terminal, but the code chunks still use the old version. I am unsure of how to save this version of Python to a different location. I feel like what I need to do is change the engine.path parameter in the code chunk, but I am not sure how I move this version of Python and refer to it in the engine.path.

Any help would be greatly appreciated!!

Best wishes

B

Body:
This is a common problem when using knitr and RMarkdown. You need to set the engine.path variable in your chunk. If you are using Anaconda, it might look like this...

```{python, engine.path="~/anaconda3/bin/python"}
your code here...
```

If you open python in your terminal and run...

import sys
print(sys.executable)

It should point you to the location of the python executable you should pass as an argument to engine.path in RMarkdown/knitr.