问:
Why does key disappear from subclassed dict when iterating over `dict_keys`?
I ran across strange behavior in Python 3.6.3 when iterating over the keys of an object subclassed from dict. I already understand that the behavior of dict.keys() changed from Python 2 to Python 3 to return a dict_keys object so the shallow copy behavior seen is understandable. What I don't understand is why one of the elements in dict_keys can be found with an explicit search but doesn't appear when iterating over the dict_keys object.

Here's the MWE:

```<code>#!/usr/bin/env python

from __future__ import print_function

class chemdist(dict):
    def normalize_names(self, force_static=False):

        if force_static:
            raw_chems = tuple(self.keys())
        else:
            raw_chems = self.keys()

        print("raw_chems is " + repr(raw_chems))

        if 'Ar' in raw_chems:
            print("Found Argon!")

        for old_chem in raw_chems:
            print("Checking {:s}".format(old_chem))
            if old_chem.startswith('_'):
                new_chem = old_chem
            else:
                new_chem = '_' + old_chem

            if old_chem != new_chem:
                curr_keys = self.keys()
                if new_chem in curr_keys:
                    self[new_chem] += self[old_chem]
                else:
                    self[new_chem] = self[old_chem]

                del self[old_chem]

def main():
    h_dryair = {
        'N2' : 78.084,
        'O2' : 20.947,
        'Ar' :  0.934,
        'CO2' : 0.0350
    }

    print("Test 1: Not static")
    cd_dryair = chemdist(h_dryair)

    print("  Unnormalized:")
    print(cd_dryair)

    print("\n  Normalizing:")
    cd_dryair.normalize_names()

    print("\n  Normalized:")
    print(cd_dryair)

    print("\n\nTest 2: Static")
    cd_dryair = chemdist(h_dryair)

    print("  Unnormalized:")
    print(cd_dryair)

    print("\n  Normalizing:")
    cd_dryair.normalize_names(force_static=True)

    print("\n  Normalized:")
    print(cd_dryair)

main()
</code>```

And here are the results:

```<code>Test 1: Not static
  Unnormalized:
{'N2': 78.084, 'O2': 20.947, 'Ar': 0.934, 'CO2': 0.035}

  Normalizing:
raw_chems is dict_keys(['N2', 'O2', 'Ar', 'CO2'])
Found Argon!
Checking N2
Checking O2
Checking CO2
Checking _N2
Checking _O2
Checking _CO2

  Normalized:
{'Ar': 0.934, '_N2': 78.084, '_O2': 20.947, '_CO2': 0.035}

Test 2: Not static
  Unnormalized:
{'N2': 78.084, 'O2': 20.947, 'Ar': 0.934, 'CO2': 0.035}

  Normalizing:
raw_chems is ('N2', 'O2', 'Ar', 'CO2')
Found Argon!
Checking N2
Checking O2
Checking Ar
Checking CO2

  Normalized:
{'_N2': 78.084, '_O2': 20.947, '_Ar': 0.934, '_CO2': 0.035}
</code>```

In Test 1, the element 'Ar' is found by explicitly searching for it in raw_chems. However when iterating over raw_chems, the element 'Ar' never appears ("Checking Ar" never appears).

In Test 2, raw_chems is cast to a tuple and "Checking Ar" appears as expected.

Also, compare the final normalized object contents: in Test 1, the 'Ar' key has not been replaced with '_Ar' as it has in Test 2. 'Ar' is the only key in Test 1 that hasn't been prefixed with an underscore.

I have two guesses at the cause of this problem: dict_keys has some obvious-to-everyone-but-me behavior or some weirdness is happening because I'm subclassing dict. Possibly a combination of the two.

And before someone gratuitously tries to change the question I'm asking, the Big Picture problem I'm trying to solve is to rename the dict keys to a canonical form (HH, H2, and molecular hydrogen all represent the same thing). While that may be a more interesting issue for some to address, I'm asking about the disappearing key, so please focus on the x as stated instead of the y you imagine... :)

答:
dict.keys() under Python 3 returns a view into the dictionary's keys. When you change the dictionary's keys, you change the contents of dict.keys() as well. This can lead to an item being skipped, just as when you delete items while iterating over a list:

Assume you're about to process O2:

```<code>    N2
--> O2
    Ar
    CO2
</code>```

You process it and remove O2 and add _O2. In the process, Ar slides into the slot that contained O2.

```<code>    N2
--> Ar
    CO2
    _O2
</code>```

Now you proceed to the next iteration of the loop, which advances the "current item" pointer to the next item:

```<code>    N2
    Ar
--> CO2
    _O2
</code>```

You've just skipped Ar.

One solution is as you have found: make a copy of the keys before iterating over them. Another solution is to build a new dictionary rather than modifying the existing one. I generally recommend this approach since it could make your code a fair bit cleaner in the process.

A third solution is to iterate the lists in reverse order so that the items you still have left to process don't move when you delete one; however, dictionary keys aren't guaranteed to be in any particular order. Although they are in the version of Python you're using, you shouldn't rely on that.

Body:
I ran across strange behavior in Python 3.6.3 when iterating over the keys of an object subclassed from dict. I already understand that the behavior of dict.keys() changed from Python 2 to Python 3 to return a dict_keys object so the shallow copy behavior seen is understandable. What I don't understand is why one of the elements in dict_keys can be found with an explicit search but doesn't appear when iterating over the dict_keys object.

Here's the MWE:

#!/usr/bin/env python

from __future__ import print_function

class chemdist(dict):
    def normalize_names(self, force_static=False):

        if force_static:
            raw_chems = tuple(self.keys())
        else:
            raw_chems = self.keys()

        print("raw_chems is " + repr(raw_chems))

        if 'Ar' in raw_chems:
            print("Found Argon!")

        for old_chem in raw_chems:
            print("Checking {:s}".format(old_chem))
            if old_chem.startswith('_'):
                new_chem = old_chem
            else:
                new_chem = '_' + old_chem

            if old_chem != new_chem:
                curr_keys = self.keys()
                if new_chem in curr_keys:
                    self[new_chem] += self[old_chem]
                else:
                    self[new_chem] = self[old_chem]

                del self[old_chem]

def main():
    h_dryair = {
        'N2' : 78.084,
        'O2' : 20.947,
        'Ar' :  0.934,
        'CO2' : 0.0350
    }

    print("Test 1: Not static")
    cd_dryair = chemdist(h_dryair)

    print("  Unnormalized:")
    print(cd_dryair)

    print("\n  Normalizing:")
    cd_dryair.normalize_names()

    print("\n  Normalized:")
    print(cd_dryair)

    print("\n\nTest 2: Static")
    cd_dryair = chemdist(h_dryair)

    print("  Unnormalized:")
    print(cd_dryair)

    print("\n  Normalizing:")
    cd_dryair.normalize_names(force_static=True)

    print("\n  Normalized:")
    print(cd_dryair)

main()

And here are the results:

Test 1: Not static
  Unnormalized:
{'N2': 78.084, 'O2': 20.947, 'Ar': 0.934, 'CO2': 0.035}

  Normalizing:
raw_chems is dict_keys(['N2', 'O2', 'Ar', 'CO2'])
Found Argon!
Checking N2
Checking O2
Checking CO2
Checking _N2
Checking _O2
Checking _CO2

  Normalized:
{'Ar': 0.934, '_N2': 78.084, '_O2': 20.947, '_CO2': 0.035}

Test 2: Not static
  Unnormalized:
{'N2': 78.084, 'O2': 20.947, 'Ar': 0.934, 'CO2': 0.035}

  Normalizing:
raw_chems is ('N2', 'O2', 'Ar', 'CO2')
Found Argon!
Checking N2
Checking O2
Checking Ar
Checking CO2

  Normalized:
{'_N2': 78.084, '_O2': 20.947, '_Ar': 0.934, '_CO2': 0.035}

In Test 1, the element 'Ar' is found by explicitly searching for it in raw_chems. However when iterating over raw_chems, the element 'Ar' never appears ("Checking Ar" never appears).

In Test 2, raw_chems is cast to a tuple and "Checking Ar" appears as expected.

Also, compare the final normalized object contents: in Test 1, the 'Ar' key has not been replaced with '_Ar' as it has in Test 2. 'Ar' is the only key in Test 1 that hasn't been prefixed with an underscore.

I have two guesses at the cause of this problem: dict_keys has some obvious-to-everyone-but-me behavior or some weirdness is happening because I'm subclassing dict. Possibly a combination of the two.

And before someone gratuitously tries to change the question I'm asking, the Big Picture problem I'm trying to solve is to rename the dict keys to a canonical form (HH, H2, and molecular hydrogen all represent the same thing). While that may be a more interesting issue for some to address, I'm asking about the disappearing key, so please focus on the x as stated instead of the y you imagine... :)

Body:
dict.keys() under Python 3 returns a view into the dictionary's keys. When you change the dictionary's keys, you change the contents of dict.keys() as well. This can lead to an item being skipped, just as when you delete items while iterating over a list:

Assume you're about to process O2:

    N2
--> O2
    Ar
    CO2

You process it and remove O2 and add _O2. In the process, Ar slides into the slot that contained O2.

    N2
--> Ar
    CO2
    _O2

Now you proceed to the next iteration of the loop, which advances the "current item" pointer to the next item:

    N2
    Ar
--> CO2
    _O2

You've just skipped Ar.

One solution is as you have found: make a copy of the keys before iterating over them. Another solution is to build a new dictionary rather than modifying the existing one. I generally recommend this approach since it could make your code a fair bit cleaner in the process.

A third solution is to iterate the lists in reverse order so that the items you still have left to process don't move when you delete one; however, dictionary keys aren't guaranteed to be in any particular order. Although they are in the version of Python you're using, you shouldn't rely on that.


来源: stackexchange

问:
Segmentation fault (core dumped) using stringstream in multithread application
I trying do simple threadsafe logger, which print messages to console.

```<code>// Test function for check logger. It is work
void test(double& diff)
{
  std::vector<double> result;
  for( int counter = 0; counter < 100000; ++counter)
  {
    result.push_back(clock());

    std::string text = "counter = ";
    text.append(std::to_string(counter));
    LOG_MESSAGE(text); //<-- Correct log..
  }
  diff = clock() - result.front();

}

int main(int argc, char** argv)
{
  double time2;
  double time1;
  std::vector<double> timerResult;
  std::vector<std::thread> threadVector;

  time1 = clock();
  for(int i = 0; i < 5; ++i) //<-- Create 5 thread of test function
  {
    timerResult.push_back(0);
    threadVector.push_back(std::thread(test, std::ref(timerResult[i])));
  }
  for(std::thread& t : threadVector)
    t.join();
  time2 = clock(); //<-- Threads is finished

  double res = 0;
  for(double tRes : timerResult)
     res += tRes;
  res = res / static_cast<double>(CLOCKS_PER_SEC);

  std::string message; //<-- Generate final message
  message.append("Timer: ")
      .append(std::to_string((time2 - time1) / (double)CLOCKS_PER_SEC))
      .append(" - thread timer: ")
      .append(std::to_string(res));

  LOG_MESSAGE(message); //<-- Crash inside!!

  return 0;
}
</code>```

Logger is good working in threads. But when I try log in main() function that call SIGSEGV signal in destructor of std::ostringstream (in function of construct log message):

