问:
save selected checkbox in gridview row c# asp
i want to save each row which checked using sqldatasource, but i got error The variable name '@Approved_By' has already been declared. Variable names must be unique within a query batch or stored procedure.

am i wrong in looping?

```<code>int i = 0;
foreach (GridViewRow row in GridView1.Rows)
{
    if (row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chkRow = (row.Cells[2].FindControl("CheckBox1") as CheckBox);
        bool chk = chkRow.Checked;

        if (chk = chkRow.Checked)
        {
            SqlDataSource3.UpdateParameters.Add("Approved_By", Session["username"].ToString());
            SqlDataSource3.UpdateParameters.Add("Kode_Personel", GridView1.Rows[row.RowIndex].Cells[0].Text);
            SqlDataSource3.Update();
        }
    }
    i++;
}
</code>```

答:
The variable name has already been declared message is pretty obvious: you're adding same parameter names in foreach loop multiple times for every iteration.

Add SqlDataSource3.UpdateParameters.Clear(); method either before adding UpdateParameters or after executing Update() method to clear parameter collection before next iteration starts:

```<code>int i = 0;
foreach (GridViewRow row in GridView1.Rows)
{
    if (row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chkRow = (row.Cells[2].FindControl("CheckBox1") as CheckBox);
        bool chk = chkRow.Checked;

        if (chk = chkRow.Checked)
        {
            // add this line so that UpdateParameter collection cleared before adding new parameters
            SqlDataSource3.UpdateParameters.Clear();

            SqlDataSource3.UpdateParameters.Add("Approved_By", Session["username"].ToString());
            SqlDataSource3.UpdateParameters.Add("Kode_Personel", GridView1.Rows[row.RowIndex].Cells[0].Text);

            SqlDataSource3.Update();

            // or you can clear UpdateParameters collection here
        }

    }
    i++;
}
</code>```

Body:
i want to save each row which checked using sqldatasource, but i got error The variable name '@Approved_By' has already been declared. Variable names must be unique within a query batch or stored procedure.

am i wrong in looping?

int i = 0;
foreach (GridViewRow row in GridView1.Rows)
{
    if (row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chkRow = (row.Cells[2].FindControl("CheckBox1") as CheckBox);
        bool chk = chkRow.Checked;

        if (chk = chkRow.Checked)
        {
            SqlDataSource3.UpdateParameters.Add("Approved_By", Session["username"].ToString());
            SqlDataSource3.UpdateParameters.Add("Kode_Personel", GridView1.Rows[row.RowIndex].Cells[0].Text);
            SqlDataSource3.Update();
        }
    }
    i++;
}

Body:
The variable name has already been declared message is pretty obvious: you're adding same parameter names in foreach loop multiple times for every iteration.

Add SqlDataSource3.UpdateParameters.Clear(); method either before adding UpdateParameters or after executing Update() method to clear parameter collection before next iteration starts:

int i = 0;
foreach (GridViewRow row in GridView1.Rows)
{
    if (row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chkRow = (row.Cells[2].FindControl("CheckBox1") as CheckBox);
        bool chk = chkRow.Checked;

        if (chk = chkRow.Checked)
        {
            // add this line so that UpdateParameter collection cleared before adding new parameters
            SqlDataSource3.UpdateParameters.Clear();

            SqlDataSource3.UpdateParameters.Add("Approved_By", Session["username"].ToString());
            SqlDataSource3.UpdateParameters.Add("Kode_Personel", GridView1.Rows[row.RowIndex].Cells[0].Text);

            SqlDataSource3.Update();

            // or you can clear UpdateParameters collection here
        }

    }
    i++;
}


来源: stackexchange

问:
computer on PCIe card
Does anyone know a COM which is put on a PCIe card, which has some flash memory, some RAM, JTAG support (or some kind of debugging support), some input ports like USB, perhaps support some output like via VGA or LVDS, just like this board: http://www.knjn.com/FPGA-PCIe.html but not for FPGA development, but for microprocessors, preferably x86.

Something similar has been done in the past, but the link is dead, and it should have enough documentation and be hacker-friendly (and cheap, not more than 100-150 USD).

I will be writing the driver for the host system (linux), for inter-system communication, but the PCIe board itself should be pretty stand-alone (beside the operating system for the "guest OS" on the PCIe card which I will also have to write).

Thanks

答:
You're not going to find anything of that sort for anything close to that price range.  The "similar" board you link to (which had a Cell processor) is probably an $8000 board -- at least, that's what the other similar Cell boards I knew of sold for.  And Cell was expensive, sure, but it's not like a Cell processor is $7850 more than an x86 processor.

The closest thing to what you're looking for in that price range are things like evaluation boards that you can buy from chip manufacturers (e.g., this ARM board, which retails for $70), and those aren't very close.  For reference, that example is about the cheapest board you can get with a 32-bit processor and an ethernet port -- and it's that cheap in large part because TI is using it to promote their ARM processor that it contains.  There aren't any chipmakers for x86 other than Intel and AMD, so you won't get that sort of subsidy on the board, to begin with.  And then you're asking for lots more off-chip extras on the board -- USB (ok, probably similar in cost to Ethernet), RAM, video output.  (Not to mention that the TI ARM processor is a system-on-chip that contains flash controller, flash, and lots of other basic things in the chip that you don't get in an x86 chip.)  Oh, and you want a PCIe device-side interface, too.

And all of this, in a package that is definitely not going to sell in high volume.  (The Cell and FPGA boards have a market as fast specialized coprocessor boards; an x86 board is of no use for that because you can just put the extra x86 on the motherboard instead.)  You'd be quite lucky to get something like that under $1000, much less near $100.

With that said, I have seen PCI-bus 486 computers of roughly this ilk (EGA graphics, of course) at HSC Surplus in Santa Clara, about three years ago though they don't have any now.  They looked like they had been built when a 486 was a nice processor, and were selling for about $30.  And, on reflection, I'm not sure they were PCI; I think they might have been ISA.  Your best bet would probably be tracking down something like that.

ContentLicense: CC BY-SA 2.5

Title: computer on PCIe card


问:
Find partial keywords in python list
```<code>x = 'a'
list = ['ab','cd','a']
if x in list:
    print(list.index(x))
</code>```

Here I try to find all the values in list which contains 'a'. But with the 'in' method I can only find the value which is 'a' rather than contain 'a',like 'ab'. Are there any efficient ways to do so? Thanks

答:
You can use a simple for loop for this. Loop through the list and for each element in the list check whether your x is a substring of that element with in. If it is true display that element.

You can do it in python like this..

```<code>x = 'a'
list = ['ab','cd','a']

for element in list:
    if x in element:
        print(element)

Output
ab
a
</code>```

ContentLicense: CC BY-SA 3.0

Title: Find partial keywords in python list

Body:
x = 'a'
list = ['ab','cd','a']
if x in list:
    print(list.index(x))

Here I try to find all the values in list which contains 'a'. But with the 'in' method I can only find the value which is 'a' rather than contain 'a',like 'ab'. Are there any efficient ways to do so? Thanks

Body:
You can use a simple for loop for this. Loop through the list and for each element in the list check whether your x is a substring of that element with in. If it is true display that element.

You can do it in python like this..

x = 'a'
list = ['ab','cd','a']

for element in list:
    if x in element:
        print(element)

Output
ab
a


问:
Overwriting nested styles in React Bootstrap using Styled-Components
I'm using styled-components with React Bootstrap. We want a tab (Tab 3 in this example) to be colored based on a status. It works well when the tab is not active, but when it's active, the Bootstrap style overwrites the style.

I've identified the style that's overwriting my color in the console. When I use console to turn off the style, I see my intended tab color.

I'm just not sure how to target this style using style-components. I've tried experimenting with different ideas from the official doc but haven't been able to get it working.

My styled component:

```<code> export const TabNavItem = styled(NavItem)`
      background-color: ${props => (props.colorize ? 'orange' : 'white')};
      }
    `;
</code>```

Usage:

```<code>  render() {
    const { children, active, colorize } = this.props;
    return (
      <TabNavItem onClick={this.handleChangeLocation} active={active} colorize={colorize}>
        {children}
      </TabNavItem>
    );
  }
</code>```

Color works fine when tab is not active:

When tab is active, color is covered by Bootstrap styles:

This is the style I need to overwrite (background-color):

答:
I typically wouldn't apply styled-components directly to each react-bootstrap components, but instead create a single one to wrap the entire component scope and rely more on CSS classes to get things done.

For example in your case, I would do something like:

const StyledWrap = styled.div`
  & .nav-tabs > .active > li {
    background: white;
  }

  & .nav-tabs > .active.colorize > li {
    background: orange;
  }
`
const MyCustomNavbar = (props) => {
  return (

  )
}
```

<p>In my opinion, its a cleaner pattern that keeps your component specific CSS properly scoped, concentrated and comprehensive.</p>

<p>Generally, I find that applying <code>styled-components</code> only once per component scope keeps things simple and manageable. When you apply it in multiple places you end up doing a lot of prefixing and end up with code that looks like this: </p>

```

    </StyledNavDropdown>
  </StyledNav>
</StyledNavbar>
```

This is an extreme example, but you get the idea.

Body:
I'm using styled-components with React Bootstrap. We want a tab (Tab 3 in this example) to be colored based on a status. It works well when the tab is not active, but when it's active, the Bootstrap style overwrites the style.

I've identified the style that's overwriting my color in the console. When I use console to turn off the style, I see my intended tab color.

I'm just not sure how to target this style using style-components. I've tried experimenting with different ideas from the official doc but haven't been able to get it working.

My styled component:

 export const TabNavItem = styled(NavItem)`
      background-color: ${props => (props.colorize ? 'orange' : 'white')};
      }
    `;

Usage:

  render() {
    const { children, active, colorize } = this.props;
    return (
      <TabNavItem onClick={this.handleChangeLocation} active={active} colorize={colorize}>
        {children}
      </TabNavItem>
    );
  }

Color works fine when tab is not active:

When tab is active, color is covered by Bootstrap styles:

This is the style I need to overwrite (background-color):

Body:
I typically wouldn't apply styled-components directly to each react-bootstrap components, but instead create a single one to wrap the entire component scope and rely more on CSS classes to get things done.

For example in your case, I would do something like:

const StyledWrap = styled.div`
  & .nav-tabs > .active > li {
    background: white;
  }

  & .nav-tabs > .active.colorize > li {
    background: orange;
  }
