问:
Changing reference types(strings) inside methods
I am passing a string variable to a method. I know strings are reference types but the value that I assign inside the method is lost. </p>

```<code>public static void TestMethod(string myString)
{
    myString = "world";
}

static void Main(string[] args)
{
    string s = "hello";
    Console.WriteLine(s); // output is "hello"
    TestMethod(s);
    Console.WriteLine(s); // output is also "hello" not "world" !?
}
</code>```

<p>Anyway this does not happen with an array for example. Can someone explain why might be the cause? </p>

答:
For this to work you need to add the "ref" keyword to the parameter in the method signature.

Though your string is passed by reference, when you pass it to your method you have 2 references to the same string - the one in the Main() and the one in TestMethod(). When you assign a new value to the variable in the TestMethod() you are changing its reference, but not what Main()'s variable is referencing.

If you were able to just change the string from the TestMethod() instead of reassigning then you would see the effects in the Main(), but you can't with strings since they are immutable.

To play with this further you can try the following - change TestMethod() to receive a IList and add items to this list. You can see these new items in the variable you passed in from Main(). Now if you change TestMethod(IList listArg) to first reassign listArg to a new list (i.e. listArg = new List) and then add items, the list in Main() remains unchanged. This is the same idea.

Body:
I am passing a string variable to a method. I know strings are reference types but the value that I assign inside the method is lost.

public static void TestMethod(string myString)
{
    myString = "world";
}

static void Main(string[] args)
{
    string s = "hello";
    Console.WriteLine(s); // output is "hello"
    TestMethod(s);
    Console.WriteLine(s); // output is also "hello" not "world" !?
}

Anyway this does not happen with an array for example. Can someone explain why might be the cause?


来源: stackexchange

问:
Swift add icon/image in UITextField
I would like to add icon/image in UITextField. The icon/image should be left to placeholder.

I tried this:

```<code>var imageView = UIImageView();
var image = UIImage(named: "email.png");
imageView.image = image;
emailField.leftView = imageView;
</code>```

Thanks.

答:
Why don't you go for the easiest approach. For most cases you want to add icons like font awesome... Just use font awesome library and it would be as easy to add an icon to an text field as this:

```<code>myTextField.setLeftViewFAIcon(icon: .FAPlus, leftViewMode: .always, textColor: .red, backgroundColor: .clear, size: nil)
</code>```

You would need to install first this swift library:
https://github.com/Vaberer/Font-Awesome-Swift

ContentLicense: CC BY-SA 3.0

Title: Swift add icon/image in UITextField

Body:
I would like to add icon/image in UITextField. The icon/image should be left to placeholder.

I tried this:

var imageView = UIImageView();
var image = UIImage(named: "email.png");
imageView.image = image;
emailField.leftView = imageView;

Thanks.

Body:
Why don't you go for the easiest approach. For most cases you want to add icons like font awesome... Just use font awesome library and it would be as easy to add an icon to an text field as this:

myTextField.setLeftViewFAIcon(icon: .FAPlus, leftViewMode: .always, textColor: .red, backgroundColor: .clear, size: nil)

You would need to install first this swift library:
https://github.com/Vaberer/Font-Awesome-Swift


问:
Cannot commit Android Studio Project to Bitbucket - "Home Variable is Not defined"
I'm trying to commit a project to Bitbucket and I'm getting this error:

Anyone knows, what I should do?

答:
Hello I am pretty sure that your Android Studio is not able to find your local installation of git.

I would also encourage you to try and Commit from the shell to see if my last affirmation is true.


问:
IIS express doesn't start but Kestrel web server instead
My application have been working well for weeks. Today I possibly did something wrong and IIS express is not starting any more (and no errors in the event log) but Kestrel appears in a command window saying it is listening for connections on 5000th port.

How to fix it and get IIS express back?

Startup.cs:

```<code>public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        if (env.IsDevelopment())
        {
            // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
            builder.AddApplicationInsightsSettings(developerMode: true);
        }
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddMvc();

        // Add functionality to inject IOptions<T>
        services.AddOptions();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseApplicationInsightsRequestTelemetry();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseDeveloperExceptionPage();
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
</code>```

答:
Check your Properties/launchSettings.json file. It contains "configuration" for VS "Run" button (it dropdown menu), like this:

```<code>{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:63104/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "My Web App": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:5000"
    }
  }
}
</code>```

Body:
My application have been working well for weeks. Today I possibly did something wrong and IIS express is not starting any more (and no errors in the event log) but Kestrel appears in a command window saying it is listening for connections on 5000th port.

How to fix it and get IIS express back?

Startup.cs:

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        if (env.IsDevelopment())
        {
            // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
            builder.AddApplicationInsightsSettings(developerMode: true);
        }
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddMvc();

        // Add functionality to inject IOptions<T>
        services.AddOptions();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseApplicationInsightsRequestTelemetry();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseDeveloperExceptionPage();
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

Body:
Check your Properties/launchSettings.json file. It contains "configuration" for VS "Run" button (it dropdown menu), like this:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:63104/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "My Web App": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:5000"
    }
  }
}


问:
Make a flexbox middle part scroll, without the container taking 100% of the page
Making a flexbox child have a scroll bar instead of growing, takes a container with fixed height.
easy to create in a an isolated environment:

```<code> #container {
  height: 100%;
  display: flex;
  flex: 0 0 auto;
  flex-flow: column;
}

#list {
  display: flex;
  flex-flow: column;
  overflow: auto;
}
</code>```

https://jsfiddle.net/1yjk5ojp/

but let's say i want to use a page header.
i don't know it's exact size, so i can't use aboslute position with mergin.
i also can't use any flex component along the way, cuz it's must be fixed size.

for example - added a 100px header

```<code><div style="height: 100px;">
  <h1>Page header</h1>
</div>
</code>```

https://jsfiddle.net/z6dsq822/1/

is there anything i can do to make a fixed height component after an unknown size component?

my constrains are that i don't want another scroll bar, and i want the header to be outside this structure (it's a large application with different views, the header is in a template)

答:
Make the parent container for everything a flex column and set #container to flex-grow: 1 so it takes up the available space, then everything else works as you already had it.

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

html,
body {
  height: 100vh;
}

body {
  display: flex;
  flex-direction: column;
}

header {
  flex: 0 0 100px;
}

#container {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  overflow: auto;
}

#list {
  display: flex;
  overflow: scroll;
  flex-direction: column;
  flex-grow: 1;
}

#top {
  flex: 0 0 20px;
  background-color: #db9277;
}

#bottom {
  flex: 0 0 20px;
  background-color: #db9277;
}