```<code>static Logger::Core logger; //<--Global Logger variable

#define LOG_MESSAGE( TEXT ) logger.addNoteInLog(TEXT) //<-- Define for log message

void Core::addNoteInLog(const Message &message) //<-- threadsafe log function
{
  std::string text;
  message.generateString(text); //<-- [Crash here] generate log message
  g_lock.lock();
  std::cout << text;
  g_lock.unlock();
}

void Message::generateString(std::string& text) const
{
  text.clear();
  tm *ltm = localtime(&mDate);

  std::ostringstream data; //<-- [Crash here] function is finished, but cannot destruct object.
  data << 1900 + ltm->tm_year << "/"
       << 1 + ltm->tm_mon << "/"
       << ltm->tm_mday << "\t";
  data << "[INF] - ";
  data << std::this_thread::get_id() << " - "
       << mMessage << "\n";

  text = data.str();
}
</code>```

I dont understand why logger in threads is work, but in main() function crashed. Using the exclusion method, I found out when the error is occurred:

when I use 5 (or more) threads

when test function is not empty

when in generateString use stringstream or ostringstream or string.append() (in last case application crash in std::string destructor in same place)

What say debugger in QtCreater.

Build in Ubuntu OS, gcc version 5.4.0, compilation flags: -std=c++17 -pthread -Wall

This is my git repository with error.

答:
Problem solved.
As it was said in the comments, line threadVector.push_back(std::thread(test, std::ref(timerResult[i]))); is not correct, because memory reallocation in timerResult was done after calling push_back 5 times, and passing reference by ref(timerResult[i]) is incorrect.

Correct code:

```<code>    int main(int argc, char** argv)
    {
      double time2;
      double time1;
      std::vector<double> timerResult (5); //<-- Create filling of vector
      std::vector<std::thread> threadVector;

      time1 = clock();
      for(int i = 0; i < 5; ++i)
      {
        //timerResult.push_back(0); //<-- incorrect filling of vector
        threadVector.push_back(std::thread(test, std::ref(timerResult[i])));
      }
      for(std::thread& t : threadVector)
        t.join();
      time2 = clock();
      ...
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I trying do simple threadsafe logger, which print messages to console.

// Test function for check logger. It is work
void test(double& diff)
{
  std::vector<double> result;
  for( int counter = 0; counter < 100000; ++counter)
  {
    result.push_back(clock());

    std::string text = "counter = ";
    text.append(std::to_string(counter));
    LOG_MESSAGE(text); //<-- Correct log..
  }
  diff = clock() - result.front();

}

int main(int argc, char** argv)
{
  double time2;
  double time1;
  std::vector<double> timerResult;
  std::vector<std::thread> threadVector;

  time1 = clock();
  for(int i = 0; i < 5; ++i) //<-- Create 5 thread of test function
  {
    timerResult.push_back(0);
    threadVector.push_back(std::thread(test, std::ref(timerResult[i])));
  }
  for(std::thread& t : threadVector)
    t.join();
  time2 = clock(); //<-- Threads is finished

  double res = 0;
  for(double tRes : timerResult)
     res += tRes;
  res = res / static_cast<double>(CLOCKS_PER_SEC);

  std::string message; //<-- Generate final message
  message.append("Timer: ")
      .append(std::to_string((time2 - time1) / (double)CLOCKS_PER_SEC))
      .append(" - thread timer: ")
      .append(std::to_string(res));

  LOG_MESSAGE(message); //<-- Crash inside!!

  return 0;
}

Logger is good working in threads. But when I try log in main() function that call SIGSEGV signal in destructor of std::ostringstream (in function of construct log message):

static Logger::Core logger; //<--Global Logger variable

#define LOG_MESSAGE( TEXT ) logger.addNoteInLog(TEXT) //<-- Define for log message

void Core::addNoteInLog(const Message &message) //<-- threadsafe log function
{
  std::string text;
  message.generateString(text); //<-- [Crash here] generate log message
  g_lock.lock();
  std::cout << text;
  g_lock.unlock();
}

void Message::generateString(std::string& text) const
{
  text.clear();
  tm *ltm = localtime(&mDate);

  std::ostringstream data; //<-- [Crash here] function is finished, but cannot destruct object.
  data << 1900 + ltm->tm_year << "/"
       << 1 + ltm->tm_mon << "/"
       << ltm->tm_mday << "\t";
  data << "[INF] - ";
  data << std::this_thread::get_id() << " - "
       << mMessage << "\n";

  text = data.str();
}

I dont understand why logger in threads is work, but in main() function crashed. Using the exclusion method, I found out when the error is occurred:

when I use 5 (or more) threads

when test function is not empty

when in generateString use stringstream or ostringstream or string.append() (in last case application crash in std::string destructor in same place)

What say debugger in QtCreater.

Build in Ubuntu OS, gcc version 5.4.0, compilation flags: -std=c++17 -pthread -Wall

This is my git repository with error.

Body:
Problem solved.
As it was said in the comments, line threadVector.push_back(std::thread(test, std::ref(timerResult[i]))); is not correct, because memory reallocation in timerResult was done after calling push_back 5 times, and passing reference by ref(timerResult[i]) is incorrect.

Correct code:

    int main(int argc, char** argv)
    {
      double time2;
      double time1;
      std::vector<double> timerResult (5); //<-- Create filling of vector
      std::vector<std::thread> threadVector;

      time1 = clock();
      for(int i = 0; i < 5; ++i)
      {
        //timerResult.push_back(0); //<-- incorrect filling of vector
        threadVector.push_back(std::thread(test, std::ref(timerResult[i])));
      }
      for(std::thread& t : threadVector)
        t.join();
      time2 = clock();
      ...
    }


问:
Strava V3 api upload gpx file php
i'm trying to upload a gpx file using strava api. I've already got the access token and i'm using this script :

```<code>$actual_file= realpath('/.../../myfile.gpx');

$url="https://www.strava.com/api/v3/uploads";

$postfields = array(
    "activity_type" => "ride",
    "data_type" => "gpx",
    "file" => '@' . $actual_file . ";type=application/xml"
);

$headers = array('Authorization: Bearer ' . $token);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec ($ch);
echo $response;
</code>```

but  the response i get from strava is {"message":"Bad Request","errors":[{"resource":"Upload","field":"file","code":"not a file"}]}

答:
I found out that you should use "file" => curl_file_create($actual_file) for the file param. Also those params are out of date (check out the new doc).

I hope this will help someone. I discovered it while look through this PHP wrapper for Strava's API

Title: Strava V3 api upload gpx file php

Body:
i'm trying to upload a gpx file using strava api. I've already got the access token and i'm using this script :

$actual_file= realpath('/.../../myfile.gpx');

$url="https://www.strava.com/api/v3/uploads";

$postfields = array(
    "activity_type" => "ride",
    "data_type" => "gpx",
    "file" => '@' . $actual_file . ";type=application/xml"
);

$headers = array('Authorization: Bearer ' . $token);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec ($ch);
echo $response;

but  the response i get from strava is {"message":"Bad Request","errors":[{"resource":"Upload","field":"file","code":"not a file"}]}


问:
How to summarize column price from 2 tables with no relationship?
In a mysql databse, I have tblA.price and tblB.price. There is no relationship between them.

I want summarize all sales from tableA and tableB. It will be something like that sum(tblA.price)+sum(tblB.price) AS total.

how could I perform that query?

答:
The union that @cjsfj shows would work, and here are a couple of other options:

Do two scalar subqueries and add them together.

```<code>select (select sum(price) from tblA) + (select sum(price) from tblB) as total;
</code>```

Do two queries from your application, get the results of each, and add them together.

Body:
The union that @cjsfj shows would work, and here are a couple of other options:

Do two scalar subqueries and add them together.

select (select sum(price) from tblA) + (select sum(price) from tblB) as total;

Do two queries from your application, get the results of each, and add them together.


问:
Get the latest file from a bunch of similar named files in a directory - powershell
I need to get the latest file from the below list.There are 3 types of files created everyday and I just need 1 from the 3 types.

Example:

```<code>my_file_dob_6545d.txt   12/3/2017 5:00 PM
my_file_csm_6545d.txt   12/3/2017 5:00 PM
my_file_6545d.txt       12/3/2017 5:00 PM  <--- Need to get this.
my_file_dob_6544d.txt   12/2/2017 5:00 PM
my_file_csm_6544d.txt   12/2/2017 5:00 PM
my_file_6544d.txt       12/2/2017 5:00 PM
my_file_dob_6543d.txt   12/1/2017 5:00 PM
my_file_csm_6543d.txt   12/1/2017 5:00 PM
my_file_6543d.txt       12/1/2017 5:00 PM
</code>```

I have the following script from here

```<code>$dir = "c:\my_folder\"
$filter="my_file_*d.txt" <--How can modify this to get only  my_file_XXXXd.txt files? XXXX keeps incrementing everyday
$latest = Get-ChildItem -Path $dir -Filter $filter | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.name
</code>```

答:
Slightly simpler syntax:</p>

```<code>$latest = Get-ChildItem C:\my_folder\my_file_????d.txt | Sort-Object LastAccessTime -Descending | Select -First 1
</code>```

Body:
I need to get the latest file from the below list.There are 3 types of files created everyday and I just need 1 from the 3 types.

Example:

my_file_dob_6545d.txt   12/3/2017 5:00 PM
my_file_csm_6545d.txt   12/3/2017 5:00 PM
my_file_6545d.txt       12/3/2017 5:00 PM  <--- Need to get this.
my_file_dob_6544d.txt   12/2/2017 5:00 PM
my_file_csm_6544d.txt   12/2/2017 5:00 PM
my_file_6544d.txt       12/2/2017 5:00 PM
my_file_dob_6543d.txt   12/1/2017 5:00 PM
my_file_csm_6543d.txt   12/1/2017 5:00 PM
my_file_6543d.txt       12/1/2017 5:00 PM

I have the following script from here

$dir = "c:\my_folder\"
$filter="my_file_*d.txt" <--How can modify this to get only  my_file_XXXXd.txt files? XXXX keeps incrementing everyday
$latest = Get-ChildItem -Path $dir -Filter $filter | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.name

Body:
Slightly simpler syntax:

$latest = Get-ChildItem C:\my_folder\my_file_????d.txt | Sort-Object LastAccessTime -Descending | Select -First 1


问:
Unexpected type error with multiplication of two integers in a while loop
I am supposed to implement a Method to my program that multiply all of the integers in the intervall n1,n2. This is my code:

```<code>static int productofIntervall (int n1, int n2){
    int a;
    while(n1 <= n2){
        n1*n2 = a;
        n1=n1++;
    }
    return(a);
}
        public static void main(String[] args){
        System.out.println(productofIntervall(6,11));
    }
</code>```

}

When I try to comply i recieve the error:

```<code>Main.java:6: error: unexpected type
                        (n1)*(n2)=a;
                            ^
  required: variable
  found:    value
1 error
</code>```

Can anybody tell me what`s wrong?
Thanks in advance.

答:
Given the below code:

```<code>package com.example.so.questions;

public class SO47660627CompilationAndIncrement {

    public static void main(String[] args) {

        int a = 0;
        int b = 1;
        int c = 0;
        int d = 1;
        int e = 0;
        int f = 0;
        int g = 1;
        int h = 1;
        int i = 0;
        int j = 0;

        a = b++;
        c = ++d;
        e = e++;
        f = ++f;
        i = g-(g++);
        j = h-(++h);

        System.out.println(" int a=0; b=1; a=b++ // a is : "+a+" and b is : "+b);
        System.out.println(" int c=0; d=1; c=++d // c is : "+c+" and d is : "+d);
        System.out.println(" int e=0; e = e++ ; // e is : "+e);
        System.out.println(" int f=0; f = ++f ; // f is : "+f);
        System.out.println(" int g=1; int i = g-(g++); // i is : "+ i);
        System.out.println(" int h=1; int j = h-(++h); // j is : "+ j);

    }

}
</code>```

If you run FindBugs source code analyzer, it flags as a concern - the line comprising :

```<code>e = e++;
</code>```

The explanation is :

Bug: Overwritten increment in
  com.example.so.questions.SO47660627CompilationAndIncrement.main(String[])

The code performs an increment operation (e.g., i++) and then
  immediately overwrites it. For example, i = i++ immediately overwrites
  the incremented value with the original value.

On running the above code, the output is :

```<code> int a=0; b=1; a=b++ // a is : 1 and b is : 2
 int c=0; d=1; c=++d // c is : 2 and d is : 2
 int e=0; e = e++ ; // e is : 0
 int f=0; f = ++f ; // f is : 1
 int g=1; int i = g-(g++); // i is : 0
 int h=1; int j = h-(++h); // j is : -1
</code>```

From the above output, we can conclude that the the post or pre increment operation involves the creation of a temporary variable that stores the original value - prior to increment operation in case of post-increment operation and after the increment in case of pre-increment operation and then applies the result stored in the temporary variable further in the expression.

Body:
I am supposed to implement a Method to my program that multiply all of the integers in the intervall n1,n2. This is my code:

static int productofIntervall (int n1, int n2){
    int a;
    while(n1 <= n2){
        n1*n2 = a;
        n1=n1++;
    }
    return(a);
}
        public static void main(String[] args){
        System.out.println(productofIntervall(6,11));
    }

}

When I try to comply i recieve the error:

Main.java:6: error: unexpected type
                        (n1)*(n2)=a;
                            ^
  required: variable
  found:    value
1 error

Can anybody tell me what`s wrong?
Thanks in advance.

Body:
Given the below code:

package com.example.so.questions;

public class SO47660627CompilationAndIncrement {

    public static void main(String[] args) {

        int a = 0;
        int b = 1;
        int c = 0;
        int d = 1;
        int e = 0;
        int f = 0;
        int g = 1;
        int h = 1;
        int i = 0;
        int j = 0;

        a = b++;
        c = ++d;
        e = e++;
        f = ++f;
        i = g-(g++);
        j = h-(++h);

        System.out.println(" int a=0; b=1; a=b++ // a is : "+a+" and b is : "+b);
        System.out.println(" int c=0; d=1; c=++d // c is : "+c+" and d is : "+d);
        System.out.println(" int e=0; e = e++ ; // e is : "+e);
        System.out.println(" int f=0; f = ++f ; // f is : "+f);
        System.out.println(" int g=1; int i = g-(g++); // i is : "+ i);
        System.out.println(" int h=1; int j = h-(++h); // j is : "+ j);

    }

}

If you run FindBugs source code analyzer, it flags as a concern - the line comprising :

e = e++;

The explanation is :

Bug: Overwritten increment in
  com.example.so.questions.SO47660627CompilationAndIncrement.main(String[])

The code performs an increment operation (e.g., i++) and then
  immediately overwrites it. For example, i = i++ immediately overwrites
  the incremented value with the original value.

On running the above code, the output is :

 int a=0; b=1; a=b++ // a is : 1 and b is : 2
 int c=0; d=1; c=++d // c is : 2 and d is : 2
 int e=0; e = e++ ; // e is : 0
 int f=0; f = ++f ; // f is : 1
 int g=1; int i = g-(g++); // i is : 0
 int h=1; int j = h-(++h); // j is : -1

From the above output, we can conclude that the the post or pre increment operation involves the creation of a temporary variable that stores the original value - prior to increment operation in case of post-increment operation and after the increment in case of pre-increment operation and then applies the result stored in the temporary variable further in the expression.


问:
Android emulator not running google maps
I'm having an issue with my android studio emulator, specifically running an app which I made that has a google maps element in it.  The app works perfectly fine, as I have been able to test it on my phone, but the problem I am currently having is that when I run it on the emulator, the map doesn't show up, it just shows that it should be there.  Is there a setting I am missing or something else? I will include a screenshot of it running in the emulator so you can see what I mean.Here is the screenshot.

I am not allowed to embed images in posts, so the link is provided above. The emulator is for a Nexus 5X running API 27.

Edit: The problem is API 27.

答: I edited the post, but I solved the issue, the problem was using API 27, for anyone else who has had this problem.</p>


问:
(Another) question regarding C loops and data structures
I have a program (who's code is available at the bottom) which generates a list of numbers the way that I want it to. The program works fine as is and does exactly what I want. I'm just not a fan of the way I wrote it. It returns "Segmentation fault" if I change one thing, which I'll say at the bottom as well. Here's the code:

```<code>#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2, *dat;
    //double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (int*) calloc(nrow, sizeof(int));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }

    // Generates the bonds
    k=2;
    for (i=0; i<nrow; i++) {
        k--;
        for (j=0; j<2; j++) {
            dat2[i][j] = k++;
            if ( ((k%501) == 0) ) {
                k--;
                dat2[i][j] = k++;
                k++;
            }
        }
    }

    FILE *inp2;
    inp2 = fopen("bonds.out", "w");

    for (i=1; i<=nrow; i++)
        fprintf(inp2, "%d %d\n", dat2[i-1][0], dat2[i-1][1]);

    fclose(inp2);

    // Generates the bond ID in the pattern 1 2 3 3 2 1 ... (appropriate for Bond swap!)
    k=1;
    while ( k < nrow ) {
        for (j=0; j<250; j++) {
            dat[k] = (j+1);
            k++;
        }
        for (j=250; j>0; j--) {
            dat[k] = j;
            k++;
        }
    }

    // Scans bonds.out (because just reporting dat2[][] returns segmentation error, not sure why.
    // scans the bonds.out file and stores both values into dm1 and dm2, then reports into 'results.out' file
    int dm1, dm2;

    FILE *inp;
    inp = fopen("input.out", "w");
    inp2 = fopen("bonds.out", "r");

    for (i=1; i<=nrow; i++) {
        fscanf(inp2, "%d %d", &dm1, &dm2);
        fprintf(inp, "%d  %d  %d  %d\n", i, dat[i], dm1, dm2);
    }

    printf("\nDone. All data has been written to \"input.out\"\n");

    fclose(inp2);
    fclose(inp);

    return 0;
}
</code>```

Now, I don't like the fact that it's first writing dat2[][] to a file and then scanning that file for the values. Why, instead, can't I incorporate dat2[][] in the main loop that writes the "results.out" file? If I do so, I get Segmentation fault. For clarification, I mean changing these lines in the code:

```<code>for (i=1; i<=nrow; i++) {
    fscanf(inp2, "%d %d", &dm1, &dm2);
    fprintf(inp, "%d  %d  %d  %d\n", i, dat[i], dm1, dm2);
}
</code>```

To these:

```<code>for (i=1; i<=nrow; i++) {
    fprintf(inp, "%d  %d  %d  %d\n", i, dat[i], dat2[i-1][0], dat2[i-1][1]);
}
</code>```

I'd love an explanation as I'm still very new to C.

Thanks a lot!
Amit

答:
I think there is something else on your code too besides what Relkin (correctly) pointed out.

```<code>int nrow = NCH*(ns-1);
dat = (int*) calloc(nrow, sizeof(int));
</code>```

If my calculations are right, nrow == 81*(500-1) (== 40419) so it is dat[40419]

On the following explosive algorithm :

```<code>k=1;
while ( k < nrow ) {
    for (j=0; j<250; j++) {
        dat[k] = (j+1);
        k++;
    }
    for (j=250; j>0; j--) {
        dat[k] = j;
        k++;
    }
}
</code>```

Every internal for loop increases k by 250 (so both increase it by 500 for every while loop), while k < 40419. This means there is a point where k reaches 40001, the condition is satisfied and the loop goes one more. At this moment, on the second for loop you exceed 40419 and write in memory you shouldn't. Take a look at that and check my maths again plz.

Once you are inside the while loop, and the condition falsifies, this does not mean the loop will automatically exit.

ContentLicense: CC BY-SA 2.5

Body:
I have a program (who's code is available at the bottom) which generates a list of numbers the way that I want it to. The program works fine as is and does exactly what I want. I'm just not a fan of the way I wrote it. It returns "Segmentation fault" if I change one thing, which I'll say at the bottom as well. Here's the code:

#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2, *dat;
    //double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (int*) calloc(nrow, sizeof(int));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }

    // Generates the bonds
    k=2;
    for (i=0; i<nrow; i++) {
        k--;
        for (j=0; j<2; j++) {
            dat2[i][j] = k++;
            if ( ((k%501) == 0) ) {
                k--;
                dat2[i][j] = k++;
                k++;
            }
        }
    }

    FILE *inp2;
    inp2 = fopen("bonds.out", "w");

    for (i=1; i<=nrow; i++)
        fprintf(inp2, "%d %d\n", dat2[i-1][0], dat2[i-1][1]);

    fclose(inp2);

    // Generates the bond ID in the pattern 1 2 3 3 2 1 ... (appropriate for Bond swap!)
    k=1;
    while ( k < nrow ) {
        for (j=0; j<250; j++) {
            dat[k] = (j+1);
            k++;
        }
        for (j=250; j>0; j--) {
            dat[k] = j;
            k++;
        }
    }

    // Scans bonds.out (because just reporting dat2[][] returns segmentation error, not sure why.
    // scans the bonds.out file and stores both values into dm1 and dm2, then reports into 'results.out' file
    int dm1, dm2;

    FILE *inp;
    inp = fopen("input.out", "w");
    inp2 = fopen("bonds.out", "r");

    for (i=1; i<=nrow; i++) {
        fscanf(inp2, "%d %d", &dm1, &dm2);
        fprintf(inp, "%d  %d  %d  %d\n", i, dat[i], dm1, dm2);
    }

    printf("\nDone. All data has been written to \"input.out\"\n");

    fclose(inp2);
    fclose(inp);

    return 0;
}

Now, I don't like the fact that it's first writing dat2[][] to a file and then scanning that file for the values. Why, instead, can't I incorporate dat2[][] in the main loop that writes the "results.out" file? If I do so, I get Segmentation fault. For clarification, I mean changing these lines in the code:

for (i=1; i<=nrow; i++) {
    fscanf(inp2, "%d %d", &dm1, &dm2);
    fprintf(inp, "%d  %d  %d  %d\n", i, dat[i], dm1, dm2);
}

To these:

for (i=1; i<=nrow; i++) {
    fprintf(inp, "%d  %d  %d  %d\n", i, dat[i], dat2[i-1][0], dat2[i-1][1]);
}

I'd love an explanation as I'm still very new to C.

Thanks a lot!
Amit

Body:
I think there is something else on your code too besides what Relkin (correctly) pointed out.

int nrow = NCH*(ns-1);
dat = (int*) calloc(nrow, sizeof(int));

If my calculations are right, nrow == 81*(500-1) (== 40419) so it is dat[40419]

On the following explosive algorithm :

k=1;
while ( k < nrow ) {
    for (j=0; j<250; j++) {
        dat[k] = (j+1);
        k++;
    }
    for (j=250; j>0; j--) {
        dat[k] = j;
        k++;
    }
}

Every internal for loop increases k by 250 (so both increase it by 500 for every while loop), while k < 40419. This means there is a point where k reaches 40001, the condition is satisfied and the loop goes one more. At this moment, on the second for loop you exceed 40419 and write in memory you shouldn't. Take a look at that and check my maths again plz.

Once you are inside the while loop, and the condition falsifies, this does not mean the loop will automatically exit.


问:
Fonts not displayed on HTML email and underline comes for hyperlinks
I have an HTML email code as given in the below link:

https://privatebin.net/?1ca92ace7be6c777#LLNgtdGPXCC4Si0Ui7jsEt7P/g+PsZ1gRq08qBTOljo=

The issue is the fonts linked by link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700" rel="stylesheet" type="text/css" is not displayed correctly even though I have added inline styles to all tags.
Also an underline is displayed for the renew button. I tried by adding text-decoration:none style with !important. but was of no use.
Any opinions?

答:
you asked a few questions here so I'll do my best to answer them separately.

Web fonts, as mentioned by others, are not supported in all email clients. It's currently not possible to display web fonts in Outlook, Gmail app, or any webmail client. Be aware that fallback system fonts will display in some email clients no matter how the email is coded.

For clients that do support web fonts, something like this inside your  will get you the best possible coverage:

```<code><!-- Desktop Outlook chokes on web font references and defaults to Times New Roman, so we force a safe fallback font. -->
<!--[if mso]>
    <style>
        * {
            font-family: sans-serif !important;
        }
    </style>