`
const MyCustomNavbar = (props) => {
  return (
    <StyledWrap>
      /* ... */
        <NavItem active={true} />
        <NavItem className="colorize"/>
        <NavItem active={true} className="colorize" />
      /* ... */
    </StyledWrap>
  )
}

In my opinion, its a cleaner pattern that keeps your component specific CSS properly scoped, concentrated and comprehensive.

Generally, I find that applying styled-components only once per component scope keeps things simple and manageable. When you apply it in multiple places you end up doing a lot of prefixing and end up with code that looks like this:

<StyledNavbar>
  <StyledNav>
    <StyledNavItem active={true} />
    <StyledNavDropdown>
      <StyledMenuItem eventKey={1.1}>Action 1</StyledMenuItem>
      <StyledMenuItem eventKey={1.2}>Action 2</StyledMenuItem>
    </StyledNavDropdown>
  </StyledNav>
</StyledNavbar>

This is an extreme example, but you get the idea.


问:
Match after space or everything without space
I would like to have a regex to match string after space or without space.
here's example of input:

```<code>Singapore NET-AP-1

Thailand Bangkok RT-SW-2b

WIN-OS-0
</code>```

Output should be like this:

```<code>NET-AP-1

RT-SW-2b

WIN-OS-0
</code>```

I tried .*\s(.*) and this is only good for first 2 but not the last without space.

答:
(\w+-)+\w+

if your input line always like

NET-AP-1 then

above regex will help.

Body:
I would like to have a regex to match string after space or without space.
here's example of input:

Singapore NET-AP-1

Thailand Bangkok RT-SW-2b

WIN-OS-0

Output should be like this:

NET-AP-1

RT-SW-2b

WIN-OS-0

I tried .*\s(.*) and this is only good for first 2 but not the last without space.


问:
Python - reordering items in list by moving some items to the front while keeping the rest in the same order
I am trying to reorder items in a list in a way illustrated by the following example:

Suppose the list before reordering is:

```<code>list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code>```

I want to implement a method called reorder_list(list, custom_order) such that:

```<code>list1 = reorder_list(list1, [3, 6, 12, 9])
print(list1)

Out: [3, 6, 9, 1, 2, 4, 5, 7, 8, 10]
</code>```

Explanation: [3, 6, 12, 9] is a custom order I am specifying. 12 is not in  list1 so it will be ignored. 3,6,9 are in list1, so they get moved to the front of the list and their order is the same as in [3, 6, 12, 9]. The remaining items in list1 are after 3,6,9 and in the original order.

Is there is an easier way (and a Pythonic way) than implementing the C-like loop code. For my purpose I care more about code simplicity than performance.

答:
A couple of list comprehensions should be reasonably performant for this:

Code:

```<code>def reorder_list(list_to_reorder, custom_order):
    new_list = [x for x in custom_order if x in set(list_to_reorder)]
    new_list.extend(x for x in list_to_reorder if x not in set(custom_order))
    return new_list
</code>```

Test Code:

```<code>list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(reorder_list(list1, [9, 6, 3, 12]))
</code>```

Results:

```<code>[9, 6, 3, 1, 2, 4, 5, 7, 8, 10]
</code>```

Body:
I am trying to reorder items in a list in a way illustrated by the following example:

Suppose the list before reordering is:

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I want to implement a method called reorder_list(list, custom_order) such that:

list1 = reorder_list(list1, [3, 6, 12, 9])
print(list1)

Out: [3, 6, 9, 1, 2, 4, 5, 7, 8, 10]

Explanation: [3, 6, 12, 9] is a custom order I am specifying. 12 is not in  list1 so it will be ignored. 3,6,9 are in list1, so they get moved to the front of the list and their order is the same as in [3, 6, 12, 9]. The remaining items in list1 are after 3,6,9 and in the original order.

Is there is an easier way (and a Pythonic way) than implementing the C-like loop code. For my purpose I care more about code simplicity than performance.

Body:
A couple of list comprehensions should be reasonably performant for this:

Code:

def reorder_list(list_to_reorder, custom_order):
    new_list = [x for x in custom_order if x in set(list_to_reorder)]
    new_list.extend(x for x in list_to_reorder if x not in set(custom_order))
    return new_list

Test Code:

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(reorder_list(list1, [9, 6, 3, 12]))

Results:

[9, 6, 3, 1, 2, 4, 5, 7, 8, 10]


问:
mailto not opening email form
I want to open email that fills the following details. I am using chrome. But the email is not opening. I have to press send only and then the email should be sent. Is there any way like this.
Code

```<code>   <a href="mailto:coolfire525@gmail.com?cc=coolfire525%40gmail.com&bcc=coolfire525%40gmail.com&body=Dear%20Global%20Supply%20Chain%20Group%0A%20%0AI%20would%20like%20you%20to%20send%20me%20your%20report%20titled%20A%20FIDUCIARY%20BOARD%20REPORT%20-%20%20THE%20FUTURE%20OF%20BUSINESS%20IN%20THE%20AGE%20OF%20B2B%20NETWORKS%2C%20and%20attach%20an%20invoice%20for%20the%20report.%20I%20understand%20that%20I%20can%20ask%20for%20a%20refund%20and%20return%20the%20report%20in%20original%20condition%20within%2030%20days%2C%20if%20I%20do%20not%20like%20the%20content.">Mail Now</a>
</code>```

答:
It about how your default mail application setup on your computer...

it's worked for me.

Also see this link for more info: https://developers.google.com/web/updates/2012/02/Getting-Gmail-to-handle-all-mailto-links-with-registerProtocolHandler

Title: mailto not opening email form

Body:
I want to open email that fills the following details. I am using chrome. But the email is not opening. I have to press send only and then the email should be sent. Is there any way like this.
Code

   <a href="mailto:coolfire525@gmail.com?cc=coolfire525%40gmail.com&bcc=coolfire525%40gmail.com&body=Dear%20Global%20Supply%20Chain%20Group%0A%20%0AI%20would%20like%20you%20to%20send%20me%20your%20report%20titled%20A%20FIDUCIARY%20BOARD%20REPORT%20-%20%20THE%20FUTURE%20OF%20BUSINESS%20IN%20THE%20AGE%20OF%20B2B%20NETWORKS%2C%20and%20attach%20an%20invoice%20for%20the%20report.%20I%20understand%20that%20I%20can%20ask%20for%20a%20refund%20and%20return%20the%20report%20in%20original%20condition%20within%2030%20days%2C%20if%20I%20do%20not%20like%20the%20content.">Mail Now


问:
How can i locate the Publish link of "orthoacapulco_30cm_cut ? Selenium webdriver using Java
Publish link

this is the HTML code

```<code><tbody>
  <tr id="id71" class="even">
  <!-- The select row checkbox -->
  <!-- This is a repeater, will generate one td for each property -->
  <td>
    <span></span>
  </td>
  <td>
    <span>orthoacapulco_30cm_cut</span>
  </td>
  <td>
    <span>
      <a id="id64" href="javascript:;"><span>Publish</span></a>
    </span>
  </td>
  </tr>
 </tbody>