.row {
  height: 100px;
  background-color: #85d8d5;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  header
</header>
<div id="container">
  <div id="top"></div>
  <div id="list">
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
  </div>
  <div id="bottom"></div>
</div></code>```

Body:
Making a flexbox child have a scroll bar instead of growing, takes a container with fixed height.
easy to create in a an isolated environment:

 #container {
  height: 100%;
  display: flex;
  flex: 0 0 auto;
  flex-flow: column;
}

#list {
  display: flex;
  flex-flow: column;
  overflow: auto;
}

https://jsfiddle.net/1yjk5ojp/

but let's say i want to use a page header.
i don't know it's exact size, so i can't use aboslute position with mergin.
i also can't use any flex component along the way, cuz it's must be fixed size.

for example - added a 100px header

Page header

https://jsfiddle.net/z6dsq822/1/

is there anything i can do to make a fixed height component after an unknown size component?

my constrains are that i don't want another scroll bar, and i want the header to be outside this structure (it's a large application with different views, the header is in a template)

Body:
Make the parent container for everything a flex column and set #container to flex-grow: 1 so it takes up the available space, then everything else works as you already had it.

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

html,
body {
  height: 100vh;
}

body {
  display: flex;
  flex-direction: column;
}

header {
  flex: 0 0 100px;
}

#container {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  overflow: auto;
}

#list {
  display: flex;
  overflow: scroll;
  flex-direction: column;
  flex-grow: 1;
}

#top {
  flex: 0 0 20px;
  background-color: #db9277;
}

#bottom {
  flex: 0 0 20px;
  background-color: #db9277;
}

.row {
  height: 100px;
  background-color: #85d8d5;
}

<header>
  header
</header>
<div id="container">
  <div id="top"></div>
  <div id="list">
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
    <div class="row">Lorem ipsum dolor sit amet.</div>
  </div>
  <div id="bottom"></div>
</div>


问:
The while loop doesn't continue as intended
For some reason, the while loop in main terminates once I enter a character to search, but the intention is for you to be able to enter a line and then a character to search until you enter a blank line (enter nothing). Basically I would want to do step 1 and step 2 infinitely until I type nothing and hit enter. Why doesn't this work? Thanks anyone for help!

Also, a little side question, how do I clear any garbage after a character is entered for searching?

```<code>#include <stdio.h>
#define SIZE 41
int CharIsAt(char *pStr,char ch,int loc[],int mLoc);
int main(void){
    char array[SIZE],search;
    int found[SIZE],i,charsFound;
    //Step 1
    printf("Enter a line of text(empty line to quit): ");
    while (fgets(array,SIZE, stdin)!=NULL && array[0]!='\n'){ //Loop until nothing is entered
    //Step 2
        printf("Enter a character to search: ");
        search=getchar();
        charsFound=CharIsAt(array,search,found,SIZE);
        printf("Entered text: ");
        fputs(array,stdout);
        printf("Character being searched for: %c\n",search);
        printf("Character found at %d location(s).\n",charsFound);
        for (i=0;i<charsFound;i++)
            printf("%c was found at %d\n",search,found[i]);
        printf("Enter a line of text(empty line to quit): ");
    }
    return 0;
}
int CharIsAt(char *pStr,char ch,int loc[],int mLoc){
    //Searches for ch in *pStr by incrementing a pointer to access
    //and compare each character in *pStr to ch.
    int i,x;
    for (i=0,x=0;i<mLoc;i++){
        if (*(pStr+i)==ch){
            //Stores index of ch's location to loc
            loc[x]=i;
            x++;    //Increment for each time ch was counted in pStr
        }
    }
    //Returns the number of times ch was found
    return x;
}
</code>```

I included my entire code if that's not too annoying, I can try and make a simpler version of the problem if that would help. I figured posting the entire code might be more useful for answering the question.

Thanks again, cheers!

答:
the main problem with the posted code is that the user had to press enter to get the search character into the program.  However, the call to getchar() only consumes a single char, so it did not consume the newline sequence.

To fix this problem, call getchar() in a loop until the char is either EOF or '\n'  to empty stdin of any/all leftover trash.

Then step back to the top of the loop

Body:
For some reason, the while loop in main terminates once I enter a character to search, but the intention is for you to be able to enter a line and then a character to search until you enter a blank line (enter nothing). Basically I would want to do step 1 and step 2 infinitely until I type nothing and hit enter. Why doesn't this work? Thanks anyone for help!

Also, a little side question, how do I clear any garbage after a character is entered for searching?

#include <stdio.h>
#define SIZE 41
int CharIsAt(char *pStr,char ch,int loc[],int mLoc);
int main(void){
    char array[SIZE],search;
    int found[SIZE],i,charsFound;
    //Step 1
    printf("Enter a line of text(empty line to quit): ");
    while (fgets(array,SIZE, stdin)!=NULL && array[0]!='\n'){ //Loop until nothing is entered
    //Step 2
        printf("Enter a character to search: ");
        search=getchar();
        charsFound=CharIsAt(array,search,found,SIZE);
        printf("Entered text: ");
        fputs(array,stdout);
        printf("Character being searched for: %c\n",search);
        printf("Character found at %d location(s).\n",charsFound);
        for (i=0;i<charsFound;i++)
            printf("%c was found at %d\n",search,found[i]);
        printf("Enter a line of text(empty line to quit): ");
    }
    return 0;
}
int CharIsAt(char *pStr,char ch,int loc[],int mLoc){
    //Searches for ch in *pStr by incrementing a pointer to access
    //and compare each character in *pStr to ch.
    int i,x;
    for (i=0,x=0;i<mLoc;i++){
        if (*(pStr+i)==ch){
            //Stores index of ch's location to loc
            loc[x]=i;
            x++;    //Increment for each time ch was counted in pStr
        }
    }
    //Returns the number of times ch was found
    return x;
}

I included my entire code if that's not too annoying, I can try and make a simpler version of the problem if that would help. I figured posting the entire code might be more useful for answering the question.

Thanks again, cheers!


问:
messagebox appeared second time
In my code, when TextBox3 does not have any value, it must show a notice in a MsgBox to enter a value in TextBox1

But when I run it the MsgBoxnotice appears twice in the screen when it should show only once.

Here is my code:

```<code>Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    If TextBox3.Text = Nothing Then
        TextBox1.Clear()
        MsgBox("Enter Number to Textbox1")
    Else
        Dim digit As Integer = CInt(TextBox3.Text)
        If TextBox1.TextLength = digit Then
            Dim fields() As String = ListBox1.Text.Split(";")
            Dim idx As Integer = ListBox1.FindString(TextBox1.Text)
            If idx <> -1 Then
                ListBox1.SelectedIndex = idx
                ListBox1.SelectedIndex.ToString(fields(0))
                ListBox2.Items.Add(Now() + Space(1) + ListBox1.Text.Substring(0, 13))
                PrintDocument1.Print()
            Else
                TextBox1.Clear()
            End If
        End If
    End If
End Sub
</code>```

答:
The Issue here is that the event handler gets triggered another time because clearing the textbox1 equals the textbox1_changed event handler to go of. You could as well just disable the textbox till the textbox3 is not nothing anymore.
or a quick solution would be aswell</p>

```<code>Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If not TextBox1.Text = Nothing AndAlso TextBox3.text = Nothing Then
    TextBox1.Clear()
    MsgBox("Enter Number to Textbox1")
.............
</code>```

Title: messagebox appeared second time

Body:
In my code, when TextBox3 does not have any value, it must show a notice in a MsgBox to enter a value in TextBox1

But when I run it the MsgBoxnotice appears twice in the screen when it should show only once.

Here is my code:

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    If TextBox3.Text = Nothing Then
        TextBox1.Clear()
        MsgBox("Enter Number to Textbox1")
    Else
        Dim digit As Integer = CInt(TextBox3.Text)
        If TextBox1.TextLength = digit Then
            Dim fields() As String = ListBox1.Text.Split(";")
            Dim idx As Integer = ListBox1.FindString(TextBox1.Text)
            If idx <> -1 Then
                ListBox1.SelectedIndex = idx
                ListBox1.SelectedIndex.ToString(fields(0))
                ListBox2.Items.Add(Now() + Space(1) + ListBox1.Text.Substring(0, 13))
                PrintDocument1.Print()
            Else
                TextBox1.Clear()
            End If
        End If
    End If
End Sub

Body:
The Issue here is that the event handler gets triggered another time because clearing the textbox1 equals the textbox1_changed event handler to go of. You could as well just disable the textbox till the textbox3 is not nothing anymore.
or a quick solution would be aswell

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If not TextBox1.Text = Nothing AndAlso TextBox3.text = Nothing Then
    TextBox1.Clear()
    MsgBox("Enter Number to Textbox1")
.............


问:
plyr summarize only calls global functions
I'm trying to pass a function (weight.func) to a different function (wrapper) that calls ddply. I want ddply to use that function (weight.func) as part of its calculations. I get the output I want when weight.func is set 'globally' but not when it is passes as an anonymous function to the wrapper.

Can I get ddply to do what I want? Here is a code example:

```<code>> print(sampleData)
   studentId   problem  part       workerId rating
1       8001 problem26 partA A127R5QI5OGBIK    0.0
2       8001 problem26 partA A1FCLYRBAB430F    0.0
3       8001 problem26 partA A25FZQY34C6RVO    0.0
4       8001 problem26 partA A3G0MO562MHMZ3    0.5
5       8001 problem26 partA A3RB9ZOIUC3NWG    2.0
6       8001 problem26 partB A1FCLYRBAB430F    0.5
7       8001 problem26 partB A1XRDZKSJBWY8Q    0.5
8       8001 problem26 partB A22CRWMZUX7FFR    0.5
9       8001 problem26 partB A25FZQY34C6RVO    1.0
10      8001 problem26 partB A3G0MO562MHMZ3    0.5
11      8001 problem27 partA A1ET309DW6M2XA    2.0
12      8001 problem27 partA A1FCLYRBAB430F    0.0
13      8001 problem27 partA A22CRWMZUX7FFR    0.0
14      8001 problem27 partA A25FZQY34C6RVO    0.0
15      8001 problem27 partA A3G0MO562MHMZ3    0.0
16      8001 problem27 partB A1FCLYRBAB430F    1.0
17      8001 problem27 partB A22CRWMZUX7FFR    0.0
18      8001 problem27 partB A25FZQY34C6RVO    0.0
19      8001 problem27 partB A2U9676210WST5    0.0
20      8001 problem27 partB A3G0MO562MHMZ3    0.0
21      8002 problem26 partA A127R5QI5OGBIK    0.0
22      8002 problem26 partA A1FCLYRBAB430F    0.5
23      8002 problem26 partA A22CRWMZUX7FFR    0.0
24      8002 problem26 partA A25FZQY34C6RVO    2.0
25      8002 problem26 partA A3G0MO562MHMZ3    0.5
26      8002 problem26 partB A17EHJZNJGNRAN    2.0
27      8002 problem26 partB A1FCLYRBAB430F    0.0
28      8002 problem26 partB A2IPRDTE6B4TAB    0.0
29      8002 problem26 partB A3G0MO562MHMZ3    0.0
30      8002 problem26 partB  A6SON3OS15XKA    0.0
31      8002 problem27 partA A1FCLYRBAB430F    0.0
32      8002 problem27 partA A25FZQY34C6RVO    0.0
33      8002 problem27 partA A2IPRDTE6B4TAB    0.0
34      8002 problem27 partA A2U9676210WST5    0.0
35      8002 problem27 partA A3G0MO562MHMZ3    0.0
36      8002 problem27 partB A1FCLYRBAB430F    0.0
37      8002 problem27 partB A1V52SSKROBV8E    2.0
38      8002 problem27 partB A25FZQY34C6RVO    2.0
39      8002 problem27 partB A2IPRDTE6B4TAB    0.0
40      8002 problem27 partB A3G0MO562MHMZ3    0.0
>
> #Make a wrapper
> wrapper <- function ( ratingData, weight.func ) {
+   print(weight.func) #prove that the function is being passed
+   ddply(ratingData, c('studentId','problem','part'), summarize,
+           sum.weights = sum ( weight.func(rating)  ))
+ }
> wrapper( sampleData, weight.func=function(x) (x+.001)^-1  )
function(x) (x+.001)^-1
Error in data.frame(sum.weights = sum(weight.func(rating))) :
  could not find function "weight.func"
>
> #'globally' declare weight.func
> weight.func <- function(x) (x+.001)^-1
> wrapper( sampleData, weight.func=NULL  )
NULL
  studentId   problem  part sum.weights
1      8001 problem26 partA 3002.495758
2      8001 problem26 partB    8.983033
3      8001 problem27 partA 4000.499750
4      8001 problem27 partB 4000.999001
5      8002 problem26 partA 2004.491766
6      8002 problem26 partB 4000.499750
7      8002 problem27 partA 5000.000000
8      8002 problem27 partB 3000.999500
</code>```

The second output is the goal. Any help appreciated! (Including a non plyr based way to accomplish the same task.)

The example above is a toy example. It's the simplest case I could get to reproduce the behavior.

答: This is a known bug in plyr: https://github.com/hadley/plyr/issues#issue/3</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to pass a function (weight.func) to a different function (wrapper) that calls ddply. I want ddply to use that function (weight.func) as part of its calculations. I get the output I want when weight.func is set 'globally' but not when it is passes as an anonymous function to the wrapper.

Can I get ddply to do what I want? Here is a code example:

> print(sampleData)
   studentId   problem  part       workerId rating
1       8001 problem26 partA A127R5QI5OGBIK    0.0
2       8001 problem26 partA A1FCLYRBAB430F    0.0
3       8001 problem26 partA A25FZQY34C6RVO    0.0
4       8001 problem26 partA A3G0MO562MHMZ3    0.5
5       8001 problem26 partA A3RB9ZOIUC3NWG    2.0
6       8001 problem26 partB A1FCLYRBAB430F    0.5
7       8001 problem26 partB A1XRDZKSJBWY8Q    0.5
8       8001 problem26 partB A22CRWMZUX7FFR    0.5
9       8001 problem26 partB A25FZQY34C6RVO    1.0
10      8001 problem26 partB A3G0MO562MHMZ3    0.5
11      8001 problem27 partA A1ET309DW6M2XA    2.0
12      8001 problem27 partA A1FCLYRBAB430F    0.0
13      8001 problem27 partA A22CRWMZUX7FFR    0.0
14      8001 problem27 partA A25FZQY34C6RVO    0.0
15      8001 problem27 partA A3G0MO562MHMZ3    0.0
16      8001 problem27 partB A1FCLYRBAB430F    1.0
17      8001 problem27 partB A22CRWMZUX7FFR    0.0
18      8001 problem27 partB A25FZQY34C6RVO    0.0
19      8001 problem27 partB A2U9676210WST5    0.0
20      8001 problem27 partB A3G0MO562MHMZ3    0.0
21      8002 problem26 partA A127R5QI5OGBIK    0.0
22      8002 problem26 partA A1FCLYRBAB430F    0.5
23      8002 problem26 partA A22CRWMZUX7FFR    0.0
24      8002 problem26 partA A25FZQY34C6RVO    2.0
25      8002 problem26 partA A3G0MO562MHMZ3    0.5
26      8002 problem26 partB A17EHJZNJGNRAN    2.0
27      8002 problem26 partB A1FCLYRBAB430F    0.0
28      8002 problem26 partB A2IPRDTE6B4TAB    0.0
29      8002 problem26 partB A3G0MO562MHMZ3    0.0
30      8002 problem26 partB  A6SON3OS15XKA    0.0
31      8002 problem27 partA A1FCLYRBAB430F    0.0
32      8002 problem27 partA A25FZQY34C6RVO    0.0
33      8002 problem27 partA A2IPRDTE6B4TAB    0.0
34      8002 problem27 partA A2U9676210WST5    0.0
35      8002 problem27 partA A3G0MO562MHMZ3    0.0
36      8002 problem27 partB A1FCLYRBAB430F    0.0
37      8002 problem27 partB A1V52SSKROBV8E    2.0
38      8002 problem27 partB A25FZQY34C6RVO    2.0
39      8002 problem27 partB A2IPRDTE6B4TAB    0.0
40      8002 problem27 partB A3G0MO562MHMZ3    0.0
>
> #Make a wrapper
> wrapper <- function ( ratingData, weight.func ) {
+   print(weight.func) #prove that the function is being passed
+   ddply(ratingData, c('studentId','problem','part'), summarize,
+           sum.weights = sum ( weight.func(rating)  ))
+ }
> wrapper( sampleData, weight.func=function(x) (x+.001)^-1  )
function(x) (x+.001)^-1
Error in data.frame(sum.weights = sum(weight.func(rating))) :
  could not find function "weight.func"
>
> #'globally' declare weight.func
> weight.func <- function(x) (x+.001)^-1
> wrapper( sampleData, weight.func=NULL  )
NULL
  studentId   problem  part sum.weights
1      8001 problem26 partA 3002.495758
2      8001 problem26 partB    8.983033
3      8001 problem27 partA 4000.499750
4      8001 problem27 partB 4000.999001
5      8002 problem26 partA 2004.491766
6      8002 problem26 partB 4000.499750
7      8002 problem27 partA 5000.000000
8      8002 problem27 partB 3000.999500

The second output is the goal. Any help appreciated! (Including a non plyr based way to accomplish the same task.)

The example above is a toy example. It's the simplest case I could get to reproduce the behavior.


问:
Why won't my code divide the remaining cents by dimes, nickels, and pennies after it divided by quarters?
```<code>    String choice = "y";
    while(choice.equalsIgnoreCase("y")){
        if (cents <= 99 && cents > 0){
        quarters = cents / quarters;
        System.out.println("Quarters: " + quarters);

        dimes = cents / dimes;
        System.out.println("Dimes: " + dimes);

        nickels = cents / nickels;
        System.out.println("Nickels: " + nickels);

        pennies = cents / pennies;
        System.out.println("Pennies: " + pennies);
</code>```

Do i need to implement a modulus operator after each step?

答:
Ah you have a can't see the wood for the trees problem.

Old school trick this called a dry run

```<code>Cents Quarters Dimes Nickels Pennies Remaining Cents
41    1                              16
16             1                     6
6                       1            1
1                               1    0
</code>```

You are starting from 41 each calculation.

Body:
    String choice = "y";
    while(choice.equalsIgnoreCase("y")){
        if (cents <= 99 && cents > 0){
        quarters = cents / quarters;
        System.out.println("Quarters: " + quarters);

        dimes = cents / dimes;
        System.out.println("Dimes: " + dimes);

        nickels = cents / nickels;
        System.out.println("Nickels: " + nickels);

        pennies = cents / pennies;
        System.out.println("Pennies: " + pennies);

Do i need to implement a modulus operator after each step?

Body:
Ah you have a can't see the wood for the trees problem.

Old school trick this called a dry run

Cents Quarters Dimes Nickels Pennies Remaining Cents
41    1                              16
16             1                     6
6                       1            1
1                               1    0

You are starting from 41 each calculation.


问:
switching from Jquery post requests to modern Promises
I'm working on a web application project with Flask+Python on the back-end, and Javascript on the front-end.  I'd like to take advantage of some of the more modern (ES6/7) styles of things, such as Promises.

I've currently been writing all my javascript using Jquery 3+.  Most of the time I'm making single Ajax requests to the server at a time.  I've been specifically writing my Ajax requests using $.post and .done() and .fail(), which I know is already promise-based, or promise-like.  Most of my code is in the style of

do function setup stuff and checks

make single ajax request

on success

good status, run several success code bits

bad status, run failure code

on failure - run failure code

I always seem to have to account for cases of server failures + cases of server success but it returned the wrong thing, which I usually control with a status argument.  I've been looking into the straight Promise syntax with then, catch, resolve, reject, and I have some questions.

Is there any advantage to me switching to this format, from what I currently have, given my simple Ajax requests?

Can it be used to simplify the way I currently write my requests and handle my failure cases?

Here is a simple login example that I have, with a function that is called when a login button is clicked.

```<code>    $('#loginsubmit').on('click', this, this.login);

    // Login function
    login() {
        const form = $('#loginform').serialize();

      $.post(Flask.url_for('index_page.login'), form, 'json')
          .done((data)=>{
              if (data.result.status < 0) {
                  // bad submit
                  this.resetLogin();
              } else {
                  // good submit
                  if (data.result.message !== ''){
                      const stat = (data.result.status === 0) ? 'danger' : 'success';
                      const htmlstr = `<div class='alert alert-${stat}' role='alert'><h4>${data.result.message}</h4></div>`;
                      $('#loginmessage').html(htmlstr);
                  }
                  if (data.result.status === 1){
                      location.reload(true);
                  }

              }
          })
          .fail((data)=>{ alert('Bad login attempt'); });
    }
</code>```

And a typical more complex example that I have.  In this case, some interactive elements are initialized when a button is toggled on and off.

```<code>    this.togglediv.on('change', this, this.initDynamic);

    // Initialize the Dynamic Interaction upon toggle - makes loading an AJAX request
    initDynamic(event) {

        let _this = event.data;

        if (!_this.togglediv.prop('checked')){
            // Turning Off
            _this.toggleOff();
        } else {
            // Turning On
            _this.toggleOn();

            // check for empty divs
            let specempty = _this.graphdiv.is(':empty');
            let imageempty = _this.imagediv.is(':empty');
            let mapempty = _this.mapdiv.is(':empty');

            // send the request if the dynamic divs are empty
            if (imageempty) {
                // make the form
                let keys = ['plateifu', 'toggleon'];
                let form = m.utils.buildForm(keys, _this.plateifu, _this.toggleon);
                _this.toggleload.show();

                $.post(Flask.url_for('galaxy_page.initdynamic'), form, 'json')
                    .done(function(data) {
                        let image = data.result.image;
                        let spaxel = data.result.spectra;
                        let spectitle = data.result.specmsg;
                        let maps = data.result.maps;
                        let mapmsg = data.result.mapmsg;

                        // Load the Image
                        _this.initOpenLayers(image);
                        _this.toggleload.hide();

                        // Try to load the spaxel
                        if (data.result.specstatus !== -1) {
                            _this.loadSpaxel(spaxel, spectitle);
                        } else {
                            _this.updateSpecMsg(`Error: ${spectitle}`, data.result.specstatus);
                        }

                        // Try to load the Maps
                        if (data.result.mapstatus !== -1) {
                            _this.initHeatmap(maps);
                        } else {
                            _this.updateMapMsg(`Error: ${mapmsg}`, data.result.mapstatus);
                        }

                    })
                    .fail(function(data) {
                        _this.updateSpecMsg(`Error: ${data.result.specmsg}`, data.result.specstatus);
                        _this.updateMapMsg(`Error: ${data.result.mapmsg}`, data.result.mapstatus);
                        _this.toggleload.hide();
                    });
            }
        }
    }
</code>```

I know this is already roughly using promises, but can I make improvements to my code flow by switching to the Promise then catch syntax?  As you can see, I end up repeating a lot of the failure case code for real failures and successful failures.  Most of my code looks like this, but I've been having a bit of trouble trying to convert these into something that's like

```<code>promise_ajax_call
  .then(do real success)
  .catch(all failure cases)
</code>```

答:
I always use Bluebird Promises. They have a Promise.resolve function that you can utilize with ajax. One thing to know about Promises, if you throw an error in a then, it will be caught in a chained catch. One way to clean this up a bit might be something like this (keep in mind, this is pseudo)

```<code>Promise.resolve($.ajax(...some properties..))
    .then((data)=>{
        if(data.result.status < 0){
            //throw some error
        }

        // process the data how you need it
    })
    .catch((error){
        // either the ajax failed, or you threw an error in your then. either way, it will end up in this catch
    });
</code>```

Body:
I'm working on a web application project with Flask+Python on the back-end, and Javascript on the front-end.  I'd like to take advantage of some of the more modern (ES6/7) styles of things, such as Promises.

I've currently been writing all my javascript using Jquery 3+.  Most of the time I'm making single Ajax requests to the server at a time.  I've been specifically writing my Ajax requests using $.post and .done() and .fail(), which I know is already promise-based, or promise-like.  Most of my code is in the style of

do function setup stuff and checks

make single ajax request

on success

good status, run several success code bits

bad status, run failure code

on failure - run failure code

I always seem to have to account for cases of server failures + cases of server success but it returned the wrong thing, which I usually control with a status argument.  I've been looking into the straight Promise syntax with then, catch, resolve, reject, and I have some questions.

Is there any advantage to me switching to this format, from what I currently have, given my simple Ajax requests?

Can it be used to simplify the way I currently write my requests and handle my failure cases?

Here is a simple login example that I have, with a function that is called when a login button is clicked.

    $('#loginsubmit').on('click', this, this.login);

    // Login function
    login() {
        const form = $('#loginform').serialize();

      $.post(Flask.url_for('index_page.login'), form, 'json')
          .done((data)=>{
              if (data.result.status < 0) {
                  // bad submit
                  this.resetLogin();
              } else {
                  // good submit
                  if (data.result.message !== ''){
                      const stat = (data.result.status === 0) ? 'danger' : 'success';
                      const htmlstr = `<div class='alert alert-${stat}' role='alert'><h4>${data.result.message}</h4></div>`;
                      $('#loginmessage').html(htmlstr);
                  }
                  if (data.result.status === 1){
                      location.reload(true);
                  }

              }
          })
          .fail((data)=>{ alert('Bad login attempt'); });
    }

And a typical more complex example that I have.  In this case, some interactive elements are initialized when a button is toggled on and off.

    this.togglediv.on('change', this, this.initDynamic);

    // Initialize the Dynamic Interaction upon toggle - makes loading an AJAX request
    initDynamic(event) {

        let _this = event.data;

        if (!_this.togglediv.prop('checked')){
            // Turning Off
            _this.toggleOff();
        } else {
            // Turning On
            _this.toggleOn();

            // check for empty divs
            let specempty = _this.graphdiv.is(':empty');
            let imageempty = _this.imagediv.is(':empty');
            let mapempty = _this.mapdiv.is(':empty');

            // send the request if the dynamic divs are empty
            if (imageempty) {
                // make the form
                let keys = ['plateifu', 'toggleon'];
                let form = m.utils.buildForm(keys, _this.plateifu, _this.toggleon);
                _this.toggleload.show();

                $.post(Flask.url_for('galaxy_page.initdynamic'), form, 'json')
                    .done(function(data) {
                        let image = data.result.image;
                        let spaxel = data.result.spectra;
                        let spectitle = data.result.specmsg;
                        let maps = data.result.maps;
                        let mapmsg = data.result.mapmsg;

                        // Load the Image
                        _this.initOpenLayers(image);
                        _this.toggleload.hide();

                        // Try to load the spaxel
                        if (data.result.specstatus !== -1) {
                            _this.loadSpaxel(spaxel, spectitle);
                        } else {
                            _this.updateSpecMsg(`Error: ${spectitle}`, data.result.specstatus);
                        }

                        // Try to load the Maps
                        if (data.result.mapstatus !== -1) {
                            _this.initHeatmap(maps);
                        } else {
                            _this.updateMapMsg(`Error: ${mapmsg}`, data.result.mapstatus);
                        }

                    })
                    .fail(function(data) {
                        _this.updateSpecMsg(`Error: ${data.result.specmsg}`, data.result.specstatus);
                        _this.updateMapMsg(`Error: ${data.result.mapmsg}`, data.result.mapstatus);
                        _this.toggleload.hide();
                    });
            }
        }
    }

I know this is already roughly using promises, but can I make improvements to my code flow by switching to the Promise then catch syntax?  As you can see, I end up repeating a lot of the failure case code for real failures and successful failures.  Most of my code looks like this, but I've been having a bit of trouble trying to convert these into something that's like

promise_ajax_call
  .then(do real success)
  .catch(all failure cases)

Body:
I always use Bluebird Promises. They have a Promise.resolve function that you can utilize with ajax. One thing to know about Promises, if you throw an error in a then, it will be caught in a chained catch. One way to clean this up a bit might be something like this (keep in mind, this is pseudo)

Promise.resolve($.ajax(...some properties..))
    .then((data)=>{
        if(data.result.status < 0){
            //throw some error
        }

        // process the data how you need it
    })
    .catch((error){
        // either the ajax failed, or you threw an error in your then. either way, it will end up in this catch
    });


问:
How can I take max id into a TextView?
I'm using sqlite with xamarin. I want to give some kind of query and take max(id) to a TextView. Here is what I'm trying to do:

```<code> string dpPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "student.db3");
 var db = new SQLiteConnection(dpPath);
 db.CreateTable<ExtrasPreviewClass>();

 TextView txtExtrasID = row.FindViewById<TextView>(Resource.Id.txtExtrasID);
        txtExtrasID.Text = Convert.ToString(mitems[position].id);

 var data = db.Table<ExtrasPreviewClass>(); //Call Table

 txtExtrasID.Text = Convert.ToString(db.Query<ExtrasPreviewClass>("select max(_id) from ExtrasPreviewClass "));
</code>```

But my result is something system.collection.list1(ExtrasPreviewClass). How can I manage take max(id) into a TextView?

This is my class:

```<code>class ExtrasPreviewClass
{
    [PrimaryKey, AutoIncrement, Column("_Id")]

    public int id { get; set; }
    public string ExtrasName { get; set; }
    public string ExtrasCheckBox { get; set; }
}
</code>```

答:
What you are seeing is the ToString() representation of the object.

If you want to show something else, you may want to override the method in your ExtrasPreviewClass:

public override string ToString()
{
    return $"Id: {id}, Name {ExtrasName}, CheckBox {ExtrasCheckBox}";
}
```

<p>Or you could simply change your last line from:</p>

<pre class="lang-cs prettyprint-override"><code>txtExtrasID.Text = Convert.ToString(db.Query<ExtrasPreviewClass>("select max(_id) from ExtrasPreviewClass "));
</code>```

to:

var extras = db.Query<ExtrasPreviewClass>("select max(_id) from ExtrasPreviewClass ");
txtExtrasId.Text = extras.id; // or whatever you want to display
```

Title: How can I take max id into a TextView?

Body:
I'm using sqlite with xamarin. I want to give some kind of query and take max(id) to a TextView. Here is what I'm trying to do:

 string dpPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "student.db3");
 var db = new SQLiteConnection(dpPath);
 db.CreateTable<ExtrasPreviewClass>();

 TextView txtExtrasID = row.FindViewById<TextView>(Resource.Id.txtExtrasID);
        txtExtrasID.Text = Convert.ToString(mitems[position].id);

 var data = db.Table<ExtrasPreviewClass>(); //Call Table

 txtExtrasID.Text = Convert.ToString(db.Query<ExtrasPreviewClass>("select max(_id) from ExtrasPreviewClass "));

But my result is something system.collection.list1(ExtrasPreviewClass). How can I manage take max(id) into a TextView?

This is my class:

class ExtrasPreviewClass
{
    [PrimaryKey, AutoIncrement, Column("_Id")]

    public int id { get; set; }
    public string ExtrasName { get; set; }
    public string ExtrasCheckBox { get; set; }
}

Body:
What you are seeing is the ToString() representation of the object.

If you want to show something else, you may want to override the method in your ExtrasPreviewClass:

public override string ToString()
{
    return $"Id: {id}, Name {ExtrasName}, CheckBox {ExtrasCheckBox}";
}

Or you could simply change your last line from:

txtExtrasID.Text = Convert.ToString(db.Query<ExtrasPreviewClass>("select max(_id) from ExtrasPreviewClass "));

to:

var extras = db.Query<ExtrasPreviewClass>("select max(_id) from ExtrasPreviewClass ");
txtExtrasId.Text = extras.id; // or whatever you want to display


答:
Because myString = "world" assigns a new string to the parameter, not updating the existing string. To update the original reference to the string you must pass the parameter with ref.

```<code>public static void TestMethod(ref string myString)
{
    myString = "world";
}

static void Main(string[] args)
{
    string s = "hello";
    Console.WriteLine(s); // output is "hello"
    TestMethod(ref s);
    Console.WriteLine(s); // output is also "hello" not "world" !?
}
</code>```

Title: Changing reference types(strings) inside methods

Body:
I am passing a string variable to a method. I know strings are reference types but the value that I assign inside the method is lost.

public static void TestMethod(string myString)
{
    myString = "world";
}

static void Main(string[] args)
{
    string s = "hello";
    Console.WriteLine(s); // output is "hello"
    TestMethod(s);
    Console.WriteLine(s); // output is also "hello" not "world" !?
}

Anyway this does not happen with an array for example. Can someone explain why might be the cause?

Body:
Because myString = "world" assigns a new string to the parameter, not updating the existing string. To update the original reference to the string you must pass the parameter with ref.

public static void TestMethod(ref string myString)
{
    myString = "world";
}

static void Main(string[] args)
{
    string s = "hello";
    Console.WriteLine(s); // output is "hello"
    TestMethod(ref s);
    Console.WriteLine(s); // output is also "hello" not "world" !?
}


问:
Codeigniter login system issue loging
I got a table "usuarios" which contains the following information:

(id, username, name, lastname, password, type, status, date), right?

Take a look:

My personal goal is to make a login system which allows me to clasify those WHO are ADMIN from those who are just simple users... I mean, if a row of the table contains type = 0 it is an ADMIN and if type = 1 it is a simple user.
So,in the login system if i write for example ADMIN 1234 and this data corresponds to an ADMIN user from the table "users"; when i press "login" it must open an exclusive page only for ADMINs.. The same but for those who are "simple" users.

The system must validate if i write wrongs usernames/passwords and if the username corresponds to an active member (status = 1 active, status = 0 not active). No empty fields while login

No matter what i write in "username" and "password" in the login system.. when i click on "login" i always get this message and nothing happens:

And these are the users registered in my database:

Here is my code:
Controller files (2 files: "dashboard" and "login")
Dashboard:

```<code>    <?php

        Class dashboard extends CI_Controller{

         public function __construct(){
             parent::__construct();
             $this->load->model('m_login');
         $this->auth->cek_auth();

        }

        public function index(){
            $ambil_akun = $this->m_login->ambil_user($this->session->userdata('usuario'));
            $data = array(

              'user' =>$ambil_akun,

              );

            $stat = $this->session->userdata('lvl');
            if($stat=='s_admin'){
              $this->load->view('dashboard_admin', $data);

            }else{

              $this->load->view('dashboard_user', $data);

            }

        }

  public function login(){

    $session = $this->session->userdata('isLogin');
    if($session == FALSE)
    {

      $this->load->view('login_form');

    }else
    {

      redirect('dashboard');

    }

  }

  public function logout(){

    $this->session->sess_destroy();
    redirect('login', 'refresh');

  }

}

?>
</code>```

Login:

```<code>    <?php

        Class Login extends CI_Controller{

        public function __construct(){
             parent::__construct();
             $this->load->model("m_login");

        }

        public function index(){
            $session = $this->session->userdata('isLogin');
            if($session == FALSE)
            {

                $this->load->view('login_form');

            }else
            {

                redirect('dashboard');

            }

        }

        public function do_login()
        {

            $usuario=$this->input->post('uname');
            $contrasena=$this->input->post('pass');

            $cek=$this->m_login->cek_user($contrasena, md5($contrasena));
            if(count($cek) == 1){

                foreach ($cek as $cek) {

                    $tipo=$cek['tipo'];
                    $estado=$cek['estado'];
                    $nombre=$cek['nombre'];

                }

                if($estado =='0'){

                    $this->session->set_userdata(array(

                        'isLogin'=>TRUE,
                        'uname'=>$usuario,
                        'lvl'=>$tipo,
                        'estado'=>$estado

                    ));
                    redirect('dashboard', 'refresh');

                }
                else{

                    echo "<script>alert('YOUR ACCOUNT IS NOT ACTIVE')</script>";
                    redirect('login','refresh');

                }

                }else{

                    echo "<script>alert('USERNAME OR PASSWORD INVALID!')</script>";
                    redirect('login','refresh');

                }

}

}

?>
</code>```

The model file (m_login):

```<code>    <?php

    class m_login extends CI_Model{

        public function __construct(){

         parent::__construct();
         $this->tbl="usuarios";

        }

    public function cek_user($usuario="", $contrasena="")
    {

        $query=$this->db->get_where($this->tbl, array('usuario'=>$usuario, 'contrasena'=>$contrasena));
        $query=$query->result_array();
        return $query;
    }

    public function ambil_user($nombre)
    {

        $query=$this->db->get_where($this->tbl, array('nombre'=> $nombre));
        $query=$query->result_array();
        if(query){

            return $query[0];

        }

    }

}

?>
</code>```

And my view files:
login_form:

```<code>    <!DOCTYPE html>
<html lang="">

    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

    </head>

        <body>
            <div class="container">
            <h3>Login</h3>
            <hr>
            <form action="<?php echo base_url('login/do_login')?>" method="POST">
                <div class="form-group">
                    <label for="cari">USERNAME</label>
                    <input type="text" name="usuario" id="usuario" class="form-control"><?php echo form_error('usuario');?>

                </div>

                <div class="form-group">
                    <label for="cari">PASSWORD</label>
                    <input type="password" name="contrasena" id="contrasena" class="form-control"><?php echo form_error('contrasena');?>

                </div>

                <input class="btn btn-primary" type="submit" value="Login">
                <input class="btn btn-primary" type="reset" value="Reset">

            </form>
                </div>

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

dashboard_admin:

```<code>Hi!<b><?php echo $user['nombre'];?></b>YOU ARE AN ADMINISTRATOR! > [<a href= '<?php echo base_url('dashboard/logout');?>'>LOGOUT</a>]
</code>```

dashboard_user:

```<code>Hi!<b><?php echo $user['nombre'];?></b>YOU ARE A SIMPLE USER! > [<a href= '<?php echo base_url('dashboard/logout');?>'>LOGOUT</a>]
</code>```

Dont know what to do now :/

答:
in this code, you encrypt password. But on db, its not encrypted with md5 ?
Maybe sending without md5 will solve your problem for now. But i think also encrypt with md5 good selection.</p>

```<code>$cek=$this->m_login->cek_user($contrasena, $contrasena); // change like this.
</code>```

Title: Codeigniter login system issue loging

Body:
I got a table "usuarios" which contains the following information:

(id, username, name, lastname, password, type, status, date), right?

Take a look:

My personal goal is to make a login system which allows me to clasify those WHO are ADMIN from those who are just simple users... I mean, if a row of the table contains type = 0 it is an ADMIN and if type = 1 it is a simple user.
So,in the login system if i write for example ADMIN 1234 and this data corresponds to an ADMIN user from the table "users"; when i press "login" it must open an exclusive page only for ADMINs.. The same but for those who are "simple" users.

The system must validate if i write wrongs usernames/passwords and if the username corresponds to an active member (status = 1 active, status = 0 not active). No empty fields while login

No matter what i write in "username" and "password" in the login system.. when i click on "login" i always get this message and nothing happens:

And these are the users registered in my database:

Here is my code:
Controller files (2 files: "dashboard" and "login")
Dashboard:

    <?php

        Class dashboard extends CI_Controller{

         public function __construct(){
             parent::__construct();
             $this->load->model('m_login');
         $this->auth->cek_auth();

        }

        public function index(){
            $ambil_akun = $this->m_login->ambil_user($this->session->userdata('usuario'));
            $data = array(

              'user' =>$ambil_akun,

              );

            $stat = $this->session->userdata('lvl');
            if($stat=='s_admin'){
              $this->load->view('dashboard_admin', $data);

            }else{

              $this->load->view('dashboard_user', $data);

            }

        }

  public function login(){

    $session = $this->session->userdata('isLogin');
    if($session == FALSE)
    {

      $this->load->view('login_form');

    }else
    {

      redirect('dashboard');

    }

  }

  public function logout(){

    $this->session->sess_destroy();
    redirect('login', 'refresh');

  }

}

?>

Login:

    <?php

        Class Login extends CI_Controller{

        public function __construct(){
             parent::__construct();
             $this->load->model("m_login");

        }

        public function index(){
            $session = $this->session->userdata('isLogin');
            if($session == FALSE)
            {

                $this->load->view('login_form');

            }else
            {

                redirect('dashboard');

            }

        }

        public function do_login()
        {

            $usuario=$this->input->post('uname');
            $contrasena=$this->input->post('pass');

            $cek=$this->m_login->cek_user($contrasena, md5($contrasena));
            if(count($cek) == 1){

                foreach ($cek as $cek) {

                    $tipo=$cek['tipo'];
                    $estado=$cek['estado'];
                    $nombre=$cek['nombre'];

                }

                if($estado =='0'){

                    $this->session->set_userdata(array(

                        'isLogin'=>TRUE,
                        'uname'=>$usuario,
                        'lvl'=>$tipo,
                        'estado'=>$estado

                    ));
                    redirect('dashboard', 'refresh');

                }
                else{

                    echo "";
                    redirect('login','refresh');

                }

                }else{

                    echo "";
                    redirect('login','refresh');

                }

}

}

?>

The model file (m_login):

    <?php

    class m_login extends CI_Model{

        public function __construct(){

         parent::__construct();
         $this->tbl="usuarios";

        }

    public function cek_user($usuario="", $contrasena="")
    {

        $query=$this->db->get_where($this->tbl, array('usuario'=>$usuario, 'contrasena'=>$contrasena));
        $query=$query->result_array();
        return $query;
    }

    public function ambil_user($nombre)
    {

        $query=$this->db->get_where($this->tbl, array('nombre'=> $nombre));
        $query=$query->result_array();
        if(query){

            return $query[0];

        }

    }

}

?>

And my view files:
login_form:

    <!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">

Login

            <form action="<?php echo base_url('login/do_login')?>" method="POST">

                    USERNAME
                    <input type="text" name="usuario" id="usuario" class="form-control"><?php echo form_error('usuario');?>

                    PASSWORD
                    <input type="password" name="contrasena" id="contrasena" class="form-control"><?php echo form_error('contrasena');?>

                <input class="btn btn-primary" type="submit" value="Login">
                <input class="btn btn-primary" type="reset" value="Reset">

            </form>

dashboard_admin:

Hi!<?php echo $user['nombre'];?>YOU ARE AN ADMINISTRATOR! > [<a href= '<?php echo base_url('dashboard/logout');?>'>LOGOUT]

dashboard_user:

Hi!<?php echo $user['nombre'];?>YOU ARE A SIMPLE USER! > [<a href= '<?php echo base_url('dashboard/logout');?>'>LOGOUT]

Dont know what to do now :/

Body:
in this code, you encrypt password. But on db, its not encrypted with md5 ?
Maybe sending without md5 will solve your problem for now. But i think also encrypt with md5 good selection.

$cek=$this->m_login->cek_user($contrasena, $contrasena); // change like this.


问:
How do I chain three asynchronous calls using jQuery promises?
I have three HTTP calls that need I need to make in a synchronous manner and how do I pass data from one call to the other?

```<code>function first()
{
   ajax()
}

function second()
{
   ajax()
}

function third()
{
   ajax()
}

function main()
{
    first().then(second).then(third)
}
</code>```

I tried to use the deferred for the two functions and I came up with a partial solution. Can I extend  it to be for three functions?

```<code>function first() {
    var deferred = $.Deferred();
     $.ajax({

             "success": function (resp)
             {

                 deferred.resolve(resp);
             },

         });
    return deferred.promise();
}

function second(foo) {
     $.ajax({
            "success": function (resp)
            {
            },
            "error": function (resp)
            {
            }
        });
}

first().then(function(foo){second(foo)})
</code>```

答:
Quite late to reply, but I guess answers are missing some straight forward code for chaining. Chaining events is pretty simple with promise support in jquery. I use the following for chaining:

```<code>$.ajax()
.then(function(){
   return $.ajax() //second ajax call
})
.then(function(){
   return $.ajax() //third ajax call
})
.done(function(resp){
   //handle final response here
 })
</code>```

It's simple with no complicated for loops or multiple nested callbacks.

Body:
I have three HTTP calls that need I need to make in a synchronous manner and how do I pass data from one call to the other?

function first()
{
   ajax()
}

function second()
{
   ajax()
}

function third()
{
   ajax()
}

function main()
{
    first().then(second).then(third)
}

I tried to use the deferred for the two functions and I came up with a partial solution. Can I extend  it to be for three functions?

function first() {
    var deferred = $.Deferred();
     $.ajax({

             "success": function (resp)
             {

                 deferred.resolve(resp);
             },

         });
    return deferred.promise();
}

function second(foo) {
     $.ajax({
            "success": function (resp)
            {
            },
            "error": function (resp)
            {
            }
        });
}

first().then(function(foo){second(foo)})

Body:
Quite late to reply, but I guess answers are missing some straight forward code for chaining. Chaining events is pretty simple with promise support in jquery. I use the following for chaining:

$.ajax()
.then(function(){
   return $.ajax() //second ajax call
})
.then(function(){
   return $.ajax() //third ajax call
})
.done(function(resp){
   //handle final response here
 })

It's simple with no complicated for loops or multiple nested callbacks.

ContentLicense: CC BY-SA 4.0


问:
Make sure that `gem install pg -v '0.18.4'` succeeds before bundling
I get the below error when I execute bundle update:

To see why this extension failed to compile, please check the mkmf.log which can

  be found here:

/Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in

  /Users/jack/.rvm/gems/ruby-2.3.3/gems/pg-0.18.4 for inspection.
  Results logged to

  /Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/gem_make.out

An error occurred while installing pg (0.18.4), and Bundler cannot
  continue.

  Make sure that gem install pg -v '0.18.4' succeeds before bundling.

I don't know why I get this issue. And I execute the gem install pg -v '0.18.4':

To see why this extension failed to compile, please check the mkmf.log which can be found here:

/Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /Users/jack/.rvm/gems/ruby-2.3.3/gems/pg-0.18.4 for inspection.
  Results logged to /Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/gem_make.out

My Gemfile is this:

```<code>source 'https://gems.ruby-china.org'
gem 'rails', '5.0.0.1'
gem 'puma', '3.4.0'
gem 'sass-rails', '5.0.6'
gem 'uglifier', '3.0.0'
gem 'coffee-rails', '4.2.1'
gem 'jquery-rails', '4.1.1'
gem 'turbolinks', '5.0.1'
gem 'jbuilder', '2.4.1'

group :development, :test do
gem 'sqlite3', '1.3.11'
gem 'byebug', '9.0.0', platform: :mri
end

group :development do
  gem 'web-console', '3.1.1'
  gem 'listen', '3.0.8'
  gem 'spring', '1.7.2'
  gem 'spring-watcher-listen', '2.0.0'

end
group :production do gem 'pg', '0.18.4'
end
    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
</code>```

Edit -1

My OS is macOS Sierra

答:
I had a similar problem and this is what worked for me:

(Note: First make sure you've got XCode and homebrew installed)

brew install postgresql

gem uninstall pg - this might not return anything, that's ok.

Then in your app's directory, either bundle install or gem install pg

Body:
I get the below error when I execute bundle update:

To see why this extension failed to compile, please check the mkmf.log which can

  be found here:

/Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in

  /Users/jack/.rvm/gems/ruby-2.3.3/gems/pg-0.18.4 for inspection.
  Results logged to

  /Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/gem_make.out

An error occurred while installing pg (0.18.4), and Bundler cannot
  continue.

  Make sure that gem install pg -v '0.18.4' succeeds before bundling.

I don't know why I get this issue. And I execute the gem install pg -v '0.18.4':

To see why this extension failed to compile, please check the mkmf.log which can be found here:

/Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /Users/jack/.rvm/gems/ruby-2.3.3/gems/pg-0.18.4 for inspection.
  Results logged to /Users/jack/.rvm/gems/ruby-2.3.3/extensions/x86_64-darwin-16/2.3.0/pg-0.18.4/gem_make.out

My Gemfile is this:

source 'https://gems.ruby-china.org'
gem 'rails', '5.0.0.1'
gem 'puma', '3.4.0'
gem 'sass-rails', '5.0.6'
gem 'uglifier', '3.0.0'
gem 'coffee-rails', '4.2.1'
gem 'jquery-rails', '4.1.1'
gem 'turbolinks', '5.0.1'
gem 'jbuilder', '2.4.1'

group :development, :test do
gem 'sqlite3', '1.3.11'
gem 'byebug', '9.0.0', platform: :mri
end

group :development do
  gem 'web-console', '3.1.1'
  gem 'listen', '3.0.8'
  gem 'spring', '1.7.2'
  gem 'spring-watcher-listen', '2.0.0'

end
group :production do gem 'pg', '0.18.4'
end
    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Edit -1

My OS is macOS Sierra


问:
“%%” on a vector with non-numeric and numeric values
I have a Feature Vector fv with Numeric and Non-numeric features

```<code>fv <- c(22, 72, "San Jose", 60)
</code>```

I need to replace values that are divisible by 3 with a String

```<code>fv[fv%%3==0] <- "Negligible"
</code>```

However I get the following error message:

```<code>Error in fv%%3 : non-numeric argument to binary operator
</code>```

Due to the "San Jose" Feature in the Feature Vector.

How can I ignore the non-numerics in

```<code>fv[fv%%3==0] <- "Negligible"
</code>```

?

答:
Try this:

```<code>fv[as.numeric(fv)%%3==0] <- "Negligible"
#[1] "22"         "Negligible" "San Jose"   "Negligible"
</code>```

A warning will be triggered which is OK due to NA introduced by the string in the vector.

Body:
I have a Feature Vector fv with Numeric and Non-numeric features

fv <- c(22, 72, "San Jose", 60)

I need to replace values that are divisible by 3 with a String

fv[fv%%3==0] <- "Negligible"

However I get the following error message:

Error in fv%%3 : non-numeric argument to binary operator

Due to the "San Jose" Feature in the Feature Vector.

How can I ignore the non-numerics in

fv[fv%%3==0] <- "Negligible"

?

Body:
Try this:

fv[as.numeric(fv)%%3==0] <- "Negligible"
#[1] "22"         "Negligible" "San Jose"   "Negligible"

A warning will be triggered which is OK due to NA introduced by the string in the vector.


问:
How to use foreach in SWI-Prolog
I want to convert a list of pairs to two lists – first containing first elements of the pairs, second containing second elements of the pairs.

E.g.

```<code>[['Test1', 'US'], ['Test1', 'France'], ['Test2', 'German']]
</code>```

should produce

```<code>List1 = ['Test1', 'Test1', 'Test2']
List2 = ['US', 'France', 'German']
</code>```

I tried to use foreach and come up with this function:

```<code>testfor:-
List = [['Test1', 'US'], ['Test1', 'France'], ['Test2', 'German']],
(
  foreach(X,List) do
    X=[F,S],
    append([F],[],List1),
    append([S],[],List2)
),
writeln(List1).
</code>```

It doesn't work, I am confused. Where did I make a mistake? Of course, you can help me implement this function using your method (i.e. "don't use foreach").

答:
Using maplist/4, the whole iteration is hidden and you have to think just about the deconstruction of a single pair.

```<code>%zip(?FirstList, ?SecondList, ?PairList)
zip(Fst, Snd, Pair) :- maplist(pair, Fst, Snd, Pair).

%pair(?First, ?Second, ?Pair)
pair(Fst, Snd, [Fst, Snd]).
</code>```

Use it thus:

```<code>?- zip(List1, List2, [['Test1', 'US'], ['Test1', 'France'], ['Test2', 'German']]).
List1 = ['Test1', 'Test1', 'Test2'],
List2 = ['US', 'France', 'German'].
</code>```

Note that this is an advanced solution, though. First, getting to know the basic recursive solutions (presented by other answers) is really useful and I recommend it. Without a good grasp of recursion, Prolog is just one big hell. Actually, maplist uses recursion too, it is just hidden from the caller.

Another thing to learn is how Prolog terms and unification work.

Using append is completely unnecessary here. Moreover, it is harmful both performance-wise and readability-wise.

Pairs are better represented using a functor, e.g. pair ['Test1', 'US'] becomes pair('Test1', 'US'). Among other benefits, it is harder to accidentally mix up pairs and triplets. Using functors is somewhat similar to using types in other languages.

SWI-Prolog uses hyphen-minus as the functor for pairs. Due to having an operator declaration, hyphen-minus can be used in infix notation, too. E.g. pair ['Test1', 'US'] becomes 'Test1'-'US'. Infix notation is just syntactic sugar for the usual prefix notation used for other functors (i.e. 'Test1'-'US' == -('Test1', 'US')).

Finally, the foreach ... do notation you tried to use looks like a loop construct from ECLiPSe, which is a language derived from Prolog. SWI-Prolog does not support this syntax.

Title: How to use foreach in SWI-Prolog

Body:
I want to convert a list of pairs to two lists – first containing first elements of the pairs, second containing second elements of the pairs.

E.g.

[['Test1', 'US'], ['Test1', 'France'], ['Test2', 'German']]

should produce

List1 = ['Test1', 'Test1', 'Test2']
List2 = ['US', 'France', 'German']

I tried to use foreach and come up with this function:

testfor:-
List = [['Test1', 'US'], ['Test1', 'France'], ['Test2', 'German']],
(
  foreach(X,List) do
    X=[F,S],
    append([F],[],List1),
    append([S],[],List2)
),
writeln(List1).

It doesn't work, I am confused. Where did I make a mistake? Of course, you can help me implement this function using your method (i.e. "don't use foreach").

Body:
Using maplist/4, the whole iteration is hidden and you have to think just about the deconstruction of a single pair.

%zip(?FirstList, ?SecondList, ?PairList)
zip(Fst, Snd, Pair) :- maplist(pair, Fst, Snd, Pair).

%pair(?First, ?Second, ?Pair)
pair(Fst, Snd, [Fst, Snd]).

Use it thus:

?- zip(List1, List2, [['Test1', 'US'], ['Test1', 'France'], ['Test2', 'German']]).
List1 = ['Test1', 'Test1', 'Test2'],
List2 = ['US', 'France', 'German'].

Note that this is an advanced solution, though. First, getting to know the basic recursive solutions (presented by other answers) is really useful and I recommend it. Without a good grasp of recursion, Prolog is just one big hell. Actually, maplist uses recursion too, it is just hidden from the caller.

Another thing to learn is how Prolog terms and unification work.

Using append is completely unnecessary here. Moreover, it is harmful both performance-wise and readability-wise.

Pairs are better represented using a functor, e.g. pair ['Test1', 'US'] becomes pair('Test1', 'US'). Among other benefits, it is harder to accidentally mix up pairs and triplets. Using functors is somewhat similar to using types in other languages.

SWI-Prolog uses hyphen-minus as the functor for pairs. Due to having an operator declaration, hyphen-minus can be used in infix notation, too. E.g. pair ['Test1', 'US'] becomes 'Test1'-'US'. Infix notation is just syntactic sugar for the usual prefix notation used for other functors (i.e. 'Test1'-'US' == -('Test1', 'US')).

Finally, the foreach ... do notation you tried to use looks like a loop construct from ECLiPSe, which is a language derived from Prolog. SWI-Prolog does not support this syntax.


问:
SDL2 - Window cannot be reopened
I am writing a simple SDL2 application with 2 windows.

The first window (window variable) is shown when the application starts, the second one (window2 variable) is hidden.

Expected behavior:

I click on the first window, the second window pops up, then I close the second window.

And I can close and reopen the window as much as I want.

Observed behavior:

Once I close the second window, if I reclick in the first window, the second window doesn't appear as expected.

As stated in my comment: the window doesn't appear in my window manager (i.e. Wayland).

The code:

```<code>#include <SDL2/SDL.h>

int main()
{
    SDL_Window* window, *window2 = NULL;

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        return 1;
    } else {
        window = SDL_CreateWindow("ONE", SDL_WINDOWPOS_UNDEFINED,
                     SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
        window2 = SDL_CreateWindow("TWO", SDL_WINDOWPOS_UNDEFINED,
                      SDL_WINDOWPOS_UNDEFINED, 320, 240, SDL_WINDOW_HIDDEN);

        if (window == NULL || window2 == NULL) {
            SDL_DestroyWindow(window);
            SDL_DestroyWindow(window2);
            return 1;
        }

        bool running = true;

        while(running) {
            SDL_Event event;
            while (SDL_PollEvent(&event)) {
                if (event.type == SDL_WINDOWEVENT) {
                    if (event.window.event == SDL_WINDOWEVENT_CLOSE) {
                        if (SDL_GetWindowID(window) == event.window.windowID) {
                            running = false;
                        } else {
                            SDL_HideWindow(window2);
                        }
                    }
                } else if (event.type == SDL_MOUSEBUTTONDOWN) {
                    SDL_ShowWindow(window2);
                }
            }
        }
    }

    SDL_DestroyWindow(window);
    SDL_DestroyWindow(window2);

    SDL_Quit();

    return 0;
}
</code>```

答:
You should call SDL_RaiseWindow to place the second window on top of the other.
From lazyfoo's legendary SDL tutorials:</p>

```<code>void LWindow::focus()
{
//Restore window if needed
if( !mShown )
    SDL_ShowWindow( mWindow );

//Move window forward
SDL_RaiseWindow( mWindow );
}
</code>```

Title: SDL2 - Window cannot be reopened

Body:
I am writing a simple SDL2 application with 2 windows.

The first window (window variable) is shown when the application starts, the second one (window2 variable) is hidden.

Expected behavior:

I click on the first window, the second window pops up, then I close the second window.

And I can close and reopen the window as much as I want.

Observed behavior:

Once I close the second window, if I reclick in the first window, the second window doesn't appear as expected.

As stated in my comment: the window doesn't appear in my window manager (i.e. Wayland).

The code:

#include <SDL2/SDL.h>

int main()
{
    SDL_Window* window, *window2 = NULL;

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        return 1;
    } else {
        window = SDL_CreateWindow("ONE", SDL_WINDOWPOS_UNDEFINED,
                     SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
        window2 = SDL_CreateWindow("TWO", SDL_WINDOWPOS_UNDEFINED,
                      SDL_WINDOWPOS_UNDEFINED, 320, 240, SDL_WINDOW_HIDDEN);

        if (window == NULL || window2 == NULL) {
            SDL_DestroyWindow(window);
            SDL_DestroyWindow(window2);
            return 1;
        }

        bool running = true;

        while(running) {
            SDL_Event event;
            while (SDL_PollEvent(&event)) {
                if (event.type == SDL_WINDOWEVENT) {
                    if (event.window.event == SDL_WINDOWEVENT_CLOSE) {
                        if (SDL_GetWindowID(window) == event.window.windowID) {
                            running = false;
                        } else {
                            SDL_HideWindow(window2);
                        }
                    }
                } else if (event.type == SDL_MOUSEBUTTONDOWN) {
                    SDL_ShowWindow(window2);
                }
            }
        }
    }

    SDL_DestroyWindow(window);
    SDL_DestroyWindow(window2);

    SDL_Quit();

    return 0;
}

Body:
You should call SDL_RaiseWindow to place the second window on top of the other.
From lazyfoo's legendary SDL tutorials:

void LWindow::focus()
{
//Restore window if needed
if( !mShown )
    SDL_ShowWindow( mWindow );

//Move window forward
SDL_RaiseWindow( mWindow );
}


问:
Access file sharing
I have a nicely designed access database, complete with layed out forms and macros behind many buttons that filter through search boxes and do many other functions.

My problem is that I am sending this database to multiple people who want to add new records, however when they give me back their edited database (now with new records", i cant import them, because another person who has also handed me their edited version of the database needs their records added and access doesnt allow me to import these records because unique ID's have been created by both people and clash when i try to import them both in.

I have tried some websites that claim to import my database and allow cloud editing, however i lose all the functionality and layout of my forms / macros as the websites dont support it.

What would be the best solution so that i can get multiple people adding new records at the same time? Are there any websites that offer this? Or is there a way inside access to reassign the Unique ID's if they are already in the system?

答: Set the field size of your AutoNumber ID fields to Replication ID instead of Long Integer. It is extremely unlikely that two users will create records with the same ID.

Title: Access file sharing


问:
Libgdx - About 2 player game. I want each player can touch his own area with one finger
I am creating 2 players game where each player has his own area. I want each player can touch his own area with one finger. So first I limit to "2 pointers" in the "touchdown" function.

```<code>public boolean touchDown(int screenX, int screenY, int pointer, int button){
    if(pointer > 1){
        return false;
    }
    Gdx.app.log("", "pointer: "+pointer);

    return false;
}
</code>```

But the problem is if one player touch his own area with his 2 fingers another player won't be able to touch his own area. How can I resolve this problem ? Thank you.

答:
You shouldn't reject based on the pointer number.

If you want to allow the first pointer down on each side of the screen, you could do something like this (untested):

```<code>private int player1Pointer = -1, player2Pointer = -1;
private int player1X, player1Y, player2X, player2Y;

//...

public boolean touchDown(int screenX, int screenY, int pointer, int button){

    // Assuming top and bottom halves of screen:
    if (screenY > Gdx.graphics.getHeight() / 2){ // player 1 side
        if (player1Pointer >= 0) // player 1 already touching somewhere
            return false;
        player1Pointer = pointer;
        player1X = screenX;
        player1Y = screenY;
    } else { //player 2 side
        if (player2Pointer >= 0) // player 2 already touching somewhere
            return false;
        player2Pointer = pointer;
        player2X = screenX;
        player2Y = screenY;
    }
    return true;
}

public boolean touchDragged (int screenX, int screenY, int pointer) {
    if (pointer == player1Pointer){
        player1X = screenX;
        player1Y = screenY;
        return true;
    }
    if (pointer == player2Pointer){
        player2X = screenX;
        player2Y = screenY;
        return true;
    }
    return false;
}

public boolean touchUp (int screenX, int screenY, int pointer, int button) {
    if (pointer == player1Pointer){
        player1Pointer = -1;
        return true;
    }
    if (pointer == player2Pointer){
        player2Pointer = -1;
        return true;
    }
    return false;
}
</code>```

Body:
I am creating 2 players game where each player has his own area. I want each player can touch his own area with one finger. So first I limit to "2 pointers" in the "touchdown" function.

public boolean touchDown(int screenX, int screenY, int pointer, int button){
    if(pointer > 1){
        return false;
    }
    Gdx.app.log("", "pointer: "+pointer);

    return false;
}

But the problem is if one player touch his own area with his 2 fingers another player won't be able to touch his own area. How can I resolve this problem ? Thank you.

Body:
You shouldn't reject based on the pointer number.

If you want to allow the first pointer down on each side of the screen, you could do something like this (untested):

private int player1Pointer = -1, player2Pointer = -1;
private int player1X, player1Y, player2X, player2Y;

//...

public boolean touchDown(int screenX, int screenY, int pointer, int button){

    // Assuming top and bottom halves of screen:
    if (screenY > Gdx.graphics.getHeight() / 2){ // player 1 side
        if (player1Pointer >= 0) // player 1 already touching somewhere
            return false;
        player1Pointer = pointer;
        player1X = screenX;
        player1Y = screenY;
    } else { //player 2 side
        if (player2Pointer >= 0) // player 2 already touching somewhere
            return false;
        player2Pointer = pointer;
        player2X = screenX;
        player2Y = screenY;
    }
    return true;
}

public boolean touchDragged (int screenX, int screenY, int pointer) {
    if (pointer == player1Pointer){
        player1X = screenX;
        player1Y = screenY;
        return true;
    }
    if (pointer == player2Pointer){
        player2X = screenX;
        player2Y = screenY;
        return true;
    }
    return false;
}

public boolean touchUp (int screenX, int screenY, int pointer, int button) {
    if (pointer == player1Pointer){
        player1Pointer = -1;
        return true;
    }
    if (pointer == player2Pointer){
        player2Pointer = -1;
        return true;
    }
    return false;
}


问:
Eclipse is not showing compilation errors in project explorer
I am using Eclipse Juno with Java 1.7 and i have created a test project. Now the problem is with project explorer. Project explorer is not showing compilation errors if class have any error.
I cleaned, closed , and rebuild the project but nothing is changed. It is still not showing errors in project explorer.It was working fine with Helios.

答:
In eclipse you can right-click on a project and go Maven-->Update Maven
Project and this will tell eclipse to update all of its local project
settings (e.g. source and build paths) based upon the current pom.xml. </p>


问:
storing data with header in csv in python
I am trying to store some data in csv file. I am able to store data but it looks like this

```<code>1901,1909,1911,1913,1917
5,5,5,4,6
</code>```

the first row is year names and second row is values.
my code is as follow

```<code>import os
import csv
from collections import Counter
from csv import reader

def read_data(filename):
    year = 3
    with open(filename) as f:
        next(f, None)  # discard header
        year2rel = Counter(int(line[YEAR]) for line in reader(f))
        return year2rel

file_exists = os.path.isfile('mycsvfile.csv')
def store_data(value):
    my_dict = read_data(filename)
    print 'my_dict: ', my_dict
    with open('mycsvfile.csv', 'wb') as f:
        w = csv.DictWriter(f, my_dict.keys())
        if not file_exists:
            w.writeheader()
        print 'w: ', w
        w.writerow(my_dict)

if __name__ == '__main__':
    filename = '/home/rob/songs_detail.csv'
    a = read_songs(filename)
    b = store_data(a)
</code>```

but I want to include headers so that it looks like

```<code>year values
1901 5
1909 5
1911 5
1913 4
1917 6
</code>```

I tried to change my code but it doesn't work for me well. I tried something like below but unsuccessful. thanks for any tip or help.

```<code>def store_data(value):
    file_exists = os.path.isfile('mycsvfile.csv')
    my_dict = read_data(filename)
    print 'my_dict: ', my_dict
    with open('mycsvfile.csv', 'wb') as csvfile:
        headers = ['year', 'values']
        writer = csv.DictWriter(csvfile, delimiter=',', lineterminator='\n',fieldnames=headers)
        if not file_exists:
            writer.writeheader()  # file doesn't exist yet, write a header

        writer.writerow({'year': my_dict[0], 'values': my_dict[1]})
</code>```

this give me the following error.

```<code>'ValueError: dict contains fields not in fieldnames: 'values', 'year'
</code>```

'

答:
I solve my question and the code is as follow, might be helpful for someone. </p>

```<code>def store_data(value):
    file_exists = os.path.isfile('mycsvfile.csv')
    my_dict = read_data(filename)
    print 'my_dict: ', my_dict
    print 'type of: ', type(my_dict)
    with open('mycsvfile.csv', 'wb') as csvfile:
        headers = ['year', 'values']
        writer = csv.DictWriter(csvfile, delimiter=',', lineterminator='\n',fieldnames=headers)
        if not file_exists:
            writer.writeheader()
        for k, v in my_dict.items():
            print(k, v)
            writer.writerow({'year': k, 'values': v})
</code>```

<p>Actually I was missing to add loop in the proper way, so it results always in the csv file without headers. now it works perfectly fine according to my requirements. </p>

Body:
I am trying to store some data in csv file. I am able to store data but it looks like this

1901,1909,1911,1913,1917
5,5,5,4,6

the first row is year names and second row is values.
my code is as follow

import os
import csv
from collections import Counter
from csv import reader

def read_data(filename):
    year = 3
    with open(filename) as f:
        next(f, None)  # discard header
        year2rel = Counter(int(line[YEAR]) for line in reader(f))
        return year2rel

file_exists = os.path.isfile('mycsvfile.csv')
def store_data(value):
    my_dict = read_data(filename)
    print 'my_dict: ', my_dict
    with open('mycsvfile.csv', 'wb') as f:
        w = csv.DictWriter(f, my_dict.keys())
        if not file_exists:
            w.writeheader()
        print 'w: ', w
        w.writerow(my_dict)

if __name__ == '__main__':
    filename = '/home/rob/songs_detail.csv'
    a = read_songs(filename)
    b = store_data(a)

but I want to include headers so that it looks like

year values
1901 5
1909 5
1911 5
1913 4
1917 6

I tried to change my code but it doesn't work for me well. I tried something like below but unsuccessful. thanks for any tip or help.

def store_data(value):
    file_exists = os.path.isfile('mycsvfile.csv')
    my_dict = read_data(filename)
    print 'my_dict: ', my_dict
    with open('mycsvfile.csv', 'wb') as csvfile:
        headers = ['year', 'values']
        writer = csv.DictWriter(csvfile, delimiter=',', lineterminator='\n',fieldnames=headers)
        if not file_exists:
            writer.writeheader()  # file doesn't exist yet, write a header

        writer.writerow({'year': my_dict[0], 'values': my_dict[1]})

this give me the following error.

'ValueError: dict contains fields not in fieldnames: 'values', 'year'

'

Body:
I solve my question and the code is as follow, might be helpful for someone.

def store_data(value):
    file_exists = os.path.isfile('mycsvfile.csv')
    my_dict = read_data(filename)
    print 'my_dict: ', my_dict
    print 'type of: ', type(my_dict)
    with open('mycsvfile.csv', 'wb') as csvfile:
        headers = ['year', 'values']
        writer = csv.DictWriter(csvfile, delimiter=',', lineterminator='\n',fieldnames=headers)
        if not file_exists:
            writer.writeheader()
        for k, v in my_dict.items():
            print(k, v)
            writer.writerow({'year': k, 'values': v})

Actually I was missing to add loop in the proper way, so it results always in the csv file without headers. now it works perfectly fine according to my requirements.


问:
JQuery nonresponsive click function
I am building a Chrome extension. I have a simple html file (containing just a div, an image and an empty table). I then echo some table rows and data that I read from a database, I got rid of some details since that works. I send an ajax request to retrieve the echo-ed table rows and data and append them to a table in that before mentioned html file.

This is how the php file looks, replacing data with 'something'

```<code>//a few of these:
echo
"<tr>
<td> Something </td>
<td> Something </td>
<td> Something </td>
</tr>";
</code>```

I then have a jquery script that handles the appending of the table's contents into the table and is also supposed to handle any table row clicks. It sends that ajax request and appends the table data just fine. This is what that script file looks like

```<code>$(document).ready(function() {

                    $.urlParam = function(name){
                    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
                    if (results==null){
                       return null;
                    }
                    else{
                       return results[1] || 0;
                    }
                }

                $usern = $.urlParam('user');
                var div = document.getElementById('welcome');
                div.innerHTML = "Pozdravljeni, <a href='https://www.google.si' id='imeUser'><span>" + $usern + "</span></a>! <a href='dodajGeslo.html'><span id='dodajGeslo'> Dodaj Geslo </span></a>";
                $.ajax({
                    url: 'http://passvault.000webhostapp.com/qryGesla.php',
                    data: {user:$usern},
                    type: "GET",
                    success: function(data) {
                        $("#gesla").append(data);
                        $("#load").css("display", "none");
                    }
                });

                $('tr').click( function() {
                    alert('test');
                });

});
</code>```

As you can see on the bottom of the page I have a click function for every tr, that only alerts, and yet when I click on the rows it doesn't work. Can someone help me out, I'm not sure what I'm getting wrong

答:
You probably want to use delegated events. The click handler will only be activated on
s that existed when the page was loaded. The code which adds the event handlers runs before you populate your table (which it looks like you're doing via ajax).

You need to set the event on an element which already exists when the page loads, but then tell it to delegate the event down to any child elements (of your choosing) which exist when the event fires. I'm going to assume the "gesla" element meets this need, since you're appending the data to it, but if not, choose another parent element higher up the DOM which does (you can just use document if nothing else is applicable, but for performance, you should choose the nearest available parent).

```<code>$("#gesla").on("click", "tr", function() {
  alert("test");
});
</code>```

For more info see here: http://api.jquery.com/on/ (the section entitled "Direct and delegated events").

Title: JQuery nonresponsive click function

Body:
I am building a Chrome extension. I have a simple html file (containing just a div, an image and an empty table). I then echo some table rows and data that I read from a database, I got rid of some details since that works. I send an ajax request to retrieve the echo-ed table rows and data and append them to a table in that before mentioned html file.

This is how the php file looks, replacing data with 'something'

//a few of these:
echo
"

 Something
 Something
 Something

";

I then have a jquery script that handles the appending of the table's contents into the table and is also supposed to handle any table row clicks. It sends that ajax request and appends the table data just fine. This is what that script file looks like

$(document).ready(function() {

                    $.urlParam = function(name){
                    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
                    if (results==null){
                       return null;
                    }
                    else{
                       return results[1] || 0;
                    }
                }

                $usern = $.urlParam('user');
                var div = document.getElementById('welcome');
                div.innerHTML = "Pozdravljeni, " + $usern + "!  Dodaj Geslo ";
                $.ajax({
                    url: 'http://passvault.000webhostapp.com/qryGesla.php',
                    data: {user:$usern},
                    type: "GET",
                    success: function(data) {
                        $("#gesla").append(data);
                        $("#load").css("display", "none");
                    }
                });

                $('tr').click( function() {
                    alert('test');
                });

});

As you can see on the bottom of the page I have a click function for every tr, that only alerts, and yet when I click on the rows it doesn't work. Can someone help me out, I'm not sure what I'm getting wrong

Body:
You probably want to use delegated events. The click handler will only be activated on <tr>s that existed when the page was loaded. The code which adds the event handlers runs before you populate your table (which it looks like you're doing via ajax).

You need to set the event on an element which already exists when the page loads, but then tell it to delegate the event down to any child elements (of your choosing) which exist when the event fires. I'm going to assume the "gesla" element meets this need, since you're appending the data to it, but if not, choose another parent element higher up the DOM which does (you can just use document if nothing else is applicable, but for performance, you should choose the nearest available parent).

$("#gesla").on("click", "tr", function() {
  alert("test");
});

For more info see here: http://api.jquery.com/on/ (the section entitled "Direct and delegated events").