<![endif]-->

<!-- All other clients get the webfont reference; some will render the font and others will silently fail to the fallbacks. -->
<!--[if !mso]><!-->
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700' rel='stylesheet' type='text/css'>
<!--<![endif]-->
</code>```

More on web font support in email on Style Campaign and Litmus.

Regarding the underline in the button, sometimes email clients place the default (and sometimes blue) underline in links within buttons. This can be reset by targeting a  inside the href=""> button:

CSS

```<code><head>
    <style>
        .button-link {
            text-decoration: none !important;
        }
    </style>
</head>
</code>```

HTML

```<code><table role="presentation" cellspacing="0" cellpadding="0" border="0">
    <tr>
        <td style="border-radius: 3px; background: #222222; text-align: center;">
            <a href="http://www.google.com" style="background: #222222; border: 15px solid #222222; font-family: sans-serif; font-size: 13px; line-height: 110%; text-align: center; text-decoration: none; display: block; border-radius: 3px; font-weight: bold;">
                <span style="color:#ffffff;" class="button-link">Button Text</span>
            </a>
        </td>
    </tr>
</table>
</code>```

Body:
you asked a few questions here so I'll do my best to answer them separately.

Web fonts, as mentioned by others, are not supported in all email clients. It's currently not possible to display web fonts in Outlook, Gmail app, or any webmail client. Be aware that fallback system fonts will display in some email clients no matter how the email is coded.

For clients that do support web fonts, something like this inside your <head> will get you the best possible coverage:

<!-- Desktop Outlook chokes on web font references and defaults to Times New Roman, so we force a safe fallback font. -->
<!--[if mso]>
    <style>
        * {
            font-family: sans-serif !important;
        }
    </style>
<![endif]-->

<!-- All other clients get the webfont reference; some will render the font and others will silently fail to the fallbacks. -->
<!--[if !mso]><!-->
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700' rel='stylesheet' type='text/css'>
<!--<![endif]-->

More on web font support in email on Style Campaign and Litmus.

Regarding the underline in the button, sometimes email clients place the default (and sometimes blue) underline in links within buttons. This can be reset by targeting a <span> inside the <a href=""> button:

CSS

<head>
    <style>
        .button-link {
            text-decoration: none !important;
        }
    </style>
</head>

HTML

<table role="presentation" cellspacing="0" cellpadding="0" border="0">
    <tr>
        <td style="border-radius: 3px; background: #222222; text-align: center;">
            <a href="http://www.google.com" style="background: #222222; border: 15px solid #222222; font-family: sans-serif; font-size: 13px; line-height: 110%; text-align: center; text-decoration: none; display: block; border-radius: 3px; font-weight: bold;">
                <span style="color:#ffffff;" class="button-link">Button Text</span>
            </a>
        </td>
    </tr>
</table>


问:
Using sed to change ip addresses in dhcpcd.conf file
On a raspberry pi I am trying to write a simple script that will allow me to change the static ip settings in the dhcpcd.conf file.  The below script works except for the dns-servers.  It appears that the sed statement does not work for that line as it contains two ip addresses seperated by a space.  The script is as follows:

```<code>#!/bin/bash
currip=$(cat /etc/dhcpcd.conf | grep -e '^static ip_address=' | cut -d= -
f2)
currgw=$(cat /etc/dhcpcd.conf | grep -e '^static routers=' | cut -d= -f2)
currdns=$(cat /etc/dhcpcd.conf | grep -e '^static domain_name_servers=' |
cut -d= -f2)
echo "current IP is $currip"
echo "current GW is $currgw"
echo "current DNS servers are $currdns"
echo "Enter new static ip in form of x.x.x.x/x: "
read newip
echo "Enter new GW in form of x.x.x.x: "
read newgw
echo "Enter new DNS servers in form of x.x.x.x x.x.x.x: "
read newdns
echo "currip is $currip"
echo "new ip will be $newip"
echo "new dns will be $newdns"
sed -i -e "s@$currip\b@$newip@g" /etc/dhcpcd.conf
sed -i -e "s@$currgw\b@$newgw@g" /etc/dhcpcd.conf
sed -i -e "s@$currdns\b@$newdns@g" /etc/dhcpcd.conf
chip=$(cat /etc/dhcpcd.conf | grep -e '^static ip_address=' | cut -d= -
f2)
chgw=$(cat /etc/dhcpcd.conf | grep -e '^static routers=' | cut -d= -f2)
chdns=$(cat /etc/dhcpcd.conf | grep -e '^static domain_name_servers=' |
cut -d= -f2)
echo "The ip has been changed to $chip"
echo "The GW has been changed to $chgw"
echo "The DNS server have been changed to $chdns"
</code>```

The lines in the dhcpcd.conf file look like this:

static ip_address=192.168.126.7/24

static routers=192.168.126.1

static domain_name_servers=192.168.126.1 66.243.243.101

How do I need to tweak my sed statement for the domain_name_servers?

答:
The problem is your static router "192.168.126.1" is also present in the static domain_name_servers. Therefore, when you overwrite the routers with

```<code>sed -i -e "s@$currgw\b@$newgw@g" /etc/dhcpcd.conf
</code>```

the line in your conf file is changed to

```<code>static domain_name_servers={{what you entered}} 66.243.243.101
</code>```

so it no longer it matched by the name servers sed.

I suggest changing the find and replace strings to include the keys as well as the values, such as in the following:

```<code>sed -i -e "s@^static ip_address=$currip\b@static ip_address=$newip@g" dhcpcd.conf
sed -i -e "s@^static routers=$currgw\b@static routers=$newgw@g" dhcpcd.conf
sed -i -e "s@^static domain_name_servers=$currdns\b@static domain_name_servers=$newdns@g" dhcpcd.conf**strong text**
</code>```

This will make it so no other lines that happen to contain an earlier replaced-string will be changed

Body:
On a raspberry pi I am trying to write a simple script that will allow me to change the static ip settings in the dhcpcd.conf file.  The below script works except for the dns-servers.  It appears that the sed statement does not work for that line as it contains two ip addresses seperated by a space.  The script is as follows:

#!/bin/bash
currip=$(cat /etc/dhcpcd.conf | grep -e '^static ip_address=' | cut -d= -
f2)
currgw=$(cat /etc/dhcpcd.conf | grep -e '^static routers=' | cut -d= -f2)
currdns=$(cat /etc/dhcpcd.conf | grep -e '^static domain_name_servers=' |
cut -d= -f2)
echo "current IP is $currip"
echo "current GW is $currgw"
echo "current DNS servers are $currdns"
echo "Enter new static ip in form of x.x.x.x/x: "
read newip
echo "Enter new GW in form of x.x.x.x: "
read newgw
echo "Enter new DNS servers in form of x.x.x.x x.x.x.x: "
read newdns
echo "currip is $currip"
echo "new ip will be $newip"
echo "new dns will be $newdns"
sed -i -e "s@$currip\b@$newip@g" /etc/dhcpcd.conf
sed -i -e "s@$currgw\b@$newgw@g" /etc/dhcpcd.conf
sed -i -e "s@$currdns\b@$newdns@g" /etc/dhcpcd.conf
chip=$(cat /etc/dhcpcd.conf | grep -e '^static ip_address=' | cut -d= -
f2)
chgw=$(cat /etc/dhcpcd.conf | grep -e '^static routers=' | cut -d= -f2)
chdns=$(cat /etc/dhcpcd.conf | grep -e '^static domain_name_servers=' |
cut -d= -f2)
echo "The ip has been changed to $chip"
echo "The GW has been changed to $chgw"
echo "The DNS server have been changed to $chdns"

The lines in the dhcpcd.conf file look like this:

static ip_address=192.168.126.7/24

static routers=192.168.126.1

static domain_name_servers=192.168.126.1 66.243.243.101

How do I need to tweak my sed statement for the domain_name_servers?

Body:
The problem is your static router "192.168.126.1" is also present in the static domain_name_servers. Therefore, when you overwrite the routers with

sed -i -e "s@$currgw\b@$newgw@g" /etc/dhcpcd.conf

the line in your conf file is changed to

static domain_name_servers={{what you entered}} 66.243.243.101

so it no longer it matched by the name servers sed.

I suggest changing the find and replace strings to include the keys as well as the values, such as in the following:

sed -i -e "s@^static ip_address=$currip\b@static ip_address=$newip@g" dhcpcd.conf
sed -i -e "s@^static routers=$currgw\b@static routers=$newgw@g" dhcpcd.conf
sed -i -e "s@^static domain_name_servers=$currdns\b@static domain_name_servers=$newdns@g" dhcpcd.conf**strong text**

This will make it so no other lines that happen to contain an earlier replaced-string will be changed


问:
Converting Geometry to Longitude/Latitude coordinates in R
https://data.sfgov.org/Transportation/Bike-Share-Stations/gtyg-jpkj

I am working with this dataset, and am wondering if I could convert geometry (Geom in the table) to two columns: longitude and latitude in R.

Thank you!

答:
I think the Geom column already contains the latitude/longitude.

```<code>library(tidyverse)

df <- df %>%
  mutate(Geom = gsub('[()°]', '', Geom)) %>%
  separate(col = Geom, into = c('Latitude', 'Longitude '), sep = '\\,')