</code>```

I tried everything. By XPath, CSS selector, by partialLinkName. I can´t use By.ID because never is the same id, and there may be more elements in the table.

答:
if there is single link then you can use simply like this

```<code>driver.findElement(By.xpath(“//span[contains(text(),'Publish')]”)).click();
</code>```

It is answer as per your Image, if there are any thing change or there are multiple elements then let me know

Body:
Publish link

this is the HTML code

    orthoacapulco_30cm_cut

      Publish

I tried everything. By XPath, CSS selector, by partialLinkName. I can´t use By.ID because never is the same id, and there may be more elements in the table.

Body:
if there is single link then you can use simply like this

driver.findElement(By.xpath(“//span[contains(text(),'Publish')]”)).click();

It is answer as per your Image, if there are any thing change or there are multiple elements then let me know


问:
Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues
I have found plenty of information out there about this error: 'ERROR: Could not load file or assembly '*.dll' or one of its dependencies. Access is denied.’
But i haven't found answer specific to my scenario.
My site is deploy on 6 different production servers, only on one server i am facing this issue. The issue is random, but after it happens once, it continues until the site is recompile by done a small modification in web.config file(i know trick, after modification in web.config recompile the web application) and site on that server start working.
Yesterday, issue was reproducing after one month period of working.
We can't afford this issue on production.

Issue detail:

Server Error in '/' Application.
      ____________________________________
      Could not load file or assembly 'MainCore.DbImpl, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Access is denied.
      Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileLoadException: Could not load file or assembly 'MainCore.DbImpl, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Access is denied.

Source Error:
      An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'MainCore.DbImpl, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' could not be loaded.

WRN: Assembly binding logging is turned OFF.
      To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
      Note: There is some performance penalty associated with assembly bind failure logging.
      To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

Stack Trace:

[FileLoadException: Could not load file or assembly 'MainCore.DbImpl, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Access is denied.]
         ...DbImpl.Event.TTCEventController.GetEventFields(Int32 eventId) +0
         WebSuite.SportChannel.ModelImpl.TTCModelController.AddEventFieldList(XmlElement eventNode, ITTCEventController ctrl, Int32 eventId, PlayerType stupidType) in ...root\SportChannel\ModelImpl\Ttc\TTCModelController.cs:171
      ...ModelImpl.TTCModelController.GetLatestFourTourSchedulesXml() in ...root\SportChannel\ModelImpl\Ttc\TTCModelController.cs:283
         ...WebRoot.UserControls.HeadlinesTab.Page_Load(Object sender, EventArgs e) +491
         System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
         System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +42
         System.EventHandler.Invoke(Object sender, EventArgs e) +0
         System.Web.UI.Control.OnLoad(EventArgs e) +132
         System.Web.UI.Control.LoadRecursive() +66
         System.Web.UI.Control.LoadRecursive() +191
         System.Web.UI.Control.LoadRecursive() +191
         System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2428

      ____________________________________

Version Information: Microsoft .NET Framework Version:2.0.50727.5446; ASP.NET Version:2.0.50727.5420

答: Go to IIS -> Application Pool -> Advance Settings -> Enable 32-bit Applications</p>


问:
How can I get the nearest points each other in a given list in python?
```<code>from math import hypot

p = [ (0,0),(1,1),(2,3),(4,5)]
def dist(p1,p2):
    x1,y1= p1
    x2,y2= p2
    return hypot(x2-x1,y2-y1)

from itertools import combinations

distances = [dist(*pair) for pair in combinations( p,2)]
</code>```

<p>After this step I don't know how to do further.. </p>

答:
```<code>1. distances = [[dist(*pair),pair]  for pair in combinations( p,2)]
2. print sorted(distances)[0][1]
</code>```

code line 1. define the distance list with the pair details. it will be a list of lists.

code line 2. sort the distance list. python default use the first index based sorting. therefor you will get the sorted array with distances. so [0]th element will be the smallest. [1] is its points.

This is not more accurate to do this kind of problem. but
hope this will help you

Body:
from math import hypot

p = [ (0,0),(1,1),(2,3),(4,5)]
def dist(p1,p2):
    x1,y1= p1
    x2,y2= p2
    return hypot(x2-x1,y2-y1)

from itertools import combinations

distances = [dist(*pair) for pair in combinations( p,2)]

After this step I don't know how to do further..

Body:
1. distances = [[dist(*pair),pair]  for pair in combinations( p,2)]
2. print sorted(distances)[0][1]

code line 1. define the distance list with the pair details. it will be a list of lists.

code line 2. sort the distance list. python default use the first index based sorting. therefor you will get the sorted array with distances. so [0]th element will be the smallest. [1] is its points.

This is not more accurate to do this kind of problem. but
hope this will help you


问:
Having a hard time Figuring out a Function in C
I'm having a hard time walking through this function to figure out what exactly it is doing.

```<code>int f2(char *s) {
  char *p;
  for (p = s; *p != ’\0’; p++)
  ;
    for (--p; p >= s && (*p < ’0’ || *p > ’9’); p--)
  ;
      if (p < s)
        return 1;
      while (p >= s && *p >= ’0’ && *p <= ’9’) {
        if (*p == ’9’)
          *p = ’0’;
        else {
          (*p)++;
          return 0;
        }
      p--;
      }
    if (p >= s && *p == ’ ’) {
      *p = ’1’;
      return 0;
    }
  return 1;
}
</code>```

I've tried walking through it with the GDB debugger, but to no avail. I think my biggest issue currently is not being sure what sort of input to test it with.

答:
If you look at the code, you can see it's comparing things against '0', '9', and ' '. So, for "what sort of input to test it with", try feeding it strings of different numbers, sometimes with spaces between them and sometimes not. Maybe also try putting a letter in one.

"120973628029"

"9375906 72010"

"0826"

"40726a591"

and such.

Body:
I'm having a hard time walking through this function to figure out what exactly it is doing.

int f2(char *s) {
  char *p;
  for (p = s; *p != ’\0’; p++)
  ;
    for (--p; p >= s && (*p < ’0’ || *p > ’9’); p--)
  ;
      if (p < s)
        return 1;
      while (p >= s && *p >= ’0’ && *p <= ’9’) {
        if (*p == ’9’)
          *p = ’0’;
        else {
          (*p)++;
          return 0;
        }
      p--;
      }
    if (p >= s && *p == ’ ’) {
      *p = ’1’;
      return 0;
    }
  return 1;
}

I've tried walking through it with the GDB debugger, but to no avail. I think my biggest issue currently is not being sure what sort of input to test it with.


问:
C# listView, how do I add items to columns 2, 3 and 4 etc?
To add items to column 1 in my listView control (Winform) I'm using listView1.Items.Add, this works fine but how do I add items to columns 2 and 3 etc?

答: Use ListViewSubItem - See: MSDN</p>

OwnerDisplayName: Steve

LastEditorDisplayName: buyutec

Body: Use ListViewSubItem - See: MSDN

OwnerDisplayName: Jan Bannister


问:
VND Currency formatting
I have a piece of code as follows:

```<code>var x = 1000;
x = x.toLocaleString('vi', {style : 'currency', currency : 'VND'});
console.log(x);
</code>```

I expected output is:

1.000đ

But the actual output is:

đ1.000

Can anyone help me? thank a lot.

答:
You can use format from other country as below:

var x = 1000;
x = x.toLocaleString('it-IT', {style : 'currency', currency : 'VND'});
console.log(x);```

Title: VND Currency formatting

Body:
I have a piece of code as follows:

var x = 1000;
x = x.toLocaleString('vi', {style : 'currency', currency : 'VND'});
console.log(x);

I expected output is:

1.000đ

But the actual output is:

đ1.000

Can anyone help me? thank a lot.

ContentLicense: CC BY-SA 4.0


问:
Finding correlation between numeric encoded categorical variables?
So I have a data set which has categorical variables. I have encoded each category from 0:x depending on the amount of categories x. I am trying to find the correlation between the variables (both numeric and categorical) to the target variable (which is also categorical, but has been coded to 0 for no and 1 for yes).

I have been able to run this code for the correlation(s) for all the variables (there are about 17) and it does seem to work, but I question whether the correlations are correct. I haven't calculated the correlation with categorical variables in my data set before, just want to ensure that I am going about this the right way:

```<code>print(df['previous'].corr(df['y']))
</code>```

Any help would be great!

答:
The trick to finding correlations within categorical variables is to dummify them. While your target variable is fine (since it i binary), the categorical variables having multiple classes need to be dummified -

```<code>pd.get_dummies(df['Categorical_Column'])
</code>```

Once done, delete one column from the dummified columns and then get the correlations...

Body:
So I have a data set which has categorical variables. I have encoded each category from 0:x depending on the amount of categories x. I am trying to find the correlation between the variables (both numeric and categorical) to the target variable (which is also categorical, but has been coded to 0 for no and 1 for yes).

I have been able to run this code for the correlation(s) for all the variables (there are about 17) and it does seem to work, but I question whether the correlations are correct. I haven't calculated the correlation with categorical variables in my data set before, just want to ensure that I am going about this the right way:

print(df['previous'].corr(df['y']))

Any help would be great!

Body:
The trick to finding correlations within categorical variables is to dummify them. While your target variable is fine (since it i binary), the categorical variables having multiple classes need to be dummified -

pd.get_dummies(df['Categorical_Column'])

Once done, delete one column from the dummified columns and then get the correlations...


问:
How to pull an integer value from NSRange?
I have an NSRange and need to break a string into two substrings on either side of this NSRange.  How do I get an integer value (like the index) out of an NSRange?</p>

答:
I know this question is old, but in Swift 4 (and perhaps earlier) there are new upperBound and lowerBound convenience properties on NSRange:

```<code>print(myRange) // Range: {13, 4}
range.lowerBound // 13
range.upperBound // 17
</code>```

Hopefully that helps someone else.

Body:
I know this question is old, but in Swift 4 (and perhaps earlier) there are new upperBound and lowerBound convenience properties on NSRange:

print(myRange) // Range: {13, 4}
range.lowerBound // 13
range.upperBound // 17

Hopefully that helps someone else.


问:
How to get uid from user on Facebook Page?
I have a question !

I wanna do customize message on my tabs on my Facebook page.
Ex : Hello Steffi or Hello Kevin

How can I do that please ?

fb:user ?

thanks !

答:
```<code>Hello, <fb:name uid="1234567890" captialize="true" firstnameonly="true" useyou="false"><a class="fb_link" href="http://www.facebook.com/profile.php?id=534481565">Kim's</a></fb:name>
</code>```

You'd replace "1234567890" with the user ID of the user you want to display the name of.

The PHP SDK has an example getting the logged in user's ID:

https://github.com/facebook/php-sdk/blob/master/examples/example.php

Body:
Hello, <fb:name uid="1234567890" captialize="true" firstnameonly="true" useyou="false"><a class="fb_link" href="http://www.facebook.com/profile.php?id=534481565">Kim's</a></fb:name>

You'd replace "1234567890" with the user ID of the user you want to display the name of.

The PHP SDK has an example getting the logged in user's ID:

https://github.com/facebook/php-sdk/blob/master/examples/example.php


问:
Podio API: how to set a value for an empty field with podio-php wrapper?
I'm trying to set a field value via API using podio-php. If the field was already  not empty, the following snippet made according to the manual works fine:

```<code>$item = PodioItem::get_basic( $item_id );
$field = $item->fields["field-name"];
$field->values = "2"; // let's say we have a number filed
$item->save(); // $field->save() also works
</code>```

But if the field was empty, a warning Creating default object from empty value occures on save. No errors, no changes in the item. This is true for different types of fields. I assume, a field-object should be created from scratch, but didn't managed to find an info on this for different field types.

So, please, how to correctly set a value with podio-php when the field is empty? Thanks.

答:
I had the Same Problem and found this Gem..

```<code>PodioItem::update(210606, array('fields' => array(
"title" => "The API documentation is much more funny",
"business_value" => array('value' => 20000, "currency" => "EUR"),
"due_date" => array('start' => "2011-05-06 11:27:20", "end" => "2012-04-30
10:44:20"),
));
</code>```

I modified it so I can update individual fields. But this will update the field without that stupid error.

```<code>$FieldsArray = [];
$FieldsArray['encounter-status'] = "Draft";
$item = PodioItem::update($itemID, array('fields' => $FieldsArray));
</code>```

Body:
I'm trying to set a field value via API using podio-php. If the field was already  not empty, the following snippet made according to the manual works fine:

$item = PodioItem::get_basic( $item_id );
$field = $item->fields["field-name"];
$field->values = "2"; // let's say we have a number filed
$item->save(); // $field->save() also works

But if the field was empty, a warning Creating default object from empty value occures on save. No errors, no changes in the item. This is true for different types of fields. I assume, a field-object should be created from scratch, but didn't managed to find an info on this for different field types.

So, please, how to correctly set a value with podio-php when the field is empty? Thanks.

Body:
I had the Same Problem and found this Gem..

PodioItem::update(210606, array('fields' => array(
"title" => "The API documentation is much more funny",
"business_value" => array('value' => 20000, "currency" => "EUR"),
"due_date" => array('start' => "2011-05-06 11:27:20", "end" => "2012-04-30
10:44:20"),
));

I modified it so I can update individual fields. But this will update the field without that stupid error.

$FieldsArray = [];
$FieldsArray['encounter-status'] = "Draft";
$item = PodioItem::update($itemID, array('fields' => $FieldsArray));


问:
Can't log in Opensis after installation
I am using Mac and XAMPP including php 7.1.10 (Apache + MariaDB + PHP + Perl)

I installed Opensis 6.4 successfully. Database was created. I made a staff id. school id was created too. the information is well connected in database.

But it keep asking me to install opensis. I cann't get log in page.

How can I solve the problem?

I tried 6.3 version and 5.3 version of Opensis

答:
Do a fresh install of XAMPP for OSX  Copy opensis (I used Community
  Edition) to the htdocs directory Before you start SQL and Apache, do
  the following in Terminal:</p>

```<code>sudo chown -R 777 /Applications/XAMPP/xamppfiles/htdocs/opensis
sudo chmod -R 777 /Applications/XAMPP/xamppfiles/htdocs/opensis
</code>```

Title: Can't log in Opensis after installation

Body:
Do a fresh install of XAMPP for OSX  Copy opensis (I used Community
  Edition) to the htdocs directory Before you start SQL and Apache, do
  the following in Terminal:

sudo chown -R 777 /Applications/XAMPP/xamppfiles/htdocs/opensis
sudo chmod -R 777 /Applications/XAMPP/xamppfiles/htdocs/opensis


问:
When i resize my webpage the section expands vertically adding unwanted background

When the webpage is on the big screen everything is perfect. All 3 blocks of text are inline and the white footer comes right after the background picture.
But when I resize the window webpage automatically adds space after the picture.
 Not sure what I should do: have my picture repeated? But that won't look good. Leave it as it is? Not sure what to do? What is a good solution for this?

答:
If you have a background image, you can set the background-size to cover to ensure that it always covers the whole element.

See example here: https://jsfiddle.net/ut04htu0/


问:
how can we use will_paginate in ruby on rails 3.0.3
is their will_paginate will support to ruby on rails 3.0.3?</p>

答: Yes. In beta - https://github.com/mislav/will_paginate/tree/rails3.</p>


问:
dyld: Library not loaded: lib/libopencv_core.3.0.dylib Reason: image not found
I am getting the following issue:

/Users/luke/Desktop/trainHOG/trainhog ; exit;
dyld: Library not loaded: lib/libopencv_core.3.0.dylib
  Referenced from: /Users/luke/Desktop/trainHOG/trainhog
  Reason: image not found
Trace/BPT trap: 5
logout

I am using a Mac running OSX v10.9.5 with openCV 3.0 alpha.

The library in question is definitely in the folder. I have tried deleting it and pasting it back into the folder, I have completely deleted and reinstalled openCV and macports, and I have tried the export DYLD_LIBRARY_PATH = "path to dynamic libs here..", but nothing has worked. I have even rebooted my computer on several occasions!

Does anyone have any further suggestions? I am out of ideas

答:
OpenCV 3.3
OSX 10.13
fist have a test, you can use clang++ -o a -I ./include -L ./lib
-lopencv_core.your.version
then you can generate executable file a ,run it ,if have the error massage.
you will find the error reason cannot find the lib when you are link.

if you want to solve error on terminal
you can use export DYLD_LIBRARY_PATH=your/lib:$DYLD_LIBRARY_PATH
if you want to solve error on Xcode
in build page , go to "Runpath Search Paths"
add you lib path


问:
What is the angle brackets part is called in C# e.g. SomeMethodName<ISomething>()
Given the following in C#:

```<code>public Complex SomeMethodName<ISomething>(int x, int y, ....)
</code>```

we can describe each part as follows :

```<code>public : accessor specifier
Complex : the resut of the function
SomeMethodName : Method Name
<ISomething> : ???
(int x, int y, ....) : parameter list
</code>```

My question is what is the name for <ISomething> Part?

PS : I know the name for angle brackets, but what does that part signify? the generiticisim of the method?

Update : for example
we would read

```<code>public Complex SomeMethodName(int x, int y, ....)
</code>```

as public method SomeMethodName returning Complex as result and taking parameters int x, int y, ...

Should we read

```<code>public Complex SomeMethodName<ISomething>(int x, int y, ....)
</code>```

as public method SomeMethodName of generic type ISomething returning Complex as result and taking parameters int x, int y, ... ?

答: It's Generic Type Parameters of Generics.</p>

Body:
Given the following in C#:

public Complex SomeMethodName<ISomething>(int x, int y, ....)

we can describe each part as follows :

public : accessor specifier
Complex : the resut of the function
SomeMethodName : Method Name
<ISomething> : ???
(int x, int y, ....) : parameter list

My question is what is the name for <ISomething> Part?

PS : I know the name for angle brackets, but what does that part signify? the generiticisim of the method?

Update : for example
we would read

public Complex SomeMethodName(int x, int y, ....)

as public method SomeMethodName returning Complex as result and taking parameters int x, int y, ...

Should we read

public Complex SomeMethodName<ISomething>(int x, int y, ....)

as public method SomeMethodName of generic type ISomething returning Complex as result and taking parameters int x, int y, ... ?


问:
Changing application.properties in AWS for a Spring Boot webapp
I've made a spring project using Boot. the project runs fine locally. It's a simple webapp connected to a mysql database. The configuration path is:

src/main/resources/application.properties

With parameters like this:

```<code>spring.datasource.url = xxx
spring.datasource.username = xxx
spring.datasource.password = xxx
</code>```

Now, I've deployed the app in AWS without problems. I've configured the database already but when the app tries to start I'm getting this error:

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

I guess that is using my local configuratión file that was packed in the war file. Now, how can I change those values in the AWS? O do I need to pack the war with the correct application.properties in that server?

Thanks!

答: Based on my experience, we can use spring cloud config server along with hosted properties on repositories like git/svn and pull them on the fly based on the active profile that you are running the application</p>

Body:
I've made a spring project using Boot. the project runs fine locally. It's a simple webapp connected to a mysql database. The configuration path is:

src/main/resources/application.properties

With parameters like this:

spring.datasource.url = xxx
spring.datasource.username = xxx
spring.datasource.password = xxx

Now, I've deployed the app in AWS without problems. I've configured the database already but when the app tries to start I'm getting this error:

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

I guess that is using my local configuratión file that was packed in the war file. Now, how can I change those values in the AWS? O do I need to pack the war with the correct application.properties in that server?

Thanks!


问:
FBX model showing Black textures on ThreeJS
I try to load this FBX model on ThreeJS.

https://www.dropbox.com/s/pwa31xkia8tg8v9/fbx%20threejs.zip?dl=0

it's loading correctly with animation, but all are showing black texture.

I'm using official example to load FBX from ThreeJS, i just replaced model file.

Please help, i need this for my project.

Thanks for your time!
Regards

答: Please check the file format of texture image. Convert the image to jpg and change your model likewise opening it in a text file. You can also check specific loader for specific image file format like TGALoader for .tga.</p>


问:
How to access local storage from chrome extension?
I have a web application that I'm writing a chrome extension for, and in this web application I save data to local storage. I am trying to access this data from a chrome extension, but none of these options are able to access the local storage that isn't associated with just the scope of the extension:

```<code>localStorage.getItem
localStorage["itemName"]
chrome.storage.local.get function
chrome.storage.sync.get function
</code>```

None of these methods have worked, as they all return "null" or "undefined" for items that I know exist in the localStorage that have been set from my web application. Can someone please help? I thought this would be a simple task but so far I can't solve it.

答: As Jaromanda X and wOxxOm have kindly pointed out, using a content script gives me the access I need to solve this--thanks!</p>

Body:
I have a web application that I'm writing a chrome extension for, and in this web application I save data to local storage. I am trying to access this data from a chrome extension, but none of these options are able to access the local storage that isn't associated with just the scope of the extension:

localStorage.getItem
localStorage["itemName"]
chrome.storage.local.get function
chrome.storage.sync.get function

None of these methods have worked, as they all return "null" or "undefined" for items that I know exist in the localStorage that have been set from my web application. Can someone please help? I thought this would be a simple task but so far I can't solve it.


问:
Toolbar not showing at the top of the page in Tab Bar Based Application in iPhone
In my iPhone app, I am using a tab-bar based application as my basic application type.

I created one toolbar at the top of the page in FirstViewController of tab-bar based app.

Also I changed File's Owner Class to "FirstViewController" aqnd have connected the outlets to toolbar buttons.

Now the problem is that when I run the project I don't see any toolbar at the top my page.

What could be wrong?

答: Set the view property "Bottom Bar" to "Tab bar" of the FirstViewController.</p>


问:
Calculate Scala average
I need to calculate the average of three ages in Scala. I have tried the method shown below, but it did not work. Please help.</p>

```<code>sealed abstract class Component
case class Life (age:Int) extends Component

object Life extends Component{
  def main(args: Array[String]){
    val lives = List{Life(10), Life(20), Life(30)}
    def livesMean (l:List[Life]):Double = {
        println(livesMean)
    }
  }
}
</code>```

答:
First you have declared list of object of lives incorrectly. And to find average, take the sum of ages and divide it by size of list.

```<code>sealed abstract class Component
case class Life (age:Int) extends Component

object Main extends Component{
    def main(args: Array[String]){
    val lives = List(Life(10), Life(20), Life(30))
    def livesMean (l:List[Life]):Double = lives.map(_.age).sum/lives.size
    println("average of lives "+ livesMean(lives))
  }
}
</code>```

It is running. You can see it here

Title: Calculate Scala average

Body:
I need to calculate the average of three ages in Scala. I have tried the method shown below, but it did not work. Please help.

sealed abstract class Component
case class Life (age:Int) extends Component

object Life extends Component{
  def main(args: Array[String]){
    val lives = List{Life(10), Life(20), Life(30)}
    def livesMean (l:List[Life]):Double = {
        println(livesMean)
    }
  }
}

Body:
First you have declared list of object of lives incorrectly. And to find average, take the sum of ages and divide it by size of list.

sealed abstract class Component
case class Life (age:Int) extends Component

object Main extends Component{
    def main(args: Array[String]){
    val lives = List(Life(10), Life(20), Life(30))
    def livesMean (l:List[Life]):Double = lives.map(_.age).sum/lives.size
    println("average of lives "+ livesMean(lives))
  }
}

It is running. You can see it here


问:
Find next instance of a given weekday (ie. Monday) with moment.js
I want to get the date of the next Monday or Thursday (or today if it is Mon or Thurs). As Moment.js works within the bounds of a Sunday - Saturday, I'm having to work out the current day and calculate the next Monday or Thursday based on that:

```<code>if (moment().format("dddd")=="Sunday") { var nextDay = moment().day(1); }
if (moment().format("dddd")=="Monday") { var nextDay = moment().day(1); }
if (moment().format("dddd")=="Tuesday") { var nextDay = moment().day(4); }
if (moment().format("dddd")=="Wednesday") { var nextDay = moment().day(4); }
if (moment().format("dddd")=="Thursday") { var nextDay = moment().day(4); }
if (moment().format("dddd")=="Friday") { var nextDay = moment(.day(8); }
if (moment().format("dddd")=="Saturday") { var nextDay = moment().day(8); }
</code>```

This works, but surely there's a better way!

答:
Here's a solution to find the next Monday, or today if it is Monday:</p>

```<code>const dayOfWeek = moment().day('monday').hour(0).minute(0).second(0);

const endOfToday = moment().hour(23).minute(59).second(59);

if(dayOfWeek.isBefore(endOfToday)) {
  dayOfWeek.add(1, 'weeks');
}
</code>```

Body:
I want to get the date of the next Monday or Thursday (or today if it is Mon or Thurs). As Moment.js works within the bounds of a Sunday - Saturday, I'm having to work out the current day and calculate the next Monday or Thursday based on that:

if (moment().format("dddd")=="Sunday") { var nextDay = moment().day(1); }
if (moment().format("dddd")=="Monday") { var nextDay = moment().day(1); }
if (moment().format("dddd")=="Tuesday") { var nextDay = moment().day(4); }
if (moment().format("dddd")=="Wednesday") { var nextDay = moment().day(4); }
if (moment().format("dddd")=="Thursday") { var nextDay = moment().day(4); }
if (moment().format("dddd")=="Friday") { var nextDay = moment(.day(8); }
if (moment().format("dddd")=="Saturday") { var nextDay = moment().day(8); }

This works, but surely there's a better way!

Body:
Here's a solution to find the next Monday, or today if it is Monday:

const dayOfWeek = moment().day('monday').hour(0).minute(0).second(0);

const endOfToday = moment().hour(23).minute(59).second(59);

if(dayOfWeek.isBefore(endOfToday)) {
  dayOfWeek.add(1, 'weeks');
}


问:
Adding the values in the list recursively and returning the partial sums
I have a list [1,2,3,4]. My function should return [1,3,6,10]. This is what I have so far. I have tried to make a helper method that takes the value and keeps it to a list and adds it. But it does not seem to work. </p>

```<code>summed = []

help x = (x + summed x) : summed

summing [] = []
summing (x:xs) = help x : summing xs
</code>```

答:
Not a complete answer, because this sounds like homework.  But there are several approaches.

You’re on the right track.  If you want to write a function with two parameters: the sum so far, and the input list.  If you pass the tail of the list to the next iteration, the number you want to add to the accumulating sum will be the head of the list you pass in.

You might also look at the higher-order functions in Data.List for one that takes as its arguments the function (+), an initial value, and a list and returns a repeated application of the function to each element of the list, then returns a list of the results, not just a final result.  What you’re doing is an important pattern to learn.

Body:
I have a list [1,2,3,4]. My function should return [1,3,6,10]. This is what I have so far. I have tried to make a helper method that takes the value and keeps it to a list and adds it. But it does not seem to work.

summed = []

help x = (x + summed x) : summed

summing [] = []
summing (x:xs) = help x : summing xs


问:
How to split train and test dataset to X_Train y_train and X_Test y_Test?
So I successfully split my dataset into Train & Test in a ratio of 70:30
I used this:

```<code>df_glass['split'] = np.random.randn(df_glass.shape[0], 1)
msk = np.random.rand(len(df_glass)) <= 0.7
train = df_glass[msk]
test = df_glass[~msk]
print(train)
print(test)
</code>```

Now how do I split train and test to X_train and y_train and X_test and y_test
Such that, X denotes the features of the database and y denotes the response?

I need to do supervised learning and apply ML modules on X_Train and y_Train.

My database looks like this:
Database_snippet

答:
Scikit-Learn has a convenience method for splitting pandas dataframes - </p>

<p>This will do the split - </p>

```<code>from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(df[list_of_X_cols], df['y'], test_size=0.33, random_state=42)
</code>```

Body:
So I successfully split my dataset into Train & Test in a ratio of 70:30
I used this:

df_glass['split'] = np.random.randn(df_glass.shape[0], 1)
msk = np.random.rand(len(df_glass)) <= 0.7
train = df_glass[msk]
test = df_glass[~msk]
print(train)
print(test)

Now how do I split train and test to X_train and y_train and X_test and y_test
Such that, X denotes the features of the database and y denotes the response?

I need to do supervised learning and apply ML modules on X_Train and y_Train.

My database looks like this:
Database_snippet

Body:
Scikit-Learn has a convenience method for splitting pandas dataframes -

This will do the split -

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(df[list_of_X_cols], df['y'], test_size=0.33, random_state=42)


问:
Multiple domains for site subsections
Here's the deal. Basically I've got multiple domains, and I would like one of the domains to point to the regular base of the site, but the other domains to point to a subsection of the site without modifying the url in the address bar. The idea is that each of the extra domains are branded for their section.

Example:

www.domain.com Top level of site

www.domain2.com points to www.domain.com/abc

www.domain3.com points to www.domain.com/def

etc.

Also note that in the example 'abc' and 'def' are not real directories on the filesystem, but are virtual areas defined in a database.

I've spent quite a bit of time looking around and couldn't find anything that fits this. I do not want to use domain cloaking because it uses frames. Regular redirects obviously are easy to point to the right thing, but they change the url in the address bar.

Is there any way to accomplish this?

Edit:

I've added the alias as Mark suggested below, but can anyone shed light on how I could then use mod_rewrite to make this work?

答:
First, your DNS records need to point to the IP of the web server.

Second, you have to set up Apache to serve multiple domains from the same VirtualHost. Enable mod_alias and then use the ServerAlias directive in your VirtualHost definition. For example:

```<code>ServerName www.domain.com
ServerAlias domain.com www.domain2.com domain2.com www.domain3.com domain3.com
</code>```

If you've done that correctly, you should see the exact same content at each domain, without any redirection.

What you do next is an architectural decision. You can use mod_rewrite to hard-code URL routing rules based on domain, or you can use PHP to do the routing, based on the value of $_SERVER['HTTP_HOST'].

A mod_rewrite solution might involve adding something like this to your .htaccess file:

```<code>RewriteEngine On

RewriteCond %{HTTP_HOST} domain2\.com$
RewriteRule ^(.*)$ /abc/$1 [L]

RewriteCond %{HTTP_HOST} domain3\.com$
RewriteRule ^(.*)$ /def/$1 [L]
</code>```

This is a high-level overview. Please comment on my answer if you need details on a particular part of the process.

Title: Multiple domains for site subsections

Body:
First, your DNS records need to point to the IP of the web server.

Second, you have to set up Apache to serve multiple domains from the same VirtualHost. Enable mod_alias and then use the ServerAlias directive in your VirtualHost definition. For example:

ServerName www.domain.com
ServerAlias domain.com www.domain2.com domain2.com www.domain3.com domain3.com

If you've done that correctly, you should see the exact same content at each domain, without any redirection.

What you do next is an architectural decision. You can use mod_rewrite to hard-code URL routing rules based on domain, or you can use PHP to do the routing, based on the value of $_SERVER['HTTP_HOST'].

A mod_rewrite solution might involve adding something like this to your .htaccess file:

RewriteEngine On

RewriteCond %{HTTP_HOST} domain2\.com$
RewriteRule ^(.*)$ /abc/$1 [L]

RewriteCond %{HTTP_HOST} domain3\.com$
RewriteRule ^(.*)$ /def/$1 [L]

This is a high-level overview. Please comment on my answer if you need details on a particular part of the process.


问:
Nothing to repeat at position 0 when replacing string in pandas dataframe
In my MySQL database, phone in a VARCHAR. Then, I import this to a pandas dataframe. Here's my data:

```<code>data5

id   phone
1     +62634783472
2       0834838483
3              +62
</code>```

What I want is convert +62 to 0, expected output would be like this

```<code>id   phone
1       0634783472
2       0834838483
3                0
</code>```

I already try two thing, there are

```<code>data5['phone'] = data5['phone'].str.replace('+62', '0')

data5['phone'] = data5['phone'].replace(to_replace='+62', value='0', regex=True)
</code>```

And the result is:

```<code>error: nothing to repeat at position 0
</code>```

What is I miss?

答:
+ is a special character and you have to escape it with \:

```<code>import pandas as pd
data5 = pd.DataFrame({"id": [1, 2, 3],
                      "phone": ["+62634783472", "0834838483", "+62"]})

data5['phone'] = data5['phone'].str.replace('\+62', '0')

# data5
   id       phone
0   1  0634783472
1   2  0834838483
2   3           0
</code>```

Body:
In my MySQL database, phone in a VARCHAR. Then, I import this to a pandas dataframe. Here's my data:

data5

id   phone
1     +62634783472
2       0834838483
3              +62

What I want is convert +62 to 0, expected output would be like this

id   phone
1       0634783472
2       0834838483
3                0

I already try two thing, there are

data5['phone'] = data5['phone'].str.replace('+62', '0')

data5['phone'] = data5['phone'].replace(to_replace='+62', value='0', regex=True)

And the result is:

error: nothing to repeat at position 0

What is I miss?

Body:
+ is a special character and you have to escape it with \:

import pandas as pd
data5 = pd.DataFrame({"id": [1, 2, 3],
                      "phone": ["+62634783472", "0834838483", "+62"]})

data5['phone'] = data5['phone'].str.replace('\+62', '0')

# data5
   id       phone
0   1  0634783472
1   2  0834838483
2   3           0


问:
anyway to optimize this multiple insert query?
So I have 3 tables given on the codes below
I don't know if there's any way to optimize this because I think it's not the proper way to insert data especially if you're dealing with normalization.</p>

```<code>string mySqlCon = "Server = localhost; port = 3306; database = rmsdb; Uid = root; pwd=''"; //connection string

private void loginbtn_Click(object sender, EventArgs e)
{
    MySqlConnection con = new MySqlConnection(mySqlCon);
    MySqlCommand cmd;

    try
    {
        if (firstnametb.Text.Length > 0 && lastnametb.Text.Length > 0 && gendercb.Text.Length > 0 && addresstb.Text.Length > 0 && birthdatetb.Text.Length > 0 && gradelevelcb.Text.Length > 0 && sectioncb.Text.Length > 0 && positioncb.Text.Length > 0 && empstatuscb.Text.Length > 0 && fiutb.Text.Length > 0 && oadtb.Text.Length > 0 && prctb.Text.Length > 0 && gsistb.Text.Length > 0 && csetb.Text.Length > 0 && contacttb.Text.Length > 0 && usernametb.Text.Length > 0 && passwordtb.Text.Length > 0 && questioncb.Text.Length > 0 && answertb.Text.Length > 0)
        {

            string CmdString = "INSERT INTO TeachersINFO('teachersid',firstname,lastname,gender,address,birthdate,position,empstatus,contactnumber,gradelevel,section,status) values (@teachersid,@firstname,@lastname,@gender,@address,@birthdate,@position,@empstatus,@contactnumber,@gradelevel,@section,@status);" +Environment.NewLine+
                               "INSERT INTO teacherslogin(teachersid,username,password,secretquestion,answer,status) values (@teachersid2,@username,@password,@secretquestion,@answer,@status2);" +Environment.NewLine+
                               "INSERT INTO teachersref(teachersid,FIU,oad,PrcNo,GSISBPNo,UMIDNo,TinNo,PhilHealthNo,CivilServiceE) values (@teachersid3,@FIU,@oad,@PrcNo,@GSISBPNo,@UMIDNo,@TinNo,@PhilHealthNo)";
            cmd = new MySqlCommand(CmdString, con);
            cmd.Parameters.AddWithValue("@teachersid", teacheridtb.Text);
            cmd.Parameters.AddWithValue("@firstname", firstnametb.Text);
            cmd.Parameters.AddWithValue("@lastname", lastnametb.Text);
            cmd.Parameters.AddWithValue("@gender", gendercb.Text);
            cmd.Parameters.AddWithValue("@address", addresstb.Text);
            cmd.Parameters.AddWithValue("@birthdate", birthdatetb.Text);
            cmd.Parameters.AddWithValue("@position", positioncb.Text);
            cmd.Parameters.AddWithValue("@empstatus", empstatuscb.Text);
            cmd.Parameters.AddWithValue("@contactnumber", contacttb.Text);
            cmd.Parameters.AddWithValue("@gradelevel", gradelevelcb.Text);
            cmd.Parameters.AddWithValue("@section", sectioncb.Text);
            cmd.Parameters.AddWithValue("@status", 1);
            //secondtable values p0ta kahit pandurugas to wala kong pake stored procedures parin tawag dito HAHAHA//
            cmd.Parameters.AddWithValue("@teachersid2", teacheridtb.Text);
            cmd.Parameters.AddWithValue("@username", usernametb.Text);
            cmd.Parameters.AddWithValue("@password", passwordtb.Text);
            cmd.Parameters.AddWithValue("@secretquestion", questioncb.Text);
            cmd.Parameters.AddWithValue("@answer", answertb.Text);
            cmd.Parameters.AddWithValue("@status2",1);
            //thirdtable values hahaha pota pandaraya so much

            con.Open();
            int RowsAffected = cmd.ExecuteNonQuery();
            if (RowsAffected > 0)
            {
                MessageBox.Show("Registered Successfully", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                firstnametb.Text = "";
                lastnametb.Text = "";
                gendercb.SelectedItem = null;
                lastnametb.Text = "";
                addresstb.Text = "";
                gradelevelcb.SelectedItem = null;
                sectioncb.SelectedItem = null;
                answertb.Text = "";
                usernametb.Text = "";
                passwordtb.Text = "";
                questioncb.Text = "";
                empstatuscb.Text = "";
                positioncb.Text = "";
                fiutb.Text = "";
                oadtb.Text = "";
                prctb.Text = "";
                gsistb.Text = "";
                csetb.Text = "";

                con.Close();
                //clearing textboxes fields.

            }
        }
        else
        {
            MessageBox.Show("Incomplete Data", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error);

        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
    }

}
</code>```

答:
There's nothing wrong with the approach to updating the data.
However, there's a lot of room for C# code optimization as well as the program reliability.

First of all, try/catch/finally blocks are not meant for managing IDisposable resources. You can make your C# code more readable, by making use of a using block instead. Then trap the database call and at least log any errors. That way, your program will sustain a database server failure and continue to execute. Later, you can inspect the logs and see what the error was and figure out how to fight it in the next program release.

```<code>string mySqlCon = "Server = localhost; port = 3306; database = rmsdb; Uid = root; pwd=''"; //connection string

private void loginbtn_Click(object sender, EventArgs e)
{
    var succeeded = false;

    var canUpdate = firstnametb.Text.Length > 0
        && lastnametb.Text.Length > 0
        && gendercb.Text.Length > 0
        && addresstb.Text.Length > 0
        && birthdatetb.Text.Length > 0
        && gradelevelcb.Text.Length > 0
        && sectioncb.Text.Length > 0
        && positioncb.Text.Length > 0
        && empstatuscb.Text.Length > 0
        && fiutb.Text.Length > 0
        && oadtb.Text.Length > 0
        && prctb.Text.Length > 0
        && gsistb.Text.Length > 0
        && csetb.Text.Length > 0
        && contacttb.Text.Length > 0
        && usernametb.Text.Length > 0
        && passwordtb.Text.Length > 0
        && questioncb.Text.Length > 0
        && answertb.Text.Length > 0;

    if (canUpdate)
    {
        using (var con = new MySqlConnection(mySqlCon))
        using (var cmd = con.CreateCommand())
        {
            cmd = "INSERT INTO TeachersINFO('teachersid',firstname,lastname,gender,address,birthdate,position,empstatus,contactnumber,gradelevel,section,status) values (@teachersid,@firstname,@lastname,@gender,@address,@birthdate,@position,@empstatus,@contactnumber,@gradelevel,@section,@status);" + Environment.NewLine
                + "INSERT INTO teacherslogin(teachersid,username,password,secretquestion,answer,status) values (@teachersid2,@username,@password,@secretquestion,@answer,@status2);" + Environment.NewLine
                + "INSERT INTO teachersref(teachersid,FIU,oad,PrcNo,GSISBPNo,UMIDNo,TinNo,PhilHealthNo,CivilServiceE) values (@teachersid3,@FIU,@oad,@PrcNo,@GSISBPNo,@UMIDNo,@TinNo,@PhilHealthNo)";

            cmd.Parameters.AddWithValue("@teachersid", teacheridtb.Text);
            cmd.Parameters.AddWithValue("@firstname", firstnametb.Text);
            cmd.Parameters.AddWithValue("@lastname", lastnametb.Text);
            cmd.Parameters.AddWithValue("@gender", gendercb.Text);
            cmd.Parameters.AddWithValue("@address", addresstb.Text);
            cmd.Parameters.AddWithValue("@birthdate", birthdatetb.Text);
            cmd.Parameters.AddWithValue("@position", positioncb.Text);
            cmd.Parameters.AddWithValue("@empstatus", empstatuscb.Text);
            cmd.Parameters.AddWithValue("@contactnumber", contacttb.Text);
            cmd.Parameters.AddWithValue("@gradelevel", gradelevelcb.Text);
            cmd.Parameters.AddWithValue("@section", sectioncb.Text);
            cmd.Parameters.AddWithValue("@status", 1);
            //secondtable values p0ta kahit pandurugas to wala kong pake stored procedures parin tawag dito HAHAHA//
            cmd.Parameters.AddWithValue("@teachersid2", teacheridtb.Text);
            cmd.Parameters.AddWithValue("@username", usernametb.Text);
            cmd.Parameters.AddWithValue("@password", passwordtb.Text);
            cmd.Parameters.AddWithValue("@secretquestion", questioncb.Text);
            cmd.Parameters.AddWithValue("@answer", answertb.Text);
            cmd.Parameters.AddWithValue("@status2", 1);
            //thirdtable values hahaha pota pandaraya so much

            con.Open();
            try
            {
                var RowsAffected = cmd.ExecuteNonQuery();
                succeeded = RowsAffected > 0;
            }
            catch (Exception ex)
            {
                // Log the captured exception here
                // E.g. if using NUnit do:
                //      Log.Fatal(ex.ToString());
            }
        }

        if (succeeded)
        {
            MessageBox.Show("Registered Successfully", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            firstnametb.Text = "";
            lastnametb.Text = "";
            gendercb.SelectedItem = null;
            lastnametb.Text = "";
            addresstb.Text = "";
            gradelevelcb.SelectedItem = null;
            sectioncb.SelectedItem = null;
            answertb.Text = "";
            usernametb.Text = "";
            passwordtb.Text = "";
            questioncb.Text = "";
            empstatuscb.Text = "";
            positioncb.Text = "";
            fiutb.Text = "";
            oadtb.Text = "";
            prctb.Text = "";
            gsistb.Text = "";
            csetb.Text = "";
            //clearing textboxes fields.
        }
        else
        {
            MessageBox.Show("Some I/O error has occured.", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    else
    {
        MessageBox.Show("Incomplete Data", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
</code>```

Body:
So I have 3 tables given on the codes below
I don't know if there's any way to optimize this because I think it's not the proper way to insert data especially if you're dealing with normalization.

string mySqlCon = "Server = localhost; port = 3306; database = rmsdb; Uid = root; pwd=''"; //connection string

private void loginbtn_Click(object sender, EventArgs e)
{
    MySqlConnection con = new MySqlConnection(mySqlCon);
    MySqlCommand cmd;

    try
    {
        if (firstnametb.Text.Length > 0 && lastnametb.Text.Length > 0 && gendercb.Text.Length > 0 && addresstb.Text.Length > 0 && birthdatetb.Text.Length > 0 && gradelevelcb.Text.Length > 0 && sectioncb.Text.Length > 0 && positioncb.Text.Length > 0 && empstatuscb.Text.Length > 0 && fiutb.Text.Length > 0 && oadtb.Text.Length > 0 && prctb.Text.Length > 0 && gsistb.Text.Length > 0 && csetb.Text.Length > 0 && contacttb.Text.Length > 0 && usernametb.Text.Length > 0 && passwordtb.Text.Length > 0 && questioncb.Text.Length > 0 && answertb.Text.Length > 0)
        {

            string CmdString = "INSERT INTO TeachersINFO('teachersid',firstname,lastname,gender,address,birthdate,position,empstatus,contactnumber,gradelevel,section,status) values (@teachersid,@firstname,@lastname,@gender,@address,@birthdate,@position,@empstatus,@contactnumber,@gradelevel,@section,@status);" +Environment.NewLine+
                               "INSERT INTO teacherslogin(teachersid,username,password,secretquestion,answer,status) values (@teachersid2,@username,@password,@secretquestion,@answer,@status2);" +Environment.NewLine+
                               "INSERT INTO teachersref(teachersid,FIU,oad,PrcNo,GSISBPNo,UMIDNo,TinNo,PhilHealthNo,CivilServiceE) values (@teachersid3,@FIU,@oad,@PrcNo,@GSISBPNo,@UMIDNo,@TinNo,@PhilHealthNo)";
            cmd = new MySqlCommand(CmdString, con);
            cmd.Parameters.AddWithValue("@teachersid", teacheridtb.Text);
            cmd.Parameters.AddWithValue("@firstname", firstnametb.Text);
            cmd.Parameters.AddWithValue("@lastname", lastnametb.Text);
            cmd.Parameters.AddWithValue("@gender", gendercb.Text);
            cmd.Parameters.AddWithValue("@address", addresstb.Text);
            cmd.Parameters.AddWithValue("@birthdate", birthdatetb.Text);
            cmd.Parameters.AddWithValue("@position", positioncb.Text);
            cmd.Parameters.AddWithValue("@empstatus", empstatuscb.Text);
            cmd.Parameters.AddWithValue("@contactnumber", contacttb.Text);
            cmd.Parameters.AddWithValue("@gradelevel", gradelevelcb.Text);
            cmd.Parameters.AddWithValue("@section", sectioncb.Text);
            cmd.Parameters.AddWithValue("@status", 1);
            //secondtable values p0ta kahit pandurugas to wala kong pake stored procedures parin tawag dito HAHAHA//
            cmd.Parameters.AddWithValue("@teachersid2", teacheridtb.Text);
            cmd.Parameters.AddWithValue("@username", usernametb.Text);
            cmd.Parameters.AddWithValue("@password", passwordtb.Text);
            cmd.Parameters.AddWithValue("@secretquestion", questioncb.Text);
            cmd.Parameters.AddWithValue("@answer", answertb.Text);
            cmd.Parameters.AddWithValue("@status2",1);
            //thirdtable values hahaha pota pandaraya so much

            con.Open();
            int RowsAffected = cmd.ExecuteNonQuery();
            if (RowsAffected > 0)
            {
                MessageBox.Show("Registered Successfully", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                firstnametb.Text = "";
                lastnametb.Text = "";
                gendercb.SelectedItem = null;
                lastnametb.Text = "";
                addresstb.Text = "";
                gradelevelcb.SelectedItem = null;
                sectioncb.SelectedItem = null;
                answertb.Text = "";
                usernametb.Text = "";
                passwordtb.Text = "";
                questioncb.Text = "";
                empstatuscb.Text = "";
                positioncb.Text = "";
                fiutb.Text = "";
                oadtb.Text = "";
                prctb.Text = "";
                gsistb.Text = "";
                csetb.Text = "";

                con.Close();
                //clearing textboxes fields.

            }
        }
        else
        {
            MessageBox.Show("Incomplete Data", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error);

        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
    }

}

Body:
There's nothing wrong with the approach to updating the data.
However, there's a lot of room for C# code optimization as well as the program reliability.

First of all, try/catch/finally blocks are not meant for managing IDisposable resources. You can make your C# code more readable, by making use of a using block instead. Then trap the database call and at least log any errors. That way, your program will sustain a database server failure and continue to execute. Later, you can inspect the logs and see what the error was and figure out how to fight it in the next program release.

string mySqlCon = "Server = localhost; port = 3306; database = rmsdb; Uid = root; pwd=''"; //connection string

private void loginbtn_Click(object sender, EventArgs e)
{
    var succeeded = false;

    var canUpdate = firstnametb.Text.Length > 0
        && lastnametb.Text.Length > 0
        && gendercb.Text.Length > 0
        && addresstb.Text.Length > 0
        && birthdatetb.Text.Length > 0
        && gradelevelcb.Text.Length > 0
        && sectioncb.Text.Length > 0
        && positioncb.Text.Length > 0
        && empstatuscb.Text.Length > 0
        && fiutb.Text.Length > 0
        && oadtb.Text.Length > 0
        && prctb.Text.Length > 0
        && gsistb.Text.Length > 0
        && csetb.Text.Length > 0
        && contacttb.Text.Length > 0
        && usernametb.Text.Length > 0
        && passwordtb.Text.Length > 0
        && questioncb.Text.Length > 0
        && answertb.Text.Length > 0;

    if (canUpdate)
    {
        using (var con = new MySqlConnection(mySqlCon))
        using (var cmd = con.CreateCommand())
        {
            cmd = "INSERT INTO TeachersINFO('teachersid',firstname,lastname,gender,address,birthdate,position,empstatus,contactnumber,gradelevel,section,status) values (@teachersid,@firstname,@lastname,@gender,@address,@birthdate,@position,@empstatus,@contactnumber,@gradelevel,@section,@status);" + Environment.NewLine
                + "INSERT INTO teacherslogin(teachersid,username,password,secretquestion,answer,status) values (@teachersid2,@username,@password,@secretquestion,@answer,@status2);" + Environment.NewLine
                + "INSERT INTO teachersref(teachersid,FIU,oad,PrcNo,GSISBPNo,UMIDNo,TinNo,PhilHealthNo,CivilServiceE) values (@teachersid3,@FIU,@oad,@PrcNo,@GSISBPNo,@UMIDNo,@TinNo,@PhilHealthNo)";

            cmd.Parameters.AddWithValue("@teachersid", teacheridtb.Text);
            cmd.Parameters.AddWithValue("@firstname", firstnametb.Text);
            cmd.Parameters.AddWithValue("@lastname", lastnametb.Text);
            cmd.Parameters.AddWithValue("@gender", gendercb.Text);
            cmd.Parameters.AddWithValue("@address", addresstb.Text);
            cmd.Parameters.AddWithValue("@birthdate", birthdatetb.Text);
            cmd.Parameters.AddWithValue("@position", positioncb.Text);
            cmd.Parameters.AddWithValue("@empstatus", empstatuscb.Text);
            cmd.Parameters.AddWithValue("@contactnumber", contacttb.Text);
            cmd.Parameters.AddWithValue("@gradelevel", gradelevelcb.Text);
            cmd.Parameters.AddWithValue("@section", sectioncb.Text);
            cmd.Parameters.AddWithValue("@status", 1);
            //secondtable values p0ta kahit pandurugas to wala kong pake stored procedures parin tawag dito HAHAHA//
            cmd.Parameters.AddWithValue("@teachersid2", teacheridtb.Text);
            cmd.Parameters.AddWithValue("@username", usernametb.Text);
            cmd.Parameters.AddWithValue("@password", passwordtb.Text);
            cmd.Parameters.AddWithValue("@secretquestion", questioncb.Text);
            cmd.Parameters.AddWithValue("@answer", answertb.Text);
            cmd.Parameters.AddWithValue("@status2", 1);
            //thirdtable values hahaha pota pandaraya so much

            con.Open();
            try
            {
                var RowsAffected = cmd.ExecuteNonQuery();
                succeeded = RowsAffected > 0;
            }
            catch (Exception ex)
            {
                // Log the captured exception here
                // E.g. if using NUnit do:
                //      Log.Fatal(ex.ToString());
            }
        }

        if (succeeded)
        {
            MessageBox.Show("Registered Successfully", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            firstnametb.Text = "";
            lastnametb.Text = "";
            gendercb.SelectedItem = null;
            lastnametb.Text = "";
            addresstb.Text = "";
            gradelevelcb.SelectedItem = null;
            sectioncb.SelectedItem = null;
            answertb.Text = "";
            usernametb.Text = "";
            passwordtb.Text = "";
            questioncb.Text = "";
            empstatuscb.Text = "";
            positioncb.Text = "";
            fiutb.Text = "";
            oadtb.Text = "";
            prctb.Text = "";
            gsistb.Text = "";
            csetb.Text = "";
            //clearing textboxes fields.
        }
        else
        {
            MessageBox.Show("Some I/O error has occured.", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    else
    {
        MessageBox.Show("Incomplete Data", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}


答: scanl (+) 0 yourList should do it. You can read up on how it's implemented and why by looking through GHC's standard library documentation and sources. https://ghc.gitlab.haskell.org/ghc/doc/libraries/base-4.16.0.0/src/GHC-List.html#scanl

Title: Adding the values in the list recursively and returning the partial sums


问:
How to send POST request to API with signup form without backend
I'm trying to figure out how to connect my signup to sender.net API so when someone fills out the form it will be added to my subscriber list. Sender.net provided me with this information to help:

API is implemented through HTTP protocool, using POST. Responses are returned in json.

All API requested shall be directed at http://app.sneder.net/api/api.

Request data must be encoded in json, in POST parameter named data.

I wrote this code but nothing appears on my subscriber list, please see below:

```<code><!DOCTYPE html>
<html>

<head>
  <title>test with sender</title>
</head>

<body>

  <h1>This is to test sender.net API "POST" </h1>

  <form>
    <input type="text" name="Fname" placeholder="first name">
    <input type="text" name="Lname" placeholder="last name">
    <input type="email" name="Email" placeholder="email address">
    <button type="submit" onclick="JSONTest()"> Let the Post req begin!
            </button>
  </form>

  <script type="text/javascript">
    JSONTest = function() {
      $.ajax({
        url: "https://app.sender.net/api/",
        method: "POST",
        datatype: "JSON",
        data: {
          method: "listSubscribe",
          params: {
            api_key: "my key number",
            list_id: "my id number",
            emails: ["Email", "Fname", "Lname"],
            update_existing: true
          }
        }
      });
    };
  </script>

  <!-- Jquery -->
  <script src="vendor/jquery/jquery.min.js"></script>

</body>

</html>
</code>```

答:
    </p>

```<code><head>
    <title>test with sender</title>
</head>

<body>

    <h1>This is to test sender.net API "POST" </h1>

    <form>
        <input type="text" name="Fname" placeholder="first name">
        <input type="text" name="Lname" placeholder="last name">
        <input type="email" name="Email" placeholder="email address">
        <button type="button" onclick="JSONTest()"> Let the Post req begin!
        </button>
    </form>

    <script type="text/javascript">
    JSONTest = function() {
        $.ajax({
            url: "https://app.sender.net/api/",
            method: "POST",
            datatype: "JSON",
            data: {
                method: "listSubscribe",
                params: {
                    api_key: "my key number",
                    list_id: "my id number",
                    emails: ["Email", "Fname", "Lname"],
                    update_existing: true
                }
            },
            success : function(response) {
                console.log(response); // Feel free to Use debugger

            }
        });
    };
    </script>
</code>```

Body:
I'm trying to figure out how to connect my signup to sender.net API so when someone fills out the form it will be added to my subscriber list. Sender.net provided me with this information to help:

API is implemented through HTTP protocool, using POST. Responses are returned in json.

All API requested shall be directed at http://app.sneder.net/api/api.

Request data must be encoded in json, in POST parameter named data.

I wrote this code but nothing appears on my subscriber list, please see below:

<!DOCTYPE html>

  <title>test with sender</title>

This is to test sender.net API "POST"

  <form>
    <input type="text" name="Fname" placeholder="first name">
    <input type="text" name="Lname" placeholder="last name">
    <input type="email" name="Email" placeholder="email address">
    <button type="submit" onclick="JSONTest()"> Let the Post req begin!
            </button>
  </form>


问:
Solution for Must use scalare variable in asp.net
```<code>protected void showData()
{
    DataTable dt = new DataTable();

    SqlDataAdapter adapt = new SqlDataAdapter("select @orderID, @buyersName, @deliveryAddress, @productID, @productName, @category, @image, @price, @paymentMode, @holderName, @OrderDate, @PhoneNo from tblOrderDetails", con);
    adapt.Fill(dt);

    GridView1.DataSource = dt;
    GridView1.DataBind();
}
</code>```

This code is showing an error:

Must use scalar variable @orderId

What do I have to correct?

答:
using @ if u awnt insert parameter, in this case no need anymore
just like this:</p>

```<code>"select orderID, buyersName, deliveryAddress, productID, productName, category, image, price, paymentMode, holderName, OrderDate, PhoneNo from tblOrderDetails", con);
</code>```

Body:
protected void showData()
{
    DataTable dt = new DataTable();

    SqlDataAdapter adapt = new SqlDataAdapter("select @orderID, @buyersName, @deliveryAddress, @productID, @productName, @category, @image, @price, @paymentMode, @holderName, @OrderDate, @PhoneNo from tblOrderDetails", con);
    adapt.Fill(dt);

    GridView1.DataSource = dt;
    GridView1.DataBind();
}

This code is showing an error:

Must use scalar variable @orderId

What do I have to correct?

Body:
using @ if u awnt insert parameter, in this case no need anymore
just like this:

"select orderID, buyersName, deliveryAddress, productID, productName, category, image, price, paymentMode, holderName, OrderDate, PhoneNo from tblOrderDetails", con);


答:
Template type.
Template typename.
Template parameter.
Template argument.</p>

Title: What is the angle brackets part is called in C# e.g. SomeMethodName<ISomething>()

Body:
Given the following in C#:

public Complex SomeMethodName<ISomething>(int x, int y, ....)

we can describe each part as follows :

public : accessor specifier
Complex : the resut of the function
SomeMethodName : Method Name
<ISomething> : ???
(int x, int y, ....) : parameter list

My question is what is the name for <ISomething> Part?

PS : I know the name for angle brackets, but what does that part signify? the generiticisim of the method?

Update : for example
we would read

public Complex SomeMethodName(int x, int y, ....)

as public method SomeMethodName returning Complex as result and taking parameters int x, int y, ...

Should we read

public Complex SomeMethodName<ISomething>(int x, int y, ....)

as public method SomeMethodName of generic type ISomething returning Complex as result and taking parameters int x, int y, ... ?


问:
How to print json array from Response<ResponseBody> response in retorift2.0
I developed android application with retorfit 2.0. I tweeter in our application. I am getting json array format data from url when check in browser. I am getting response in my application like code: 200ok and responce is like : repoces@012345 printed as raw data. How can I print response as array format.

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://cdn.syndication.twimg.com/")
                .addConverterFactory(GsonConverterFactory.create())

                .build();

        RequestInterface requestInterface = retrofit.create(RequestInterface.class);

        Call<ResponseBody> response = requestInterface.gettwetter("vinodh654");

        response.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d("Tweeter Respose",response.code()+" "+response.message()+" "+response.body().toString());

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("Tweeter Respose","Fail");
            }
        });```

答:
To get the JSON use </p>

```<code>response.body().string()
</code>```

Body:
To get the JSON use

response.body().string()


问:
AngularJS get Directive properties and pass as a paremeter on binded Click Event
I'm new to angularjs and I want to know how can I get directives properties and pass it as a parameters on my Directive's click event,

here is my HTML Directive, the  tag together with its properties is dynamically created. The properties I want to get and pass as parameters are the id and status

```<code><a href='#' class='article-link' id='"+b.id+"' status='"+articleStatus+"' display-article-div-directive>
</code>```

here is my Angular Directive

```<code>myApp.directive("displayArticleDivDirective", function($parse,$rootScope)   {

        return function($scope, $element, $attrs) {

            var id =  $parse($attrs.id)($scope);
            var status =  $parse($attrs.status)($scope);
            var clickingCallback = function(id,status) {

                console.log('stat: '+status);
                /* status and id is undefined here */
            };
            $element.bind('click', clickingCallback);
        }
    });
</code>```

I hope you can paste here a working sample, thank you very much,

答:
Use a scope on your directive to enable the data to be passed in, instead of parsing the element.  Something like this:

```<code>app.directive("displayArticleDivDirective", function() {
  return {
    scope: {
      id: "=",
      status: "="
    },
    link: function(scope, element, attrs) {
      var clickingCallback = function() {
        console.log('stat: ' + scope.status);
        console.log('id: ' + scope.id);
      };
      element.bind('click', clickingCallback);
    }
  };
});
</code>```

HTML:

```<code><a href='#' class='article-link' id='"+b.id+"' status='"+articleStatus+"' display-article-div-directive>Test </a>
</code>```

http://plnkr.co/edit/PLBQeQkLelbm9nHnBHIt?p=preview

Body:
I'm new to angularjs and I want to know how can I get directives properties and pass it as a parameters on my Directive's click event,

here is my HTML Directive, the  tag together with its properties is dynamically created. The properties I want to get and pass as parameters are the id and status

here is my Angular Directive

myApp.directive("displayArticleDivDirective", function($parse,$rootScope)   {

        return function($scope, $element, $attrs) {

            var id =  $parse($attrs.id)($scope);
            var status =  $parse($attrs.status)($scope);
            var clickingCallback = function(id,status) {

                console.log('stat: '+status);
                /* status and id is undefined here */
            };
            $element.bind('click', clickingCallback);
        }
    });

I hope you can paste here a working sample, thank you very much,

Body:
Use a scope on your directive to enable the data to be passed in, instead of parsing the element.  Something like this:

app.directive("displayArticleDivDirective", function() {
  return {
    scope: {
      id: "=",
      status: "="
    },
    link: function(scope, element, attrs) {
      var clickingCallback = function() {
        console.log('stat: ' + scope.status);
        console.log('id: ' + scope.id);
      };
      element.bind('click', clickingCallback);
    }
  };
});

HTML:

<a href='#' class='article-link' id='"+b.id+"' status='"+articleStatus+"' display-article-div-directive>Test </a>

http://plnkr.co/edit/PLBQeQkLelbm9nHnBHIt?p=preview


问:
Creating a pandas column conditional to another columns values
I'm trying to create a class column in a pandas dataframe conditional another columns values. The value will be 1 if the other column's i+1 value is greater than the i value and 0 otherwise.

For example:

```<code>column1 column2
   5       1
   6       0
   3       0
   2       1
   4       0
</code>```

How do create column2 by iterating through column1?

答:
You can also use shift. Performance is almost the same as diff but diff seems to be faster by a a little.

```<code>df = pd.DataFrame({'column1': [5,6,3,2,4]})
df['column2'] = (df['column1'] <df['column1'].shift(-1)).astype(int)
print(df)
   column1  column2
0        5        1
1        6        0
2        3        0
3        2        1
4        4        0
</code>```

Body:
I'm trying to create a class column in a pandas dataframe conditional another columns values. The value will be 1 if the other column's i+1 value is greater than the i value and 0 otherwise.

For example:

column1 column2
   5       1
   6       0
   3       0
   2       1
   4       0

How do create column2 by iterating through column1?

Body:
You can also use shift. Performance is almost the same as diff but diff seems to be faster by a a little.

df = pd.DataFrame({'column1': [5,6,3,2,4]})
df['column2'] = (df['column1'] <df['column1'].shift(-1)).astype(int)
print(df)
   column1  column2
0        5        1
1        6        0
2        3        0
3        2        1
4        4        0


答:
You can print that using response.body().string() as follows:

```<code>  response.enqueue(new Callback<ResponseBody>() {
     @Override
     public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {
            String data = response.body().string(); // It will get the response
            Log.d("Tweeter Respose",response.code()+" "+response.message()+" "+data;
     }

     @Override
     public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.d("Tweeter Respose","Fail");
     }
  });
</code>```

Title: How to print json array from Response<ResponseBody> response in retorift2.0

Body:
I developed android application with retorfit 2.0. I tweeter in our application. I am getting json array format data from url when check in browser. I am getting response in my application like code: 200ok and responce is like : repoces@012345 printed as raw data. How can I print response as array format.

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://cdn.syndication.twimg.com/")
                .addConverterFactory(GsonConverterFactory.create())

                .build();

        RequestInterface requestInterface = retrofit.create(RequestInterface.class);

        Call<ResponseBody> response = requestInterface.gettwetter("vinodh654");

        response.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d("Tweeter Respose",response.code()+" "+response.message()+" "+response.body().toString());

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("Tweeter Respose","Fail");
            }
        });

Body:
You can print that using response.body().string() as follows:

  response.enqueue(new Callback<ResponseBody>() {
     @Override
     public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {
            String data = response.body().string(); // It will get the response
            Log.d("Tweeter Respose",response.code()+" "+response.message()+" "+data;
     }

     @Override
     public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.d("Tweeter Respose","Fail");
     }
  });


问:
Cassandra Datastax Node.js driver can't find keyspace
Just installed Cassandra (3.11.1) and Datastax node.js driver (3.3.0).

Created a simple structure:

```<code>CREATE KEYSPACE CaseBox
   WITH REPLICATION={
     'class': 'SimpleStrategy',
     'replication_factor': 1};
USE CaseBox;

CREATE TABLE Regions (
    regionId int,
    name varchar,
    PRIMARY KEY ((regionId))
);
</code>```

Trying connect to the keyspace with no success:

```<code>const client = new cassandra.Client({
  contactPoints: ['localhost'],
  keyspace: 'CaseBox'
});

await client.connect();
</code>```

Error: Keyspace 'CaseBox' does not exist.
If I change the desired kayspace to system it works.
What's wrong? Please assist.

You can find my full Cassandra config, CQL and js scripts here.

答:
Keyspace names are forced lower case when unquoted in CQL.

Use CREATE KEYSPACE "CaseBox" in CQL or keyspace: 'casebox' in Node.

Generally just use snake_case names as you won't get trapped like this as often.

Body:
Just installed Cassandra (3.11.1) and Datastax node.js driver (3.3.0).

Created a simple structure:

CREATE KEYSPACE CaseBox
   WITH REPLICATION={
     'class': 'SimpleStrategy',
     'replication_factor': 1};
USE CaseBox;

CREATE TABLE Regions (
    regionId int,
    name varchar,
    PRIMARY KEY ((regionId))
);

Trying connect to the keyspace with no success:

const client = new cassandra.Client({
  contactPoints: ['localhost'],
  keyspace: 'CaseBox'
});

await client.connect();

Error: Keyspace 'CaseBox' does not exist.
If I change the desired kayspace to system it works.
What's wrong? Please assist.

You can find my full Cassandra config, CQL and js scripts here.


问:
Laravel SwiftMailer : Expected response code 250 but got code "530", with message "530-5.5.1 Authentication Required
I am using laravel 5.2, And the using Swift Mailer for password resetting.
I have 2-step verification on my gmail..

As the google help says :

If you've turned on 2-Step Verification for your account, you might need to enter an App password instead of your regular password.

I have the following settings on mail.php :

```<code>return [
    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.gmail.com'),
    'port' => env('MAIL_PORT', 465),
    'from' => ['address' => 'meaprogrammer@gmail.com', 'name' => 'Shafee'],
    'encryption' => env('MAIL_ENCRYPTION', 'ssl'),
    'username' => env('meaprogrammer@gmail.com'),
    'password' => env('MY_Gmail_API_KEY'),
    'sendmail' => '/usr/sbin/sendmail -bs',
    'pretend' => env('MAIL_PRETEND', false),

];
</code>```

On the .env i have :

```<code>MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=meaprogrammer@gmail.com
MAIL_PASSWORD=MY_Gmail_API_KEY
MAIL_ENCRYPTION=ssl
</code>```

The following error comes up :

```<code>Swift_TransportException in AbstractSmtpTransport.php line 383:

Expected response code 250 but got code "530", with message "530-5.5.1 Authentication Required.

Learn more at
530 5.5.1 https://support.google.com/mail/answer/14257 w10sm15831823wjk.18 - gsmtp
"
</code>```

答:
In laravel, I was also having the same issue but is because of... I was not using "use clause" in the Mail function .

The error got solved after using "use clause".

Body:
I am using laravel 5.2, And the using Swift Mailer for password resetting.
I have 2-step verification on my gmail..

As the google help says :

If you've turned on 2-Step Verification for your account, you might need to enter an App password instead of your regular password.

I have the following settings on mail.php :

return [
    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.gmail.com'),
    'port' => env('MAIL_PORT', 465),
    'from' => ['address' => 'meaprogrammer@gmail.com', 'name' => 'Shafee'],
    'encryption' => env('MAIL_ENCRYPTION', 'ssl'),
    'username' => env('meaprogrammer@gmail.com'),
    'password' => env('MY_Gmail_API_KEY'),
    'sendmail' => '/usr/sbin/sendmail -bs',
    'pretend' => env('MAIL_PRETEND', false),

];

On the .env i have :

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=meaprogrammer@gmail.com
MAIL_PASSWORD=MY_Gmail_API_KEY
MAIL_ENCRYPTION=ssl

The following error comes up :

Swift_TransportException in AbstractSmtpTransport.php line 383:

Expected response code 250 but got code "530", with message "530-5.5.1 Authentication Required.

Learn more at
530 5.5.1 https://support.google.com/mail/answer/14257 w10sm15831823wjk.18 - gsmtp
"