</code>```

First we remove the parentheses and degree symbol with gsub('[()°]', '', geom) and replace the Geom column. We then separate the Geom column into new Latitude and Longitude columns with a comma separator sep = '\\,'.

Body:
I think the Geom column already contains the latitude/longitude.

library(tidyverse)

df <- df %>%
  mutate(Geom = gsub('[()°]', '', Geom)) %>%
  separate(col = Geom, into = c('Latitude', 'Longitude '), sep = '\\,')

First we remove the parentheses and degree symbol with gsub('[()°]', '', geom) and replace the Geom column. We then separate the Geom column into new Latitude and Longitude columns with a comma separator sep = '\\,'.


问:
Duplicate and number rows "n" amount of times using Excel VBA
I wrote some VBA code to prompt how many times to duplicate the rows.  I now want to add a feature to number in sequence the rows in column L.

```<code>Sub InsertRows()
    Dim I As Long, J As Integer, x As Integer, N As Long

    N = InputBox("type the number of rows to be inserted")

    For I = Range("A65000").End(xlUp).Row To 1 Step -1
'        MsgBox Range("A1").Value & vbNewLine & J
        x = N
            For J = 1 To N - 1
                Rows(I + J).Insert xlDown
                Rows(I).Copy
                Rows(I + J).PasteSpecial
                Range("L" & J).Value = J
            Next
    Next
    Range("A1").Select
    Application.CutCopyMode = False
End Sub
</code>```

For example, if I type "3" in the message box, the rows will copy 3 times for each original item but the values in column L will not sequentially number 1-3 correctly.  what is going wrong here?

The result comes out like this:

Result

答:
Loop logic 101... you have multiple problems here.

First, in your example of 3, "rows to be inserted" is not actually 3.  Since you use N-1, you are only inserting 2 rows.  Thus your J count is off.

Plus, Range("L" & J).Value is only ever changing rows 1 and 2.  And since you are doing everything from the botom up, it never sets anything to original row 3.  It only ever sets 2 to original row 2.  And original row 1 has a mix of 1 and 2.  Thus you need to add your I offset to the J value in that equation.

Plus, why the assign to x when it's never used?

Hope that helps a little. :)

Body:
I wrote some VBA code to prompt how many times to duplicate the rows.  I now want to add a feature to number in sequence the rows in column L.

Sub InsertRows()
    Dim I As Long, J As Integer, x As Integer, N As Long

    N = InputBox("type the number of rows to be inserted")

    For I = Range("A65000").End(xlUp).Row To 1 Step -1
'        MsgBox Range("A1").Value & vbNewLine & J
        x = N
            For J = 1 To N - 1
                Rows(I + J).Insert xlDown
                Rows(I).Copy
                Rows(I + J).PasteSpecial
                Range("L" & J).Value = J
            Next
    Next
    Range("A1").Select
    Application.CutCopyMode = False
End Sub

For example, if I type "3" in the message box, the rows will copy 3 times for each original item but the values in column L will not sequentially number 1-3 correctly.  what is going wrong here?

The result comes out like this:

Result


问:
Filtering a Key Value from a Dictionary in C#
I'm new to C# and am currently trying to figure out the best way to implement the following:

I have a list of species with an associated group:

```<code>Bird: "Budgie", "Parrot"
Dog: "Pitbull", "Labrador"
Cat: "Cheetah", "Lion"
</code>```

Given a string of an animal, I need to return its group.
eg. "Cheetah" would return "Cat".

I have implemented the following:

```<code>// create list one and store values
List<string> valSetOne = new List<string>();
valSetOne.Add("Budgie");
valSetOne.Add("Parrot");

// create list two and store values
List<String> valSetTwo = new List<String>();
valSetTwo.Add("Lion");
valSetTwo.Add("Cheetah");

// create list three and store values
List<String> valSetThree = new List<String>();
valSetThree.Add("Labrador");
valSetThree.Add("Pitbull");

// add values into map
map.Add("Bird", valSetOne);
map.Add("Cat", valSetTwo);
map.Add("Dog", valSetThree);

foreach(KeyValuePair<string, List<string>> kvp in map){
    foreach(string value in kvp.Value)
    {
       Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, value);
    }
}
</code>```

Instead of having a foreach loop, is there a faster way to find the key given an animal value?

//EDIT:

Currently trying to initialize with a Tuple

```<code>var tupleList = new List<Tuple<string, List<string>>>
{
   new Tuple<string, List<string>>("cat", { "cheetah", "lion"})

};
</code>```

I'm getting the following error:     Unexpected symbol `{'

答:
Using your existing dictionary structure, you can do this:

```<code>string cheetahGroup = map.FirstOrDefault(item =>
    item.Value.Contains("cheetah", StringComparer.OrdinalIgnoreCase)).Key;
</code>```

Note that if the animal doesn't exist, then cheetahGroup will be null. In the case above, it will be "Cat".

Body:
I'm new to C# and am currently trying to figure out the best way to implement the following:

I have a list of species with an associated group:

Bird: "Budgie", "Parrot"
Dog: "Pitbull", "Labrador"
Cat: "Cheetah", "Lion"

Given a string of an animal, I need to return its group.
eg. "Cheetah" would return "Cat".

I have implemented the following:

// create list one and store values
List<string> valSetOne = new List<string>();
valSetOne.Add("Budgie");
valSetOne.Add("Parrot");

// create list two and store values
List<String> valSetTwo = new List<String>();
valSetTwo.Add("Lion");
valSetTwo.Add("Cheetah");

// create list three and store values
List<String> valSetThree = new List<String>();
valSetThree.Add("Labrador");
valSetThree.Add("Pitbull");

// add values into map
map.Add("Bird", valSetOne);
map.Add("Cat", valSetTwo);
map.Add("Dog", valSetThree);

foreach(KeyValuePair<string, List<string>> kvp in map){
    foreach(string value in kvp.Value)
    {
       Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, value);
    }
}

Instead of having a foreach loop, is there a faster way to find the key given an animal value?

//EDIT:

Currently trying to initialize with a Tuple

var tupleList = new List<Tuple<string, List<string>>>
{
   new Tuple<string, List<string>>("cat", { "cheetah", "lion"})

};

I'm getting the following error:     Unexpected symbol `{'

Body:
Using your existing dictionary structure, you can do this:

string cheetahGroup = map.FirstOrDefault(item =>
    item.Value.Contains("cheetah", StringComparer.OrdinalIgnoreCase)).Key;

Note that if the animal doesn't exist, then cheetahGroup will be null. In the case above, it will be "Cat".


问:
Set ggplot title to reflect dplyr grouping
I've got a grouped dataframe generated in dplyr where each group reflects a unique combination of factor variable levels. I'd like to plot the different groups using code similar to this post. However, I can't figure out how to include two (or more) variables in the title of my plots, which is a hassle since I've got a bunch of different combinations.

Fake data and plotting code:

```<code>library(dplyr)
library(ggplot2)

spiris<-iris
spiris$site<-as.factor(rep(c("A","B","C")))
spiris$year<-as.factor(rep(2012:2016))
spiris$treatment<-as.factor(rep(1:2))

g<-spiris %>%
  group_by(site, Species) %>%
  do(plots=ggplot(data=.) +
       aes(x=Petal.Width)+geom_histogram()+
       facet_grid(treatment~year))
       ##Need code for title here
g[[3]] ##view plots
</code>```

I need the title of each plot to reflect both "site" and "Species".  Any ideas?

答:
Use split() %>% purrr::map2() instead of group_by() %>% do() like this:

```<code>spiris %>%
    split(list(.$site, .$Species)) %>%
    purrr::map2(.y = names(.),
         ~ ggplot(data=., aes(x=Petal.Width)) +
           geom_histogram()+
           facet_grid(treatment~year) +
           labs(title = .y) )
</code>```

Body:
I've got a grouped dataframe generated in dplyr where each group reflects a unique combination of factor variable levels. I'd like to plot the different groups using code similar to this post. However, I can't figure out how to include two (or more) variables in the title of my plots, which is a hassle since I've got a bunch of different combinations.

Fake data and plotting code:

library(dplyr)
library(ggplot2)

spiris<-iris
spiris$site<-as.factor(rep(c("A","B","C")))
spiris$year<-as.factor(rep(2012:2016))
spiris$treatment<-as.factor(rep(1:2))

g<-spiris %>%
  group_by(site, Species) %>%
  do(plots=ggplot(data=.) +
       aes(x=Petal.Width)+geom_histogram()+
       facet_grid(treatment~year))
       ##Need code for title here
g[[3]] ##view plots

I need the title of each plot to reflect both "site" and "Species".  Any ideas?

Body:
Use split() %>% purrr::map2() instead of group_by() %>% do() like this:

spiris %>%
    split(list(.$site, .$Species)) %>%
    purrr::map2(.y = names(.),
         ~ ggplot(data=., aes(x=Petal.Width)) +
           geom_histogram()+
           facet_grid(treatment~year) +
           labs(title = .y) )


问:
How can I assign a weight for frequency score to a graph's edge using Graph::Easy
How do I assign a weight or frequency score to an graph's edge using Graph::Easy?

I have a list of bigrams and their frequencies. I can easily create a (mathematical) graph of only the bigrams using Graph::Easy. The output is exactly what I desire. But when I try to "set_attribute" I get an error that says, "'frequency' is not a valid attribute name". What am I doing wrong? Using Graph::Easy, how do I make frequency a valid attribute?

```<code>#!/usr/bin/perl

# graph.pl - given a list of bigrams and their frequencies, output graphml

# require
use Graph::Easy;
use strict;

# initialize
my $graph = Graph::Easy->new;

# process the data
while ( <DATA> ) {

    # parse
    chop;
    my ( $nodes, $frequency ) = split( "\t", $_ );
    my ( $source, $target )   = split( ' ', $nodes );

    # update the graph
    my $edge = $graph->add_edge( $source, $target );

    # error happen here
    $edge->set_attribute( 'frequency', $frequency );

}

# output & done
print $graph->as_graphml();
exit;

# a set of bigrams and their frequencies
__DATA__
cds classroom   4
maximum registration    4
may want    3
anomalies within    2
resulting analysis  2
participants may    2
corpus without  2
journal articles    2
quickly learn   2
active reading  2
text mining     2
literally count     2
find patterns   2
14 million  2
digital humanities  2
humanities research     2
</code>```

答:
I played a bit with this module and it seems it doesn't accept arbitrary "attributes" but only a certain set of predefined ones.
Apparently 'frequency' is none of them.

I picked a sample from the documentation and replaced your

```<code>$edge->set_attribute( 'frequency', $frequency );
</code>```

with

```<code>$edge->set_attribute( 'label', $frequency );
</code>```

as they often mention label in the examples.

```<code>print $graph->as_ascii();
</code>```

then printed:

```<code>+--------------+  2   +--------------+
|      14      | ---> |   million    |
+--------------+      +--------------+
+--------------+  2   +--------------+  2   +----------+
|   digital    | ---> |  humanities  | ---> | research |
+--------------+      +--------------+      +----------+
+--------------+  2   +--------------+  3   +----------+
| participants | ---> |     may      | ---> |   want   |
+--------------+      +--------------+      +----------+
...
</code>```

Is that what you were after?

Eventually I found the complete documentation for Graph::Easy. The Attributes section lists the allowed attributes. I'm pretty sure there is a way to have custom attributes because the module has a method get_custom_attributes.

Body:
How do I assign a weight or frequency score to an graph's edge using Graph::Easy?

I have a list of bigrams and their frequencies. I can easily create a (mathematical) graph of only the bigrams using Graph::Easy. The output is exactly what I desire. But when I try to "set_attribute" I get an error that says, "'frequency' is not a valid attribute name". What am I doing wrong? Using Graph::Easy, how do I make frequency a valid attribute?

#!/usr/bin/perl

# graph.pl - given a list of bigrams and their frequencies, output graphml

# require
use Graph::Easy;
use strict;

# initialize
my $graph = Graph::Easy->new;

# process the data
while ( <DATA> ) {

    # parse
    chop;
    my ( $nodes, $frequency ) = split( "\t", $_ );
    my ( $source, $target )   = split( ' ', $nodes );

    # update the graph
    my $edge = $graph->add_edge( $source, $target );

    # error happen here
    $edge->set_attribute( 'frequency', $frequency );

}

# output & done
print $graph->as_graphml();
exit;

# a set of bigrams and their frequencies
__DATA__
cds classroom   4
maximum registration    4
may want    3
anomalies within    2
resulting analysis  2
participants may    2
corpus without  2
journal articles    2
quickly learn   2
active reading  2
text mining     2
literally count     2
find patterns   2
14 million  2
digital humanities  2
humanities research     2

Body:
I played a bit with this module and it seems it doesn't accept arbitrary "attributes" but only a certain set of predefined ones.
Apparently 'frequency' is none of them.

I picked a sample from the documentation and replaced your

$edge->set_attribute( 'frequency', $frequency );

with

$edge->set_attribute( 'label', $frequency );

as they often mention label in the examples.

print $graph->as_ascii();

then printed:

+--------------+  2   +--------------+
|      14      | ---> |   million    |
+--------------+      +--------------+
+--------------+  2   +--------------+  2   +----------+
|   digital    | ---> |  humanities  | ---> | research |
+--------------+      +--------------+      +----------+
+--------------+  2   +--------------+  3   +----------+
| participants | ---> |     may      | ---> |   want   |
+--------------+      +--------------+      +----------+
...

Is that what you were after?

Eventually I found the complete documentation for Graph::Easy. The Attributes section lists the allowed attributes. I'm pretty sure there is a way to have custom attributes because the module has a method get_custom_attributes.


问:
Import dataset into MongoDB
I am trying to insert this database into MongoDB using Studio 3T. I can import the bson without any issues (the countries and timezones) by selecting the parent folder and using BSON - mongodump folder option. However I cannot figure out how to import the split cities dataset.

I have tried all the options available on Studio3T and attempted to change the filename to gz however it always fails to import. I don't know what file format the cities are in.

Normally I do not have any issue importing but I cannot figure out how to do this. How would I achieve this?

The source DB is here https://github.com/VinceG/world-geo-data

答:
This data is nothing but a big .bson file that has been gzipped up and split into various parts. I was not able to import the .bson file successfully. However, I could unzip the file at least without an error using the following commands and GZip for Windows</p>

```<code>copy /b city_split_aa+city_split_ab+city_split_ac+city_split_ad+city_split_ae cities.bson.gz
gzip -d cities.bson
</code>```

Title: Import dataset into MongoDB

Body:
This data is nothing but a big .bson file that has been gzipped up and split into various parts. I was not able to import the .bson file successfully. However, I could unzip the file at least without an error using the following commands and GZip for Windows

copy /b city_split_aa+city_split_ab+city_split_ac+city_split_ad+city_split_ae cities.bson.gz
gzip -d cities.bson


问:
c++ csv data importing problems
I am a college student and as part of my final project for a c++ class we are assigned to read a csv file that has distance and force data and then find torque from it.  The problem that I am running into is how to actually get the data out of the csv file into a workable format.  Currently I have been trying to get it into a matrix, to do this though I will need to first determine the size of the csv file as it is supposed to take any size file.  This is the format of the data

Case 1,,,,,x_position (m),y_position (m),z_position (m),F_x (N),F_y (N),F_z (N)16.00,5.00,8.00,394.00,-18.00,396.0022.00,26.00,14.00,-324.00,-420.00,429.0028.00,25.00,21.00,73.00,-396.00,-401.006.00,9.00,12.00,-367.00,-137.00,-143.00

Also obviously the different data pieces (distance and forces) need to be put into different vectors or matrices.
This is what I have so far to try to find the number of lines in the file.

```<code>ifstream myfile("force_measurements.csv");
if(myfile.is_open()){
        string line;
        double num=0;
        getline(myfile, line);
        if(line==""){
            cout<<num<<endl;
            myfile.close();
        }
        else{
            num++;
        }
}
</code>```

After this works how would you go about putting the data into a matrix? or would a different format be easier? vectors was my other though.

答:
You have multiple questions.  Here's something I used for loading items out of a csv.  This gets you started, and you can figure out whether further organization of the data is useful.  I personally have classes that take a tokenized line and create an instance of themselves with them.

```<code>#include <boost/tokenizer.hpp>
typedef vector<string> csvLine;
void aFunction()
{
    string line;
    vector<csvLine> usedCollection;
    ifstream csvFile("myfile.csv", ios::in);
    if (!csvFile)
        return -1;

    while (getline(csvFile, line))
    {
        vector<string> tokenizedLine;
        boost::tokenizer<boost::escaped_list_separator<char> > tk(
            line, boost::escaped_list_separator<char>('\\', ',', '\"'));
        for (const string& str : tk)
        {
            tokenizedLine.push_back(str);
        }
        usedCollection.push_back(tokenizedLine);
    }
    csvFile.close();
}
</code>```

And so usedCollection is a collection of csvLines, where each of those is a collection of strings broken up by the separator character.

Title: c++ csv data importing problems

Body:
I am a college student and as part of my final project for a c++ class we are assigned to read a csv file that has distance and force data and then find torque from it.  The problem that I am running into is how to actually get the data out of the csv file into a workable format.  Currently I have been trying to get it into a matrix, to do this though I will need to first determine the size of the csv file as it is supposed to take any size file.  This is the format of the data

Case 1,,,,,x_position (m),y_position (m),z_position (m),F_x (N),F_y (N),F_z (N)16.00,5.00,8.00,394.00,-18.00,396.0022.00,26.00,14.00,-324.00,-420.00,429.0028.00,25.00,21.00,73.00,-396.00,-401.006.00,9.00,12.00,-367.00,-137.00,-143.00

Also obviously the different data pieces (distance and forces) need to be put into different vectors or matrices.
This is what I have so far to try to find the number of lines in the file.

ifstream myfile("force_measurements.csv");
if(myfile.is_open()){
        string line;
        double num=0;
        getline(myfile, line);
        if(line==""){
            cout<<num<<endl;
            myfile.close();
        }
        else{
            num++;
        }
}

After this works how would you go about putting the data into a matrix? or would a different format be easier? vectors was my other though.

Body:
You have multiple questions.  Here's something I used for loading items out of a csv.  This gets you started, and you can figure out whether further organization of the data is useful.  I personally have classes that take a tokenized line and create an instance of themselves with them.

#include <boost/tokenizer.hpp>
typedef vector<string> csvLine;
void aFunction()
{
    string line;
    vector<csvLine> usedCollection;
    ifstream csvFile("myfile.csv", ios::in);
    if (!csvFile)
        return -1;

    while (getline(csvFile, line))
    {
        vector<string> tokenizedLine;
        boost::tokenizer<boost::escaped_list_separator<char> > tk(
            line, boost::escaped_list_separator<char>('\\', ',', '\"'));
        for (const string& str : tk)
        {
            tokenizedLine.push_back(str);
        }
        usedCollection.push_back(tokenizedLine);
    }
    csvFile.close();
}

And so usedCollection is a collection of csvLines, where each of those is a collection of strings broken up by the separator character.


问:
jQuery & Bootstrap Slide Up Alert
I have an alert:

```<code><div class="alert alert-success fade show" id='success-alert' role="alert">
        {{ message }}
      </div>
</code>```

I have a button:

```<code><input name="submit" value="Submit" class="btn btn-primary" id="submit-id-submit" type="submit" method="post">
</code>```

When the button is clicked, the alert appears. I want the alert to slide up slowly using jQuery's .slideUp(). Here is my attempt:

```<code><script>
  $(document).ready (function(){
              $("#success-alert").hide();
              $("#submit-id-submit").click(function showAlert() {
                  $("#success-alert").fadeTo(2000, 2000).slideUp(500, function(){
                 $("#success-alert").slideUp(500);
                  });
              });
   });
</script>
</code>```

This causes the alert to appear, and then abruptly disappear quickly (shorter than two seconds). I believe the alert is somehow being called twice, because when I change the 500 (all three) to 2000, the alert shows up, it slides up correctly, then a new alert appears and abruptly disappears.

How should I achieve the slow slide up, once?

答:
The classes "fade" and "show" are the reason for the weird behavior in your code.

Is this what you're looking for?

JS FIDDLE DEMO

I got rid of those classes and added some CSS.

Relevant code:

```<code>$("#submit-id-submit").click(function () {
    $("#success-alert").show(); // use slide down for animation
    setTimeout(function () {
      $("#success-alert").slideUp(500);
    }, 2000);
});
</code>```

Hope this helps. :)

Title: jQuery & Bootstrap Slide Up Alert

Body:
I have an alert:

        {{ message }}

I have a button:

<input name="submit" value="Submit" class="btn btn-primary" id="submit-id-submit" type="submit" method="post">

When the button is clicked, the alert appears. I want the alert to slide up slowly using jQuery's .slideUp(). Here is my attempt:

This causes the alert to appear, and then abruptly disappear quickly (shorter than two seconds). I believe the alert is somehow being called twice, because when I change the 500 (all three) to 2000, the alert shows up, it slides up correctly, then a new alert appears and abruptly disappears.

How should I achieve the slow slide up, once?

Body:
The classes "fade" and "show" are the reason for the weird behavior in your code.

Is this what you're looking for?

JS FIDDLE DEMO

I got rid of those classes and added some CSS.

Relevant code:

$("#submit-id-submit").click(function () {
    $("#success-alert").show(); // use slide down for animation
    setTimeout(function () {
      $("#success-alert").slideUp(500);
    }, 2000);
});

Hope this helps. :)


问:
After creating separate Models and Controllers projects, I get "no suitable method found to override" on my Initialize method declaration
This is driving me insane... I am reorganizing my MVC app into a Models project and a Controllers project, and then the main application as a project.  So, everything is working good so far except...

Whenever I go to "Rebuild" my controllers project, I get this error:

Controllers.AccountController.Initialize(System.Web.Routing.RequestContext)': no suitable method found to override.

Keep in mind that AccountController.cs was automatically placed in my application by Visual Studio, and this was all working fine when the Controllers were within my main project.  I think it might have to do with the ASPNETDB.MDF file that this AccountController.cs file references to authenticate users as they log in, since this database stayed within my main project and didn't follow the Controllers project.  Thoughts on that??

Here's the Initialize method on my AccountController:

```<code>        protected override void Initialize(RequestContext requestContext)
    {
        if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
        if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

        base.Initialize(requestContext);
    }
</code>```

PLEASE HELP!!! Thanks in advance!!

答: this error message suggests that your AccountController class isn't being derived from MVC's Controller base class.  </p>

Body:
This is driving me insane... I am reorganizing my MVC app into a Models project and a Controllers project, and then the main application as a project.  So, everything is working good so far except...

Whenever I go to "Rebuild" my controllers project, I get this error:

Controllers.AccountController.Initialize(System.Web.Routing.RequestContext)': no suitable method found to override.

Keep in mind that AccountController.cs was automatically placed in my application by Visual Studio, and this was all working fine when the Controllers were within my main project.  I think it might have to do with the ASPNETDB.MDF file that this AccountController.cs file references to authenticate users as they log in, since this database stayed within my main project and didn't follow the Controllers project.  Thoughts on that??

Here's the Initialize method on my AccountController:

        protected override void Initialize(RequestContext requestContext)
    {
        if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
        if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

        base.Initialize(requestContext);
    }

PLEASE HELP!!! Thanks in advance!!


问:
Swift 4 - How to set and show a new root view controller from current view controller
Struggling a couple of days with this...

I have set a rootVC from AppDelegate in didFinishLaunchingWithOptions and this is working fine.

Now from that rootVC I want that, if some condition is met, eg. if x=y a new rootVC is set and displayed.

I stack overflowed long long time, found different solutions, but none is working.

The below is compiling, and executing, I checked with breakpoint, but nothing shows up in the app.

```<code>animated    Bool    false
self    Regional2.IrelandViewController 0x0000000102b0ff30
newViewController   Regional2.IrelandMain   0x0000000102d0d300
customViewControllersArray  NSArray 0x00000001c000b620
ObjectiveC.NSObject NSObject
Exception State Registers
far unsigned long   0x00000001b0a7ba78
esr unsigned int    0x92000007
exception   unsigned int    0x00000000
Floating Point Registers
General Purpose Registers
</code>```

and the piece of the code . . .

```<code>override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let newViewController = self.storyboard?.instantiateViewController(withIdentifier: "IrelandMain") as! IrelandMain

    let customViewControllersArray : NSArray = [newViewController]

    self.navigationController?.viewControllers = customViewControllersArray as! [UIViewController]
    self.navigationController?.pushViewController(newViewController, animated: true)
</code>```

}

Please notice that navigationController show produces the same output. Nothing changes.

答:
That code works for me.
It simply replaces the whole UIWindow.

When I tried to only replace the rootViewController it did it but it created another one (so I had two loaded viewControllers in the view hierarchy)

```<code>if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
    // If we only reloads the rootViewController than the main window has 2 subviews
    // The older cannot be removed and the new can be removed.
    // The workaround I found is to replace the whole UIWindow with new one
    let root = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateInitialViewController()
    let newWindow = UIWindow()
    appDelegate.replaceWindow(newWindow)
    newWindow.rootViewController = root
}
</code>```

And in your AppDelegate

```<code>func replaceWindow(_ newWindow: UIWindow) {
    if let oldWindow = window {
        newWindow.frame = oldWindow.frame
        newWindow.windowLevel = oldWindow.windowLevel
        newWindow.screen = oldWindow.screen
        newWindow.isHidden = false
        window = newWindow
        oldWindow.removeFromSuperview()
    }
}
</code>```

Body:
Struggling a couple of days with this...

I have set a rootVC from AppDelegate in didFinishLaunchingWithOptions and this is working fine.

Now from that rootVC I want that, if some condition is met, eg. if x=y a new rootVC is set and displayed.

I stack overflowed long long time, found different solutions, but none is working.

The below is compiling, and executing, I checked with breakpoint, but nothing shows up in the app.

animated    Bool    false
self    Regional2.IrelandViewController 0x0000000102b0ff30
newViewController   Regional2.IrelandMain   0x0000000102d0d300
customViewControllersArray  NSArray 0x00000001c000b620
ObjectiveC.NSObject NSObject
Exception State Registers
far unsigned long   0x00000001b0a7ba78
esr unsigned int    0x92000007
exception   unsigned int    0x00000000
Floating Point Registers
General Purpose Registers

and the piece of the code . . .

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let newViewController = self.storyboard?.instantiateViewController(withIdentifier: "IrelandMain") as! IrelandMain

    let customViewControllersArray : NSArray = [newViewController]

    self.navigationController?.viewControllers = customViewControllersArray as! [UIViewController]
    self.navigationController?.pushViewController(newViewController, animated: true)

}

Please notice that navigationController show produces the same output. Nothing changes.

Body:
That code works for me.
It simply replaces the whole UIWindow.

When I tried to only replace the rootViewController it did it but it created another one (so I had two loaded viewControllers in the view hierarchy)

if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
    // If we only reloads the rootViewController than the main window has 2 subviews
    // The older cannot be removed and the new can be removed.
    // The workaround I found is to replace the whole UIWindow with new one
    let root = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateInitialViewController()
    let newWindow = UIWindow()
    appDelegate.replaceWindow(newWindow)
    newWindow.rootViewController = root
}

And in your AppDelegate

func replaceWindow(_ newWindow: UIWindow) {
    if let oldWindow = window {
        newWindow.frame = oldWindow.frame
        newWindow.windowLevel = oldWindow.windowLevel
        newWindow.screen = oldWindow.screen
        newWindow.isHidden = false
        window = newWindow
        oldWindow.removeFromSuperview()
    }
}


问:
Subscribe in Angular2 doesn't work
I have a question about subscribe in Angular2, please, help me...

I have two functions, first function return the value and the second function has to use it.

Here is my example

This is the first function, everything is ok and works works, and it returns this.mapCenter, this value I need later

```<code>   prevId () {
     let name, id, lat, lng;
     this.router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(e => {

        if (this.previousUrl !== undefined) {

          this.clickedMarker = this.previousUrl.substring(10);

          for (let i = 0; i < this.data.length; i++) {
            if(this.data[i].code === this.clickedMarker) {
              id = this.data[i].code;
              name = this.data[i].displayName;
              lat = parseFloat(this.data[i].lat);
              lng = parseFloat(this.data[i].lng);
              this.mapCenter = L.latLng([lat, lng]);
            }
          }
          // Open up the popup, when user comes back
          let myMarker = new L.Marker(this.mapCenter, {icon: mapUI.marker}).addTo(this.map);
          let mark = this.popupHtmlGenerate( name, id, this.mapCenter );
          myMarker.bindPopup(mark).openPopup();
        } else {
          console.log('not yet');
          this.mapCenter = L.latLng([48.145, 11.58]);
        }
        this.previousUrl = (e as NavigationEnd).url;
        return this.mapCenter;

      });
  }
</code>```

Now I need to use the value this. mapCenter of this function as a parameter in second function.

```<code>this.mapInitialize(this.mapCenter);
</code>```

The both functions are in the ngOnInit

```<code>  ngOnInit() {
    this.prevId();

    this.mapInitialize(this.mapCenter);
  }
</code>```

I tried something like this.prevId().subscribe, but I get error subscribe doesn't exist on type void ...

UPD: I can't assign second function in the first function. I need the second function later and if I assign it inside another function, everything brakes

答:
subscribe doesn't return values.  Its next interface is:

```<code>(value: any) => void
</code>```

It only receives values.  This is how asynchronous event processing works.  As it stands, you need to move your mapInitialize function:

```<code>prevId () {
 let name, id, lat, lng;
 this.router.events
  .filter(event => event instanceof NavigationEnd)
  .subscribe(e => {

    if (this.previousUrl !== undefined) {

      this.clickedMarker = this.previousUrl.substring(10);

      for (let i = 0; i < this.data.length; i++) {
        if(this.data[i].code === this.clickedMarker) {
          id = this.data[i].code;
          name = this.data[i].displayName;
          lat = parseFloat(this.data[i].lat);
          lng = parseFloat(this.data[i].lng);
          this.mapCenter = L.latLng([lat, lng]);
        }
      }
      // Open up the popup, when user comes back
      let myMarker = new L.Marker(this.mapCenter, {icon: mapUI.marker}).addTo(this.map);
      let mark = this.popupHtmlGenerate( name, id, this.mapCenter );
      myMarker.bindPopup(mark).openPopup();
    } else {
      console.log('not yet');
      this.mapCenter = L.latLng([48.145, 11.58]);
    }
    this.previousUrl = (e as NavigationEnd).url;
    this.mapInitialize(this.mapCenter);

  });
}

ngOnInit() {
  this.prevId();
}
</code>```

This is the quickest way to make it work, but it could be substantially cleaned up.

Title: Subscribe in Angular2 doesn't work

Body:
I have a question about subscribe in Angular2, please, help me...

I have two functions, first function return the value and the second function has to use it.

Here is my example

This is the first function, everything is ok and works works, and it returns this.mapCenter, this value I need later

   prevId () {
     let name, id, lat, lng;
     this.router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(e => {

        if (this.previousUrl !== undefined) {

          this.clickedMarker = this.previousUrl.substring(10);

          for (let i = 0; i < this.data.length; i++) {
            if(this.data[i].code === this.clickedMarker) {
              id = this.data[i].code;
              name = this.data[i].displayName;
              lat = parseFloat(this.data[i].lat);
              lng = parseFloat(this.data[i].lng);
              this.mapCenter = L.latLng([lat, lng]);
            }
          }
          // Open up the popup, when user comes back
          let myMarker = new L.Marker(this.mapCenter, {icon: mapUI.marker}).addTo(this.map);
          let mark = this.popupHtmlGenerate( name, id, this.mapCenter );
          myMarker.bindPopup(mark).openPopup();
        } else {
          console.log('not yet');
          this.mapCenter = L.latLng([48.145, 11.58]);
        }
        this.previousUrl = (e as NavigationEnd).url;
        return this.mapCenter;

      });
  }

Now I need to use the value this. mapCenter of this function as a parameter in second function.

this.mapInitialize(this.mapCenter);

The both functions are in the ngOnInit

  ngOnInit() {
    this.prevId();

    this.mapInitialize(this.mapCenter);
  }

I tried something like this.prevId().subscribe, but I get error subscribe doesn't exist on type void ...

UPD: I can't assign second function in the first function. I need the second function later and if I assign it inside another function, everything brakes

Body:
subscribe doesn't return values.  Its next interface is:

(value: any) => void

It only receives values.  This is how asynchronous event processing works.  As it stands, you need to move your mapInitialize function:

prevId () {
 let name, id, lat, lng;
 this.router.events
  .filter(event => event instanceof NavigationEnd)
  .subscribe(e => {

    if (this.previousUrl !== undefined) {

      this.clickedMarker = this.previousUrl.substring(10);

      for (let i = 0; i < this.data.length; i++) {
        if(this.data[i].code === this.clickedMarker) {
          id = this.data[i].code;
          name = this.data[i].displayName;
          lat = parseFloat(this.data[i].lat);
          lng = parseFloat(this.data[i].lng);
          this.mapCenter = L.latLng([lat, lng]);
        }
      }
      // Open up the popup, when user comes back
      let myMarker = new L.Marker(this.mapCenter, {icon: mapUI.marker}).addTo(this.map);
      let mark = this.popupHtmlGenerate( name, id, this.mapCenter );
      myMarker.bindPopup(mark).openPopup();
    } else {
      console.log('not yet');
      this.mapCenter = L.latLng([48.145, 11.58]);
    }
    this.previousUrl = (e as NavigationEnd).url;
    this.mapInitialize(this.mapCenter);

  });
}

ngOnInit() {
  this.prevId();
}

This is the quickest way to make it work, but it could be substantially cleaned up.


问:
Initialization Configuration issues to integrate pyodbc with MSSQL Server via Web Browser
Initialization Configuration issues to integrate pyodbc with MSSQL Server via Web Browser

As I'm new to Python Web Programming

I need to code by clicking submit button that should retrive all the tables in the person database to the Web Browser via localhost.

What should be the server configuration to run with localhost:

Apache HTTP Server (or)

WSGI module (or)

Any Other Module/Server (pls Specify)

Check this below links that I have configured:

By adding one statement import pyodbc causes Internal Server Error in Apache HTTP Server

Importing pyodbc results as Internal server error in Apache HTTP Server

What should be my configuration to load pyodbc module on Apache Server to run simple queries mssql server database

I had tried with Apache HTTP Server with one command import pyodbc results in 500 Internal Server Error. But rest of the things worked fine with POST as well as in Python Shell.

I had coded this way. Kindly had anyone worked with Web Server via localhost let me know what should we need to add/modify with the below code

index.html

```<code><form action="/cgi-bin/hello_get.py" method="post">
Click the submmit button to retrive all the tables
<input type="submit" value="Submit" />
</form>
</code>```

hello_get.py

```<code>import pyodbc
cnxn = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};"
                      "Server=DESKTOP-C6RS3DO;"
                      "Database=demo2016;"
                      "Trusted_Connection=yes;")

cursor = cnxn.cursor()
cursor.execute('SELECT * FROM person')

print("Content-Type: text/html")
print("")
print("<html><head>")
print("")
print("</head><body>")
for row in cursor:
    print('row = %r' % (row,))

print("Hello from Python.")
print("</body></html>")

cursor.close()
cnxn.close()
</code>```

Do I need any extra modules and code from the above code?

 error.log

```<code>[cgi:error] [pid 9344:tid 1264] [client ::1:52332] AH01215:

End of script output before headers: hello_get.py, referer: http://localhost/index.html
Traceback (most recent call last):\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
File "C:\\Apache24\\htdocs\\hello_get.py", line 6, in <module>\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
import pyodbc\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
ImportError: No module named pyodbc\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
</code>```

But whenever try to load the module from httpd.config by adding

```<code> LoadModule pyodbc_module
 "c:/users/desktop/appdata/local/programs/python/python36-32/lib/site-packages/pyodbc.cp36-win32.pyd"
</code>```

and restarting the server results in httpd -k restart

```<code>httpd: Syntax error on line 576 of C:/Apache24/conf/httpd.conf: Can't locate API module structure `pyodbc_module' in file C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages/pyodbc.cp36-win32.pyd: No error
</code>```

答:
The problem appears to be that Apache can't find the Python path. Don't forget, Apache runs as a different user on your system. If Apache runs as a user called www-user, then www-user needs to be able to import pyodbc.

There are two possible solutions here, if you want to stick with CGI instead of going to a full WSGI app.

First, in your Python script, you may be able to do this before any import statements:

```<code>sys.path.insert(0, 'c:\path\to\python-site-packages\')
</code>```

Or, in your Apache configuration:

```<code>SetEnv PYTHONPATH "c:\path\to\python-site-packages\"
</code>```

Good luck!

Body:
Initialization Configuration issues to integrate pyodbc with MSSQL Server via Web Browser

As I'm new to Python Web Programming

I need to code by clicking submit button that should retrive all the tables in the person database to the Web Browser via localhost.

What should be the server configuration to run with localhost:

Apache HTTP Server (or)

WSGI module (or)

Any Other Module/Server (pls Specify)

Check this below links that I have configured:

By adding one statement import pyodbc causes Internal Server Error in Apache HTTP Server

Importing pyodbc results as Internal server error in Apache HTTP Server

What should be my configuration to load pyodbc module on Apache Server to run simple queries mssql server database

I had tried with Apache HTTP Server with one command import pyodbc results in 500 Internal Server Error. But rest of the things worked fine with POST as well as in Python Shell.

I had coded this way. Kindly had anyone worked with Web Server via localhost let me know what should we need to add/modify with the below code

index.html

<form action="/cgi-bin/hello_get.py" method="post">
Click the submmit button to retrive all the tables
<input type="submit" value="Submit" />
</form>

hello_get.py

import pyodbc
cnxn = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};"
                      "Server=DESKTOP-C6RS3DO;"
                      "Database=demo2016;"
                      "Trusted_Connection=yes;")

cursor = cnxn.cursor()
cursor.execute('SELECT * FROM person')

print("Content-Type: text/html")
print("")
print("")
print("")
print("")
for row in cursor:
    print('row = %r' % (row,))

print("Hello from Python.")
print("")

cursor.close()
cnxn.close()

Do I need any extra modules and code from the above code?

 error.log

[cgi:error] [pid 9344:tid 1264] [client ::1:52332] AH01215:

End of script output before headers: hello_get.py, referer: http://localhost/index.html
Traceback (most recent call last):\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
File "C:\\Apache24\\htdocs\\hello_get.py", line 6, in <module>\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
import pyodbc\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
ImportError: No module named pyodbc\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html

But whenever try to load the module from httpd.config by adding

 LoadModule pyodbc_module
 "c:/users/desktop/appdata/local/programs/python/python36-32/lib/site-packages/pyodbc.cp36-win32.pyd"

and restarting the server results in httpd -k restart

httpd: Syntax error on line 576 of C:/Apache24/conf/httpd.conf: Can't locate API module structure `pyodbc_module' in file C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages/pyodbc.cp36-win32.pyd: No error

Body:
The problem appears to be that Apache can't find the Python path. Don't forget, Apache runs as a different user on your system. If Apache runs as a user called www-user, then www-user needs to be able to import pyodbc.

There are two possible solutions here, if you want to stick with CGI instead of going to a full WSGI app.

First, in your Python script, you may be able to do this before any import statements:

sys.path.insert(0, 'c:\path\to\python-site-packages\')

Or, in your Apache configuration:

SetEnv PYTHONPATH "c:\path\to\python-site-packages\"

Good luck!


问:
React/Redux controlled input with validation
Lets imagine we want an input for a "product" (stored in redux) price value.

I'm struggle to come up with the best way to handle input constraints.  For simplicity, lets just focus on the constraint that product.price cannot be empty.

It seems like the 2 options are:

1: Controlled

Implementation: The input value is bound to product.price. On change dispatches the changePrice() action.

The main issue here is that if we want to prevent an empty price from entering the product store, we essentially block the user from clearing the input field.  This isn't ideal as it makes it very hard to change the first digit of the number (you have to select it and replace it)!

2: Using defaultValue

Implementation: We set the price initially using input defaultValue, that allows us to control when we want to actually dispatch changePrice() actions and we can do validation handling in the onChange handler.

This works well, unless the product.price is ever updated from somewhere other than the input change event (for example, an applyDiscount action).  Since defaultValue doesn't cause rerenders, the product.price and the input are now out of sync!

So what am I missing?

There must be a simple & elegant solution to this problem but I just can't seem to find it!

答:
What i would do in this case is to validate the input onBlur instead of onChange.

For example consider these validations in the flowing snippet:

The input can't be empty.

The input should not contain "foo".

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      myVal: '',
      error: ''
    }
  }

  setError = error => {
    this.setState({ error });
  }

  onChange = ({ target: { value } }) => {
    this.setState({ myVal: value })
  }

  validateInput = ({ target: { value } }) => {
    let nextError = '';
    if (!value.trim() || value.length < 1) {
      nextError = ("Input cannot be empty!")
    } else if (~value.indexOf("foo")) {
      nextError = ('foo is not alowed!');
    }

    this.setError(nextError);
  }

  render() {
    const { myVal, error } = this.state;
    return (

        <input value={myVal} onChange={this.onChange} onBlur={this.validateInput} />
        {error &&
{error}
}

    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

Edit

As a followup to your comments.

To make this solution more generic, i would pass the component a predicate function as a prop, only when the function will return a valid result i would call the onChange that passed from the parent or whatever method you pass that updating the store.

This way you can reuse this pattern in other components and places on your app (or even other projects).

Body:
What i would do in this case is to validate the input onBlur instead of onChange.

For example consider these validations in the flowing snippet:

The input can't be empty.

The input should not contain "foo".

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      myVal: '',
      error: ''
    }
  }

  setError = error => {
    this.setState({ error });
  }

  onChange = ({ target: { value } }) => {
    this.setState({ myVal: value })
  }

  validateInput = ({ target: { value } }) => {
    let nextError = '';
    if (!value.trim() || value.length < 1) {
      nextError = ("Input cannot be empty!")
    } else if (~value.indexOf("foo")) {
      nextError = ('foo is not alowed!');
    }

    this.setError(nextError);
  }

  render() {
    const { myVal, error } = this.state;
    return (
      <div>
        <input value={myVal} onChange={this.onChange} onBlur={this.validateInput} />
        {error && <div>{error}</div>}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Edit

As a followup to your comments.

To make this solution more generic, i would pass the component a predicate function as a prop, only when the function will return a valid result i would call the onChange that passed from the parent or whatever method you pass that updating the store.

This way you can reuse this pattern in other components and places on your app (or even other projects).


问:
Can I detect and handle MySQL Warnings with PHP?
I'm dealing with a MySQL table that defines the JobName column as UNIQUE.  If somebody tries to save a new Job to the database using a JobName that is already in the database, MySQL throws a warning.

I would like to be able to detect this warning, just like an error, in my PHP script and deal with it appropriately.  Ideally I would like to know what kind of warning MySQL has thrown so that I can branch the code to handle it.

Is this possible?  If not, is it because MySQL doesn't have this ability, PHP doesn't have this ability, or both?

答:
For warnings to be "flagged" to PHP natively would require changes to the mysql/mysqli driver, which is obviously beyond the scope of this question.  Instead you're going to have to basically check every query you make on the database for warnings:

```<code>$warningCountResult = mysql_query("SELECT @@warning_count");
if ($warningCountResult) {
    $warningCount = mysql_fetch_row($warningCountResult );
    if ($warningCount[0] > 0) {
        //Have warnings
        $warningDetailResult = mysql_query("SHOW WARNINGS");
        if ($warningDetailResult ) {
            while ($warning = mysql_fetch_assoc($warningDetailResult) {
                //Process it
            }
        }
    }//Else no warnings
}
</code>```

Obviously this is going to be hideously expensive to apply en-mass, so you might need to carefully think about when and how warnings may arise (which may lead you to refactor to eliminate them).

For reference, MySQL SHOW WARNINGS

Of course, you could dispense with the initial query for the SELECT @@warning_count, which would save you a query per execution, but I included it for pedantic completeness.

OwnerDisplayName: Kyle Noland

Body:
For warnings to be "flagged" to PHP natively would require changes to the mysql/mysqli driver, which is obviously beyond the scope of this question.  Instead you're going to have to basically check every query you make on the database for warnings:

$warningCountResult = mysql_query("SELECT @@warning_count");
if ($warningCountResult) {
    $warningCount = mysql_fetch_row($warningCountResult );
    if ($warningCount[0] > 0) {
        //Have warnings
        $warningDetailResult = mysql_query("SHOW WARNINGS");
        if ($warningDetailResult ) {
            while ($warning = mysql_fetch_assoc($warningDetailResult) {
                //Process it
            }
        }
    }//Else no warnings
}

Obviously this is going to be hideously expensive to apply en-mass, so you might need to carefully think about when and how warnings may arise (which may lead you to refactor to eliminate them).

For reference, MySQL SHOW WARNINGS

Of course, you could dispense with the initial query for the SELECT @@warning_count, which would save you a query per execution, but I included it for pedantic completeness.

OwnerDisplayName: iAn

ContentLicense: CC BY-SA 4.0