问:
Auto file updater in C#?
In c# i m creating a application based on Thread, that read a text file from Computer(actually remote computer) selected by user. if user makes any changes in original file then this application should display the modified file(whole). </p>

<p>Successfully its doing but, thread that I am using don't know how and where to place that it continuous read the original file from background. My application gets hangs with this code    </p>

```<code>public partial class FormFileUpdate : Form
{
    // This delegate enables asynchronous calls for setting the text property on a richTextBox control.
    delegate void UpdateTextCallback(object text);

    // This thread is used to demonstrate both thread-safe and unsafe ways to call a Windows Forms control.
    private Thread autoReadThread = null;

    public FormFileUpdate()
    {
        InitializeComponent();

        //Creating Thread
        this.autoReadThread = new Thread(new ParameterizedThreadStart(UpdateText));
    }

    private void openToolStripButton_Click(object sender, EventArgs e)
    {
        OpenFileDialog fileOpen = new OpenFileDialog();
        fileOpen.Title = "Select a text document";
        fileOpen.Filter = @"Text File|*.txt|Word Document|*.rtf|MS office Documnet|*.doc|See All files|*.*";
        fileOpen.FilterIndex = 1;
        fileOpen.RestoreDirectory = true;
        fileOpen.Multiselect = false;
        if (fileOpen.ShowDialog() == DialogResult.OK)
        {
            //Created Thread will start here
            this.autoReadThread.Start(fileOpen.FileName);
        }
    }

    private void UpdateText(object fileName)
    {
        StreamReader readerStream = null;
        while(true)
        {
            if (this.richTextBox1.InvokeRequired)
            {
                UpdateTextCallback back = new UpdateTextCallback(UpdateText);
                this.Invoke(back, new object[] { fileName });
            }
            else
            {
                try
                {
                    string fileToUpdate = (string)fileName;
                    readerStream = new StreamReader(fileToUpdate);
                    richTextBox1.Text = readerStream.ReadToEnd();
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                finally
                {
                    if (readerStream != null)
                    {
                        readerStream.Close();
                        Thread.Sleep(100);
                    }
                }
            }
        }
    }
}
</code>```

答:
Additional note to what Itay wrote:

You are calling Thread.Sleep from the GUI thread! Why do you even need to make a delay after closing the file? If you do need this delay for some reason (e.g. to avoid reading the file too frequently), don't put this delay on the GUI thread, because this will make your application unresponsive.

EDIT: answering your question in the comment

A possible cleaner way would be to set a Timer which would invoke a BackgroundWorker every x seconds.

The BackgroundWorker makes it very easy to run code in a background thread, and to have a callback run on the GUI thread when the work is completed. And you don't have to deal with Invoke and InvokeRequired directly.

Furthermore, I would create a class which wraps a BackgroundWorker to make it easy to pass data from the operation of reading the file (in the background thread), to updating the UI (in the GUI thread).

Title: Auto file updater in C#?

Body:
In c# i m creating a application based on Thread, that read a text file from Computer(actually remote computer) selected by user. if user makes any changes in original file then this application should display the modified file(whole).

Successfully its doing but, thread that I am using don't know how and where to place that it continuous read the original file from background. My application gets hangs with this code

public partial class FormFileUpdate : Form
{
    // This delegate enables asynchronous calls for setting the text property on a richTextBox control.
    delegate void UpdateTextCallback(object text);

    // This thread is used to demonstrate both thread-safe and unsafe ways to call a Windows Forms control.
    private Thread autoReadThread = null;

    public FormFileUpdate()
    {
        InitializeComponent();

        //Creating Thread
        this.autoReadThread = new Thread(new ParameterizedThreadStart(UpdateText));
    }

    private void openToolStripButton_Click(object sender, EventArgs e)
    {
        OpenFileDialog fileOpen = new OpenFileDialog();
        fileOpen.Title = "Select a text document";
        fileOpen.Filter = @"Text File|*.txt|Word Document|*.rtf|MS office Documnet|*.doc|See All files|*.*";
        fileOpen.FilterIndex = 1;
        fileOpen.RestoreDirectory = true;
        fileOpen.Multiselect = false;
        if (fileOpen.ShowDialog() == DialogResult.OK)
        {
            //Created Thread will start here
            this.autoReadThread.Start(fileOpen.FileName);
        }
    }

    private void UpdateText(object fileName)
    {
        StreamReader readerStream = null;
        while(true)
        {
            if (this.richTextBox1.InvokeRequired)
            {
                UpdateTextCallback back = new UpdateTextCallback(UpdateText);
                this.Invoke(back, new object[] { fileName });
            }
            else
            {
                try
                {
                    string fileToUpdate = (string)fileName;
                    readerStream = new StreamReader(fileToUpdate);
                    richTextBox1.Text = readerStream.ReadToEnd();
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                finally
                {
                    if (readerStream != null)
                    {
                        readerStream.Close();
                        Thread.Sleep(100);
                    }
                }
            }
        }
    }
}


来源: stackexchange

问:
Spring BeanFactory and type search
When using Spring and combining both ProxyFactoryBean and @Inject Provider<>, a massive amount of objects ends up being created during startup.

I've identified the cause as the DefaultListableBeanFactory.doGetBeanNamesForType method. The "@Inject Provider<>" is satisfied by iterating over all bean definitions and searching for one that can satisfy the provider generic parameter. When a FactoryBean is encountered, it is fully initialized first and only then it is queried getObjectType(). However, ProxyFactoryBean are often setup in the applicationContext.xml with a dependency on the bean they proxy. Fully initializing the ProxyFactoryBean cause an instantiation of the inner bean.

All of that is well, unless the inner bean cannot be instantiated at that time - e.g. because it relies on some other beans that cannot be initialized until the original bean (the one with the Provider) is. There is not cyclic dependency, only over-eager initialization.

Example:

```<code>class Bean1 { @Inject Provider<X> provider;}
class Bean2 { @Inject Bean1 bean1;}

applicationContext.xml:
<bean id="bean1" class="com.rb.springissues.sample.Bean1"/>
<bean id="bean2" class="com.rb.springissues.sample.Bean2"/>
<bean id="bean2Factory" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="target" ref="bean2"/>
    <property name="proxyTargetClass" value="true"/>
</bean>
</code>```

In the above example the flow is (fully managed by Spring):

Instantiate bean1. Try to initialize bean1 and discover it has a Provider<X>.

Go through all BeanDefinition in the context. For each:

if it's a "normal" bean, evaluate the class to see if it fits.

if it's a FactoryBean, try to instantiate and initialize the FactoryBean to see what "getObjectType()" would return.

In order to initialize bean2Factory, it needs to be fed with an instance of bean2. So Spring tries to instantiate and  initialize bean2.

However - bean2 cannot be initialized since it relies on bean1 - causing Spring to throw a cyclic dependency error.

If the FactoryObject was created correctly, Spring now asks for the type and cache the response ("good path").

If we got an exception (the cyclic dependency error) it's caught and ignored, but the result isn't cached - so if we get another bean it'll do the same thing again (and again and again...)

See https://github.com/bironran/spring_issues_proxy_factory for the full description and a sample.

I have observed real-world application with about 500 defined beans instantiate and attempt to initialize over 300,000 objects (the same beans again and again) due to this issue. The startup is delayed by minutes and GC spike.

Moreover, this issue has exponential growth - any new dependency that cannot be resolved can double the time the application takes to load.

Would love to hear suggestions on how to solve (see the github project).

答:
Solution turned out to be easy - replace <property name="target" ref="bean2"/> with:

<property name="targetName">
  <idref bean="bean2"/>
</property>
<property name="targetClass" value="com.rb.springissues.sample.Bean2"/>

This causes a delayed binding of bean2 - so the factory can be initialized without a Bean2 instance.

ContentLicense: CC BY-SA 3.0

Title: Spring BeanFactory and type search

Body:
When using Spring and combining both ProxyFactoryBean and @Inject Provider<>, a massive amount of objects ends up being created during startup.

I've identified the cause as the DefaultListableBeanFactory.doGetBeanNamesForType method. The "@Inject Provider<>" is satisfied by iterating over all bean definitions and searching for one that can satisfy the provider generic parameter. When a FactoryBean is encountered, it is fully initialized first and only then it is queried getObjectType(). However, ProxyFactoryBean are often setup in the applicationContext.xml with a dependency on the bean they proxy. Fully initializing the ProxyFactoryBean cause an instantiation of the inner bean.

All of that is well, unless the inner bean cannot be instantiated at that time - e.g. because it relies on some other beans that cannot be initialized until the original bean (the one with the Provider) is. There is not cyclic dependency, only over-eager initialization.

Example:

class Bean1 { @Inject Provider<X> provider;}
class Bean2 { @Inject Bean1 bean1;}

applicationContext.xml:
<bean id="bean1" class="com.rb.springissues.sample.Bean1"/>
<bean id="bean2" class="com.rb.springissues.sample.Bean2"/>
<bean id="bean2Factory" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="target" ref="bean2"/>
    <property name="proxyTargetClass" value="true"/>
</bean>

In the above example the flow is (fully managed by Spring):

Instantiate bean1. Try to initialize bean1 and discover it has a Provider<X>.

Go through all BeanDefinition in the context. For each:

if it's a "normal" bean, evaluate the class to see if it fits.

if it's a FactoryBean, try to instantiate and initialize the FactoryBean to see what "getObjectType()" would return.

In order to initialize bean2Factory, it needs to be fed with an instance of bean2. So Spring tries to instantiate and  initialize bean2.

However - bean2 cannot be initialized since it relies on bean1 - causing Spring to throw a cyclic dependency error.

If the FactoryObject was created correctly, Spring now asks for the type and cache the response ("good path").

If we got an exception (the cyclic dependency error) it's caught and ignored, but the result isn't cached - so if we get another bean it'll do the same thing again (and again and again...)

See https://github.com/bironran/spring_issues_proxy_factory for the full description and a sample.

I have observed real-world application with about 500 defined beans instantiate and attempt to initialize over 300,000 objects (the same beans again and again) due to this issue. The startup is delayed by minutes and GC spike.

Moreover, this issue has exponential growth - any new dependency that cannot be resolved can double the time the application takes to load.

Would love to hear suggestions on how to solve (see the github project).


问:
PHP Date not working and not appending to image name
```<code>$now = DateTime::createFromFormat('U.u', microtime(true));
$id = #now=> format('YmdHisu');
$upload_folder = "upload";
$path = "$upload_folder/$id.jpeg";
$image = $_POST['image'];

if(file_put_contents($path, base64_decode($image)) != false){
    echo "uploaded_success";
    exit;
}
else{
    echo "upload_failed";
    exit;
}
</code>```

答:
Your $id variable isn't terminated. You could just use $id = round(microtime(true) * 1000); as your id.

You should test to make sure that $_POST['image'] actually contains a base_64 encoded image. if(base64_decode($_POST['image'],ture) === false { //do something }

File name then could be $ide . "_upload.jpg"


问:
Cannot create instance of ISWiProject
I am using InstallShield 2016 SP1. I am trying to set some attributes for my installation project through C#. I got Installation automation code from the following link :
http://codecontext.blogspot.in/2012/04/installshield-automation-using-c.html.

I created a Sample console application and it is working fine. When I integrate the same code with my main application I am unable to create the instance of ISWiProject at BuildProject() (You can refer the above code for reference). The error which I encountered is stated as below :

Creating an instance of the COM component with CLSID {} from the IClassFactory failed due to the following error: 800a0035 Exception from HRESULT: 0x800A0035 (CTL_E_FILENOTFOUND).

I also changed the platform target to x86, still not luck.

Thanks in advance

答: This COM server can only be called from a 32 bit process.</p>

Title: Cannot create instance of ISWiProject


问:
where is the location of client side git hooks in server
I want to deploy my own version of git client side hooks. for this, i need to know whether the client side hooks are generated from the clients system or are also cloned from the server.
If it is cloned from the server, what is the location where the client side hooks are located?</p>

答:
The client side hooks are not stored in server. Server has nothing to do with client side hooks in git. i.e. client side hooks and server side hooks are not inter-related. However, they are generated inside your local repository by your own local system.

In short, client side git hooks are not related to server and aren't stored there.


问:
How should one make a class with dependencies unit testable without bloat?
So I have a class (part of a library) that facilitates two-way TCP communication. Part of that is accepting incoming connections.

My implementation consists of using a TCPListener object and a multithreaded method to accept connections. To make it testable, I decided to instead create an "INetworkListener" interface, which contains only a single event, "OnClientAccepted". This way, I can use dependency injection to mock a fake version of TCPListener and avoid multithreaded unit tests.

The problem is that I need a way to test the class using a fake INetworkListener, but I want my users to not have the option to use other implementations of this interface.

Here is some stripped down sample code:

```<code>class TcpMessenger
{
    // Various properties

    private INetworkListener _tcpListener;

    public TcpMessenger(int port, string friendlyName) // This is the ONLY constructor I want available to users
    {
        ServerPort = port;
        FriendlyName = friendlyName;
        _isRunning = false;
        _tcpListener = new ConcreteExample(port); // This prevents unit testing because it opens threads and such
    }

    public TcpMessenger(int port, string friendlyName, INetworkListener listener) // I need this to test
    {
        ServerPort = port;
        FriendlyName = friendlyName;
        _isRunning = false;
        _tcpListener = listener; // No dependency here :)
    }
}
</code>```

Why can't I just leave both constructors?

My library acts as sort of a facade. It makes TCP communication easier, but doesn't add much functionality. Therefore, my target audience would never need to inject that dependency. And if I don't want them to do it, then proper design tells me to enforce it.

Why not just test it as a public-facing API? Integration Testing!

I actually did this with a previous version of my library, which was extremely coupled. The results were terrible. I had a dozen tests that involved multiple threads, and worse, actual sockets. Unit tests shouldn't be dependent on outside factors like that.

Do you really need to test this?

Yes. This library has high-level functionality, such as exception handling, error reporting, failsafes for connection issues, and algorithms to maintain two-way connections (meaning each node is a client and server). This functionality can be tested without opening actual sockets, so I definitely want that.

I also want the unit tests to be public. Meaning anyone can grab the source, run them, and see all the green check marks.

Concluding Question:

How do I test two classes independently, while simultaneously forcing dependencies in real-world scenarios?

答:
You can make your constructor internal and expose your internals to your tests using InternalsVisibleTo:

```<code>[assembly: InternalsVisibleTo("YourNamespace.YourTests")]
</code>```

See: https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx

Body:
So I have a class (part of a library) that facilitates two-way TCP communication. Part of that is accepting incoming connections.

My implementation consists of using a TCPListener object and a multithreaded method to accept connections. To make it testable, I decided to instead create an "INetworkListener" interface, which contains only a single event, "OnClientAccepted". This way, I can use dependency injection to mock a fake version of TCPListener and avoid multithreaded unit tests.

The problem is that I need a way to test the class using a fake INetworkListener, but I want my users to not have the option to use other implementations of this interface.

Here is some stripped down sample code:

class TcpMessenger
{
    // Various properties

    private INetworkListener _tcpListener;

    public TcpMessenger(int port, string friendlyName) // This is the ONLY constructor I want available to users
    {
        ServerPort = port;
        FriendlyName = friendlyName;
        _isRunning = false;
        _tcpListener = new ConcreteExample(port); // This prevents unit testing because it opens threads and such
    }

    public TcpMessenger(int port, string friendlyName, INetworkListener listener) // I need this to test
    {
        ServerPort = port;
        FriendlyName = friendlyName;
        _isRunning = false;
        _tcpListener = listener; // No dependency here :)
    }
}

Why can't I just leave both constructors?

My library acts as sort of a facade. It makes TCP communication easier, but doesn't add much functionality. Therefore, my target audience would never need to inject that dependency. And if I don't want them to do it, then proper design tells me to enforce it.

Why not just test it as a public-facing API? Integration Testing!

I actually did this with a previous version of my library, which was extremely coupled. The results were terrible. I had a dozen tests that involved multiple threads, and worse, actual sockets. Unit tests shouldn't be dependent on outside factors like that.

Do you really need to test this?

Yes. This library has high-level functionality, such as exception handling, error reporting, failsafes for connection issues, and algorithms to maintain two-way connections (meaning each node is a client and server). This functionality can be tested without opening actual sockets, so I definitely want that.

I also want the unit tests to be public. Meaning anyone can grab the source, run them, and see all the green check marks.

Concluding Question:

How do I test two classes independently, while simultaneously forcing dependencies in real-world scenarios?

Body:
You can make your constructor internal and expose your internals to your tests using InternalsVisibleTo:

[assembly: InternalsVisibleTo("YourNamespace.YourTests")]

See: https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx


问:
Access containing function
So, I'm working on a library that generates functions using a function constructor.

Each generated function is to have a property attached to the function known as default for store default values for an options parameter.

like so:

```<code>var generated_function = function( arg1, arg2, options_arg ){ ... }
generated_function.default = {}
</code>```

The reason for attaching the default as a property of the function instead of storing it inside the function like this:

```<code>var generated_function = function( arg1, arg2, options_arg ){
  default = {}
}
</code>```

is that I want the option to change the default settings during runtime if needed.

An example use would be say your default options is a huge object consisting of 100s or evens 1000s of properties, and your argumentative options is on average only 25% of the size that the default is.

Let's also say you are calling this function 100s or 1000s of times, and you are changing the argumentative options every call, but only changing the default options say a maximum of only 2 times.

Now I could just pass the default options along with the argumentative options in that parameter, but that would require creating and passing a lot of objects that are very large in size to the generated function. This is a memory problem.

I cannot afford memory problems with this script. Remember that the function is generated, meaning I also face the problem of passing all of data at that size and frequency to not one, but multiple functions

What I need is to be able to access that attached property, but I cannot do it like this:

```<code>var generated_function = function( arg1, arg2, options_arg ){
  ...
  generated_function.default ... //do something with it
  ...
}
generated_function.default = {}
</code>```

because the name of the function is automatically generated meaning that it will be hard to access the function by name like I did, and the function can be generated inside another generated function meaning that I have to deal with scope problems.

So, basically what I am looking for is something along the lines of:

```<code>var generated_function = function( arg1, arg2, options_arg ){
  ...
  containing_function.default ... //do something with it
  ...
}
generated_function.default = {}
</code>```

So I can use it like this in this generated scenario:

```<code>( window[ somerandomlygeneratedstring ] = function( arg1, arg2, options_arg ){
  ...
  containing_function.default ... //do something with it
  ...
  ( someobjectthatcannotbetracked[ somerandomlygeneratedstring ] = function( arg1, arg2, options_arg ){
    ...
    containing_function.default ...
    ...
  } ).default = { ... }

} ).default = { ... }
</code>```

答:
You can access the current function using arguments.callee. Here

```<code>var generated_function = function( arg1, arg2, options_arg ){
  ...
  arguments.callee.default ... //do something with it
  ...
}
generated_function.default = {}
</code>```

Title: Access containing function

Body:
So, I'm working on a library that generates functions using a function constructor.

Each generated function is to have a property attached to the function known as default for store default values for an options parameter.

like so:

var generated_function = function( arg1, arg2, options_arg ){ ... }
generated_function.default = {}

The reason for attaching the default as a property of the function instead of storing it inside the function like this:

var generated_function = function( arg1, arg2, options_arg ){
  default = {}
}

is that I want the option to change the default settings during runtime if needed.

An example use would be say your default options is a huge object consisting of 100s or evens 1000s of properties, and your argumentative options is on average only 25% of the size that the default is.

Let's also say you are calling this function 100s or 1000s of times, and you are changing the argumentative options every call, but only changing the default options say a maximum of only 2 times.

Now I could just pass the default options along with the argumentative options in that parameter, but that would require creating and passing a lot of objects that are very large in size to the generated function. This is a memory problem.

I cannot afford memory problems with this script. Remember that the function is generated, meaning I also face the problem of passing all of data at that size and frequency to not one, but multiple functions

What I need is to be able to access that attached property, but I cannot do it like this:

var generated_function = function( arg1, arg2, options_arg ){
  ...
  generated_function.default ... //do something with it
  ...
}
generated_function.default = {}

because the name of the function is automatically generated meaning that it will be hard to access the function by name like I did, and the function can be generated inside another generated function meaning that I have to deal with scope problems.

So, basically what I am looking for is something along the lines of:

var generated_function = function( arg1, arg2, options_arg ){
  ...
  containing_function.default ... //do something with it
  ...
}
generated_function.default = {}

So I can use it like this in this generated scenario:

( window[ somerandomlygeneratedstring ] = function( arg1, arg2, options_arg ){
  ...
  containing_function.default ... //do something with it
  ...
  ( someobjectthatcannotbetracked[ somerandomlygeneratedstring ] = function( arg1, arg2, options_arg ){
    ...
    containing_function.default ...
    ...
  } ).default = { ... }

} ).default = { ... }

Body:
You can access the current function using arguments.callee. Here

var generated_function = function( arg1, arg2, options_arg ){
  ...
  arguments.callee.default ... //do something with it
  ...
}
generated_function.default = {}


问:
No requests module error
I'm trying to write a web parser script using requests module. Here is my current code:

```<code>import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"],
  stdout=subprocess.PIPE).communicate()[0]
  return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
  global numberOfSockets
  global numberOfViewers
  while True:
    if numberOfSockets < numberOfViewers:
      numberOfSockets += 1
      print ("Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers))
      urls.append(getURL())

def view(): # Opens connections to send views
  global numberOfSockets
  while True:
    url=q.get()
    requests.head(url)
    if (url in urlsUsed):
      urls.remove(url)
      urlsUsed.remove(url)
      numberOfSockets -= 1
    else:
      urlsUsed.append(url)
      q.task_done()

      if __name__ == '__main__':
        for i in range(0, builderThreads):
          threading.Thread(target = build).start()

          while True:
            while (numberOfViewers != numberOfSockets): # Wait until sockets are built
              time.sleep(1)

              q=Queue(concurrent*2)
              for i in range(concurrent):
                try:
                  t=threading.Thread(target=view)
                  t.daemon=True
                  t.start()
                except:
                  print ('thread error')
                  try:
                    for url in urls:
                      print (url)
                      q.put(url.strip())
                      q.join()
                  except KeyboardInterrupt:
                    sys.exit(1)
</code>```

But when I run the code, it says:

```<code>Traceback (most recent call last):
  File "C:\Users\flamelier\Desktop\Twitch.py", line 1, in <module>
    import requests
ImportError: No module named 'requests'
</code>```

Why am I getting this error? How do I install this module?
Will this error keep repeating for all the scripts henceforth?
How can I prevent such similar errors in the future?

答: You have to run pip3 install requests as requests doesn't come with Python by default, as it is a third party library.

Title: No requests module error

Body:
I'm trying to write a web parser script using requests module. Here is my current code:

import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"],
  stdout=subprocess.PIPE).communicate()[0]
  return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
  global numberOfSockets
  global numberOfViewers
  while True:
    if numberOfSockets < numberOfViewers:
      numberOfSockets += 1
      print ("Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers))
      urls.append(getURL())

def view(): # Opens connections to send views
  global numberOfSockets
  while True:
    url=q.get()
    requests.head(url)
    if (url in urlsUsed):
      urls.remove(url)
      urlsUsed.remove(url)
      numberOfSockets -= 1
    else:
      urlsUsed.append(url)
      q.task_done()

      if __name__ == '__main__':
        for i in range(0, builderThreads):
          threading.Thread(target = build).start()

          while True:
            while (numberOfViewers != numberOfSockets): # Wait until sockets are built
              time.sleep(1)

              q=Queue(concurrent*2)
              for i in range(concurrent):
                try:
                  t=threading.Thread(target=view)
                  t.daemon=True
                  t.start()
                except:
                  print ('thread error')
                  try:
                    for url in urls:
                      print (url)
                      q.put(url.strip())
                      q.join()
                  except KeyboardInterrupt:
                    sys.exit(1)

But when I run the code, it says:

Traceback (most recent call last):
  File "C:\Users\flamelier\Desktop\Twitch.py", line 1, in <module>
    import requests
ImportError: No module named 'requests'

Why am I getting this error? How do I install this module?
Will this error keep repeating for all the scripts henceforth?
How can I prevent such similar errors in the future?


问:
Random numbers come up in my calculator-like program
As you can see in the photo in the link, the answer comes up correctly, but the equation is wrong. please keep in mind that i am new to coding, and it might be a simple mistake

https://pastebin.com/tVuuiNic  ( LINK TO THE CODE)

```<code>if ((operation_type == 'A') || (operation_type == 'a'))
 {
        printf("\n\nType the numbers you wish to have added.\n\n");
        scanf("%d %d",&add_a, &add_b  );

        printf("\n\n%d + %d = %d", &add_a, &add_b, func_add(add_a,add_b) );
 }
</code>```

答:
You are printing the address of add_a and add_b (by using the &) just do this:

```<code>printf("\n\n%d + %d = %d", add_a, add_b, func_add(add_a,add_b) );
</code>```

Body:
As you can see in the photo in the link, the answer comes up correctly, but the equation is wrong. please keep in mind that i am new to coding, and it might be a simple mistake

https://pastebin.com/tVuuiNic  ( LINK TO THE CODE)

if ((operation_type == 'A') || (operation_type == 'a'))
 {
        printf("\n\nType the numbers you wish to have added.\n\n");
        scanf("%d %d",&add_a, &add_b  );

        printf("\n\n%d + %d = %d", &add_a, &add_b, func_add(add_a,add_b) );
 }

Body:
You are printing the address of add_a and add_b (by using the &) just do this:

printf("\n\n%d + %d = %d", add_a, add_b, func_add(add_a,add_b) );


问:
Java, sum range of numbers in a for loop
Sorry I have been trying to figure this out and it's driving me crazy.

I need to write a java program that sums a range of numbers entered by the user and by the count of numbers entered by a user.  So if a user enters 5, 25 with count of 5.  It should sum 5+10+15+20+25=75  I have gotten it to work with a while loop, but not a for loop.  Sorry if I am asking for help for something that should be simple.  I left school almost 15 years ago involuntarily and struggling to get back into in.

Do I need to nest the loop?

```<code>import java.util.Scanner;
public class example1

{
  public static void main(String[] args) {
    int s, e, c = 0, sum = 0;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a starting number:  ");
    s = sc.nextInt();
    System.out.print("Enter an end number:  ");
    e = sc.nextInt();
    System.out.print("Enter a count by number:  ");
    c = sc.nextInt();

    {

      for (; s <= e; s++)
        sum += c;
      System.out.println("Sum of your numbers  " + sum);
    }

  }
}
</code>```

答:
im not sure what you are asking. but follows show the method with for loop and while loop

```<code> int i=2;
   while(i<c){
         System.out.println("Enter "+i+ " number :" );
         sum += sc.nextInt();
         i++;
    }
</code>```

for loop =>

```<code>for(int i=2; i< c ; i++){
       System.out.println("Enter "+i+ " number :" );
        sum += sc.nextInt();

   }

   System.out.println("Count : "+ (sum+s+e));
</code>```

Body:
Sorry I have been trying to figure this out and it's driving me crazy.

I need to write a java program that sums a range of numbers entered by the user and by the count of numbers entered by a user.  So if a user enters 5, 25 with count of 5.  It should sum 5+10+15+20+25=75  I have gotten it to work with a while loop, but not a for loop.  Sorry if I am asking for help for something that should be simple.  I left school almost 15 years ago involuntarily and struggling to get back into in.

Do I need to nest the loop?

import java.util.Scanner;
public class example1

{
  public static void main(String[] args) {
    int s, e, c = 0, sum = 0;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a starting number:  ");
    s = sc.nextInt();
    System.out.print("Enter an end number:  ");
    e = sc.nextInt();
    System.out.print("Enter a count by number:  ");
    c = sc.nextInt();

    {

      for (; s <= e; s++)
        sum += c;
      System.out.println("Sum of your numbers  " + sum);
    }

  }
}

Body:
im not sure what you are asking. but follows show the method with for loop and while loop

 int i=2;
   while(i<c){
         System.out.println("Enter "+i+ " number :" );
         sum += sc.nextInt();
         i++;
    }

for loop =>

for(int i=2; i< c ; i++){
       System.out.println("Enter "+i+ " number :" );
        sum += sc.nextInt();

   }

   System.out.println("Count : "+ (sum+s+e));


问:
pairwise operation on columns in R dataframe
I have a dataframe like this

```<code>sample <- data.frame(x1=c(1,2),y1=c(2,1), x2=c(2,4),y2=c(3,4),x3=c(5,2),y3=c(1,6))
</code>```

How can I operate pairwise (sum up x1&y1, x2&y2, x3&y3, 2 columns at a time) to create 3 new columns sum1, sum2, sum3? Thanks

答:
Method 1

Since it is pairwise, you can do it with mapply.

Create two vectors referring to the pairs

```<code>p1 <- seq(1, 6, by = 2)
p2 <- seq(2, 6, by = 2)
</code>```

Then use mapply to apply pairwise summation for the columns desired:

```<code>mapply(x = p1, y = p2, function(x, y) sample[[x]] + sample[[y]])
</code>```

Result:

```<code>   [,1] [,2] [,3]
[1,]    3    5    6
[2,]    3    8    8`
</code>```

Method 2

I also like to use the packages dplyr and wrapr in conjunction if you need to output the pairwise operation in the sample table.

```<code>require(dplyr)
require(wrapr)

newcols <- paste0(names(sample)[seq(1, 6, by = 2)], names(sample)[seq(2, 6, by = 2)])

for (i in c(1:3)) {
  wrapr::let(list(RES = newcols[i],
                  COL1 = names(sample)[i],
                  COL2 = names(sample)[i + 1]),
             sample <- dplyr::mutate(sample, RES = COL1 + COL2))}

sample

  x1 y1 x2 y2 x3 y3 x1y1 x2y2 x3y3
1  1  2  2  3  5  1    3    4    5
2  2  1  4  4  2  6    3    5    8
</code>```

I liek to use those packages because I find it easier to understand. But if you can't download those packages for any reason. You can do it with base R:

```<code>newcols <- paste0(names(sample)[seq(1, 6, by = 2)], names(sample)[seq(2, 6, by = 2)])

for (i in c(1:3)) {
             sample[newcols[i]] <- sample[, names(sample)[i]] + sample[, names(sample)[i + 1]]
}
</code>```

Body:
I have a dataframe like this

sample <- data.frame(x1=c(1,2),y1=c(2,1), x2=c(2,4),y2=c(3,4),x3=c(5,2),y3=c(1,6))

How can I operate pairwise (sum up x1&y1, x2&y2, x3&y3, 2 columns at a time) to create 3 new columns sum1, sum2, sum3? Thanks

Body:
Method 1

Since it is pairwise, you can do it with mapply.

Create two vectors referring to the pairs

p1 <- seq(1, 6, by = 2)
p2 <- seq(2, 6, by = 2)

Then use mapply to apply pairwise summation for the columns desired:

mapply(x = p1, y = p2, function(x, y) sample[[x]] + sample[[y]])

Result:

   [,1] [,2] [,3]
[1,]    3    5    6
[2,]    3    8    8`

Method 2

I also like to use the packages dplyr and wrapr in conjunction if you need to output the pairwise operation in the sample table.

require(dplyr)
require(wrapr)

newcols <- paste0(names(sample)[seq(1, 6, by = 2)], names(sample)[seq(2, 6, by = 2)])

for (i in c(1:3)) {
  wrapr::let(list(RES = newcols[i],
                  COL1 = names(sample)[i],
                  COL2 = names(sample)[i + 1]),
             sample <- dplyr::mutate(sample, RES = COL1 + COL2))}

sample

  x1 y1 x2 y2 x3 y3 x1y1 x2y2 x3y3
1  1  2  2  3  5  1    3    4    5
2  2  1  4  4  2  6    3    5    8

I liek to use those packages because I find it easier to understand. But if you can't download those packages for any reason. You can do it with base R:

newcols <- paste0(names(sample)[seq(1, 6, by = 2)], names(sample)[seq(2, 6, by = 2)])

for (i in c(1:3)) {
             sample[newcols[i]] <- sample[, names(sample)[i]] + sample[, names(sample)[i + 1]]
}


问:
How do I use map in React Native to create separate buttons?
I'm trying to make a simple quiz app in React Native:

App.js

```<code>export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.quizData = [
      {
        question: 'Who wrote A Game Of Thrones?',
        correctAnswer: 'George RR Martin',
        possibleAnswers: ['JK Rowling', 'Phillip Pulman', 'George RR Martin' ]
      },
    ];
  }

  render() {
    return (
      <View style={styles.container}>
        <MultiChoice answers={this.quizData[0].possibleAnswers}/>
      </View>
    );
  }
}
</code>```

And my MultiChoice component:

```<code>import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';

class MultiChoice extends Component {
  render() {
    return(
      <View>
          <Text style={styles.button}>{ this.props.answers.map(answer => answer) }</Text>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  button: {
    backgroundColor: 'blue',
    width: 200,
    height: 40,
  }
})

export default MultiChoice;
</code>```

I don't get any errors and all the elements of the array are displayed in the same button, but I would like to have three separate buttons. I wrote the same code in React and it worked, but in React Native it is not working.

答:
Currently, your map just returns each element, unmodified -- it does nothing. It will then create one single <Text> component with all the text. Just have the map operation return a separate <Text> component for every element to achieve separate buttons:

```<code>{ this.props.answers.map(answer => <Text style={styles.button}>{answer}</Text>) }
</code>```

And this will create separate <Text> components with the strings.

Body:
I'm trying to make a simple quiz app in React Native:

App.js

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.quizData = [
      {
        question: 'Who wrote A Game Of Thrones?',
        correctAnswer: 'George RR Martin',
        possibleAnswers: ['JK Rowling', 'Phillip Pulman', 'George RR Martin' ]
      },
    ];
  }

  render() {
    return (
      <View style={styles.container}>
        <MultiChoice answers={this.quizData[0].possibleAnswers}/>
      </View>
    );
  }
}

And my MultiChoice component:

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';

class MultiChoice extends Component {
  render() {
    return(
      <View>
          <Text style={styles.button}>{ this.props.answers.map(answer => answer) }</Text>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  button: {
    backgroundColor: 'blue',
    width: 200,
    height: 40,
  }
})

export default MultiChoice;

I don't get any errors and all the elements of the array are displayed in the same button, but I would like to have three separate buttons. I wrote the same code in React and it worked, but in React Native it is not working.

Body:
Currently, your map just returns each element, unmodified -- it does nothing. It will then create one single <Text> component with all the text. Just have the map operation return a separate <Text> component for every element to achieve separate buttons:

{ this.props.answers.map(answer => <Text style={styles.button}>{answer}</Text>) }

And this will create separate <Text> components with the strings.


问:
LibreOffice Command Line Convert CSV to DBF
I am working on a workflow where I need to be able to batch convert CSV files into DBF files. The data in the CSV files can all be output as TEXT fields and then saved as a DBF. I have tried to get any output possible using the command line in both Mac OS and Windows 7. While I was a little more successful in Windows, I was not able to get any conversion.

```<code>   "C:\Program Files (x86)\LibreOffice 5\program\scalc.exe" --convert-to dbf --

infilter="csv:44,34,76,1,1/2/2/2/3/2/4/2/5/2/6/2/7/2/8/2/9/2/10/2/11/2/12/2/13/2/14/2/15/2/16/2/17/2/18/2/19/2/20/2/21/2/22/2/23/2/24/2/25/2/26/2/27/2/28/2/29/2/30/2/31/2/32/2

/33/2/34/2/35/2/36/2/37/2/38/2/39/2/40/2/41/2/42/2/43/2/44/2/45/2/46/2/47/2/48/2/49/2/50/2/51/2/52/2/53/2/54/2/55/2/56/2/57/2/58/2/59/2/60/2/61/2/62/2/63/2/64/2/65/2/66/2/67/2

/68/2/69/2/70/2/71/2,0,false,false" C:\Users\jdavidson\Desktop\DBFCONVERT\*.csv --outdir C:\Users\jdavidson\desktop\complete
</code>```

So, I needed to have an --infilter on the command line to be able to do the conversion, but now it will only process 1 file and not batch file when using *.csv So, my next hurdle is to get over that.

The below helps to explain --infilters in more detail:

https://wiki.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Filter_Options#Filter_Options_for_Lotus.2C_dBase_and_DIF_Filters

Any easier way to find the filter sequence you need is by following the below listed steps:

Open the CSV Manually using LibreOffice and Specify Every Detail in the import Wizard

Run the below macro and it will show you the filter options in an input box, so you can copy the string in to your own code

Sub showFilterOptions
Dim args(),i%
   args() = thisComponent.getArgs
   for i = 0 to uBound(Args())
      if args(i).Name = "FilterOptions" then inputbox "","",args(i).value
   next
End Sub

Credit to code: https://forum.openoffice.org/en/forum/viewtopic.php?f=44&t=14018

Body:
I am working on a workflow where I need to be able to batch convert CSV files into DBF files. The data in the CSV files can all be output as TEXT fields and then saved as a DBF. I have tried to get any output possible using the command line in both Mac OS and Windows 7. While I was a little more successful in Windows, I was not able to get any conversion.

   "C:\Program Files (x86)\LibreOffice 5\program\scalc.exe" --convert-to dbf --

infilter="csv:44,34,76,1,1/2/2/2/3/2/4/2/5/2/6/2/7/2/8/2/9/2/10/2/11/2/12/2/13/2/14/2/15/2/16/2/17/2/18/2/19/2/20/2/21/2/22/2/23/2/24/2/25/2/26/2/27/2/28/2/29/2/30/2/31/2/32/2

/33/2/34/2/35/2/36/2/37/2/38/2/39/2/40/2/41/2/42/2/43/2/44/2/45/2/46/2/47/2/48/2/49/2/50/2/51/2/52/2/53/2/54/2/55/2/56/2/57/2/58/2/59/2/60/2/61/2/62/2/63/2/64/2/65/2/66/2/67/2

/68/2/69/2/70/2/71/2,0,false,false" C:\Users\jdavidson\Desktop\DBFCONVERT\*.csv --outdir C:\Users\jdavidson\desktop\complete

So, I needed to have an --infilter on the command line to be able to do the conversion, but now it will only process 1 file and not batch file when using *.csv So, my next hurdle is to get over that.

The below helps to explain --infilters in more detail:

https://wiki.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Filter_Options#Filter_Options_for_Lotus.2C_dBase_and_DIF_Filters

Any easier way to find the filter sequence you need is by following the below listed steps:

Open the CSV Manually using LibreOffice and Specify Every Detail in the import Wizard

Run the below macro and it will show you the filter options in an input box, so you can copy the string in to your own code

Sub showFilterOptions
Dim args(),i%
   args() = thisComponent.getArgs
   for i = 0 to uBound(Args())
      if args(i).Name = "FilterOptions" then inputbox "","",args(i).value
   next
End Sub

Credit to code: https://forum.openoffice.org/en/forum/viewtopic.php?f=44&t=14018

Body:
I was able to get this to work using the below code:

"C:\Program Files (x86)\LibreOffice 5\program\scalc.exe" --convert-to DBF --infilter="csv:44,34,76,1,1/2/2/2/3/2/4/2/5/2/6/2/7/2/8/2/9/2/10/2/11/2/12/2/13/2/14/2/15/2/16/2/17/2/18/2/19/2/20/2/21/2/22/2/23/2/24/2/25/2/26/2/27/2/28/2/29/2/30/2/31/2/32/2/33/2/34/2/35/2/36/2/37/2/38/2/39/2/40/2/41/2/42/2/43/2/44/2/45/2/46/2/47/2/48/2/49/2/50/2/51/2/52/2/53/2/54/2/55/2/56/2/57/2/58/2/59/2/60/2/61/2/62/2/63/2/64/2/65/2/66/2/67/2/68/2/69/2/70/2/71/2/72/2/73/2/74/2/75/2/76/2/77/2/78/2/79/2/80/2/81/2/82/2/83/2/84/2/85/2/86/2/87/2/88/2/89/2/90/2/91/2/92/2/93/2/94/2/95/2/96/2/97/2/98/2/99/2/100/2/101/2/102/2/103/2/104/2/105/2/106/2/107/2/108/2/109/2/110/2/111/2/112/2/113/2/114/2/115/2/116/2/117/2/118/2/119/2/120/2/121/2/122/2/123/2/124/2/125/2/126/2/127/2/128/2/129/2/130/2/131/2/132/2/133/2/134/2/135/2/136/2,0,false,false" C:\Users\jdavidson\Desktop\DBFCONVERT\57826001_JQSAMPLE.csv --outdir C:\Users\jdavidson\desktop\complete

Please note, that I needed to use DBF and include an --infilter parameter field

There are two websites in my original posting that shows helpful scripts and infilter information to help other users


问:
How do I create a nested dictionary under a key that is yet to exist?
I have an empty array.

I want to assign a value like this: array[key][subkey] = 'value'

This produces a KeyError as array[key] does not exist yet.

What do I do? I tried the following...

```<code>array['key'] = None
array['key']['subkey'] = 'value'
</code>```

TypeError: 'NoneType' object does not support item assignment

I tried:

```<code>array['key'] = []
array['key']['subkey'] = 'value'
</code>```

TypeError: list indices must be integers, not str

I tried:

```<code>array['key'] = ['subkey']
array['key']['subkey'] = 'value'
</code>```

TypeError: list indices must be integers, not str

So what do I do?

答:
You are using a [] list literal not a {} dict literal:

```<code>array['key'] = {}
array['key']['subkey'] = 'value'
</code>```

But this isn't very useful in a loop.

In a loop you could test if 'key' is not in array - which is a cheap operation (O(1) lookup):

```<code>if 'key' not in array:
    array['key'] = {}
array['key']['subkey'] = 'value'
</code>```

But you can use setdefault() to do the same thing and give key a default value if it doesn't already have a value, e.g.:

```<code>array.setdefault('key', {})['subkey'] = 'value'
</code>```

And if this looks ugly, then you can always use collection.defaultdict.

Body:
I have an empty array.

I want to assign a value like this: array[key][subkey] = 'value'

This produces a KeyError as array[key] does not exist yet.

What do I do? I tried the following...

array['key'] = None
array['key']['subkey'] = 'value'

TypeError: 'NoneType' object does not support item assignment

I tried:

array['key'] = []
array['key']['subkey'] = 'value'

TypeError: list indices must be integers, not str

I tried:

array['key'] = ['subkey']
array['key']['subkey'] = 'value'

TypeError: list indices must be integers, not str

So what do I do?

Body:
You are using a [] list literal not a {} dict literal:

array['key'] = {}
array['key']['subkey'] = 'value'

But this isn't very useful in a loop.

In a loop you could test if 'key' is not in array - which is a cheap operation (O(1) lookup):

if 'key' not in array:
    array['key'] = {}
array['key']['subkey'] = 'value'

But you can use setdefault() to do the same thing and give key a default value if it doesn't already have a value, e.g.:

array.setdefault('key', {})['subkey'] = 'value'

And if this looks ugly, then you can always use collection.defaultdict.

ContentLicense: CC BY-SA 4.0


问:
Ensure first and last characters of text box are numbers c#
Im currently creating a windows form that must only allow a password through when it matches certain criteria. Im close to finishing however im a bit stuck with one element. "the first and last characters of the password HAVE to be numbers".

looking at my current code how would i go about this because i have ZERO idea. so baby steps and patience would be appreciated.

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace password_test
{
    public partial class Form1 : Form
    {

        bool Finished = false;

        private bool TestPassword(string passwordText, int minimumLength =     5, int maximumLength = 12, int minimumNumbers = 1, int minimumLetters = 1)
    {

        int letters = 0;
        int digits = 0;
        int minLetters = 0;

        if (passwordText.Length < minimumLength)
        {
            MessageBox.Show("You must have at least " + minimumLength + " characters in your password.");
            return false;
        }

        if (passwordText.Length > maximumLength)
        {
            MessageBox.Show("You must have no more than " + maximumLength + " characters in your password.");
            return false;
        }

        foreach (var ch in passwordText)
        {
            if (char.IsLetter(ch)) letters++;
            if (char.IsDigit(ch)) digits++;

            if (ch > 96 && ch < 123)
            {
                minLetters++;
            }
        }

        if (digits < minimumNumbers)
        {
            MessageBox.Show("You must have at least " + minimumNumbers + " numbers in your password.");
            return false;
        }

        if (minLetters < minimumLetters)
        {
            MessageBox.Show("You must have at least " + minimumLetters + " letter in your password");
            return false;
        }
        Finished = true;
        return true;

    }

    public Form1()
    {
        InitializeComponent();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void butConfirm_Click(object sender, EventArgs e)
    {

        if (txtPassword.Text == txtRetypePassword.Text)
        {
                bool temp = TestPassword(txtPassword.Text, 10, 100, 1, 1);

            if (Finished == true)
            {
                MessageBox.Show("Password Accepted");
                Application.Exit();
                //this.Hide();
                //Form2 f2 = new Form2();
                //f2.ShowDialog();

            }
        }

        else
        {
            MessageBox.Show("Please ensure the passwords you have typed match");
            return;
        }

    }

    private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsLetterOrDigit(e.KeyChar))
        {
            e.Handled = true;
        }
        else
        {
            return;
        }
    }

    private void txtRetypePassword_TextChanged(object sender, EventArgs e)
    {

    }

}
}
</code>```

答:
Before Finished = true; you can simply do your check:

```<code>if (!char.IsDigit(passwordText[0]) || !char.IsDigit(passwordText[passwordText.Length - 1]))
{
    MessageBox.Show("The first and last characters of the password  have to be numbers");
    return false;
}
Finished = true;
</code>```

You should also enforce a minimum length in your method.

Body:
Im currently creating a windows form that must only allow a password through when it matches certain criteria. Im close to finishing however im a bit stuck with one element. "the first and last characters of the password HAVE to be numbers".

looking at my current code how would i go about this because i have ZERO idea. so baby steps and patience would be appreciated.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace password_test
{
    public partial class Form1 : Form
    {

        bool Finished = false;

        private bool TestPassword(string passwordText, int minimumLength =     5, int maximumLength = 12, int minimumNumbers = 1, int minimumLetters = 1)
    {

        int letters = 0;
        int digits = 0;
        int minLetters = 0;

        if (passwordText.Length < minimumLength)
        {
            MessageBox.Show("You must have at least " + minimumLength + " characters in your password.");
            return false;
        }

        if (passwordText.Length > maximumLength)
        {
            MessageBox.Show("You must have no more than " + maximumLength + " characters in your password.");
            return false;
        }

        foreach (var ch in passwordText)
        {
            if (char.IsLetter(ch)) letters++;
            if (char.IsDigit(ch)) digits++;

            if (ch > 96 && ch < 123)
            {
                minLetters++;
            }
        }

        if (digits < minimumNumbers)
        {
            MessageBox.Show("You must have at least " + minimumNumbers + " numbers in your password.");
            return false;
        }

        if (minLetters < minimumLetters)
        {
            MessageBox.Show("You must have at least " + minimumLetters + " letter in your password");
            return false;
        }
        Finished = true;
        return true;

    }

    public Form1()
    {
        InitializeComponent();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void butConfirm_Click(object sender, EventArgs e)
    {

        if (txtPassword.Text == txtRetypePassword.Text)
        {
                bool temp = TestPassword(txtPassword.Text, 10, 100, 1, 1);

            if (Finished == true)
            {
                MessageBox.Show("Password Accepted");
                Application.Exit();
                //this.Hide();
                //Form2 f2 = new Form2();
                //f2.ShowDialog();

            }
        }

        else
        {
            MessageBox.Show("Please ensure the passwords you have typed match");
            return;
        }

    }

    private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsLetterOrDigit(e.KeyChar))
        {
            e.Handled = true;
        }
        else
        {
            return;
        }
    }

    private void txtRetypePassword_TextChanged(object sender, EventArgs e)
    {

    }

}
}

Body:
Before Finished = true; you can simply do your check:

if (!char.IsDigit(passwordText[0]) || !char.IsDigit(passwordText[passwordText.Length - 1]))
{
    MessageBox.Show("The first and last characters of the password  have to be numbers");
    return false;
}
Finished = true;

You should also enforce a minimum length in your method.


问:
angular2 toggle icon on ngFor
My angular2 problem is that the icon is not visible when i arrive to the page but only after click. my array is "keys"</p>

```<code><ion-grid class="dueD-line" *ngFor="let line of keys; let i=index">
<div style="margin-bottom: 6%;" (click)="toggleDetails(line)">
<ion-col class="first-title-row first-title-row-size" text-left align-items: left col-9>Line {{i+1}}</ion-col>
<ion-col class="first-title-row first-title-row-size" text-right align-items: right col-3><ion-icon class="arrow-right"  item-right name="ios-arrow-down-outline"></ion-icon><ion-icon class="arrow-right"  item-right name={{line.icon}}></ion-icon></ion-col>
</div>
<div *ngIf="line.showDetails">
{{line.text}}
</ion-grid>

export class ReviewCartPage implements OnInit {

  keys: any;
  icon: string;

constructor(){
this.icon = 'ios-arrow-down-outline';
}

toggleDetails(line) {
    if (line.showDetails) {
      line.showDetails = false;
      line.icon = 'ios-arrow-down-outline';
    } else {
      line.showDetails = true;
      line.icon = 'ios-arrow-up-outline';
    }
  }
</code>```

答:
In your component class:

```<code>showDetails = 1;
keys = [{ id: 1, icon: 'ios-arrow-down-outline', text: "Your text for icon1" }, { id: 2, icon: 'ios-arrow-up-outline', text: "Your text for icon2" }]

toggleDetails(id) {
    this.showDetails = id;
}
</code>```

and HTML:

```<code><div style="color:red; display:flex;" *ngFor="let line of keys">
    <span *ngIf="showDetails==line.id">{{line.icon}}</span>
    <span *ngIf="showDetails==line.id">{{line.text}}</span>
    <button (click)="toggleDetails(line.id)">click</button>
</div>
</code>```

This way your "lines" will show only if the button is clicked. The first one would be by default. You have to populate the 'keys' array first.
The error you were commiting was this.icon = 'ios-arrow-down-outline';

Title: angular2 toggle icon on ngFor

Body:
My angular2 problem is that the icon is not visible when i arrive to the page but only after click. my array is "keys"

<ion-grid class="dueD-line" *ngFor="let line of keys; let i=index">

<ion-col class="first-title-row first-title-row-size" text-left align-items: left col-9>Line {{i+1}}</ion-col>
<ion-col class="first-title-row first-title-row-size" text-right align-items: right col-3><ion-icon class="arrow-right"  item-right name="ios-arrow-down-outline"></ion-icon><ion-icon class="arrow-right"  item-right name={{line.icon}}></ion-icon></ion-col>

{{line.text}}
</ion-grid>

export class ReviewCartPage implements OnInit {

  keys: any;
  icon: string;

constructor(){
this.icon = 'ios-arrow-down-outline';
}

toggleDetails(line) {
    if (line.showDetails) {
      line.showDetails = false;
      line.icon = 'ios-arrow-down-outline';
    } else {
      line.showDetails = true;
      line.icon = 'ios-arrow-up-outline';
    }
  }

Body:
In your component class:

showDetails = 1;
keys = [{ id: 1, icon: 'ios-arrow-down-outline', text: "Your text for icon1" }, { id: 2, icon: 'ios-arrow-up-outline', text: "Your text for icon2" }]

toggleDetails(id) {
    this.showDetails = id;
}

and HTML:

<div style="color:red; display:flex;" *ngFor="let line of keys">
    <span *ngIf="showDetails==line.id">{{line.icon}}</span>
    <span *ngIf="showDetails==line.id">{{line.text}}</span>
    <button (click)="toggleDetails(line.id)">click</button>
</div>

This way your "lines" will show only if the button is clicked. The first one would be by default. You have to populate the 'keys' array first.
The error you were commiting was this.icon = 'ios-arrow-down-outline';


问:
Make Info window Marker Google Maps Always Appear Swift
i have info window that shows after tapped, but how to make it always appear? Without user tap on the marker. I'm using Google Maps.

here's my code :

```<code>    mapView.delegate = self
    let camera = GMSCameraPosition.camera(withLatitude: coordinate.lat, longitude: coordinate.long, zoom: 20)
    mapView.animate(to: camera)

    for state in states {
        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2DMake(state.lat, state.long)
        print(marker.position)
        marker.title = "Country"
        marker.snippet = "Places"
        marker.map = mapView
        mapView.selectedMarker = marker
        marker.map = mapView

    }
</code>```

thanks before

答: try to move mapView.selectedMarker = marker to delegate function mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool function

Body:
i have info window that shows after tapped, but how to make it always appear? Without user tap on the marker. I'm using Google Maps.

here's my code :

    mapView.delegate = self
    let camera = GMSCameraPosition.camera(withLatitude: coordinate.lat, longitude: coordinate.long, zoom: 20)
    mapView.animate(to: camera)

    for state in states {
        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2DMake(state.lat, state.long)
        print(marker.position)
        marker.title = "Country"
        marker.snippet = "Places"
        marker.map = mapView
        mapView.selectedMarker = marker
        marker.map = mapView

    }

thanks before


问:
C# - Handling Fault Exceptions in event-based WCF proxy
I am consuming a WCF service using an event-based proxy generated by Visual Studio. I have run into an issue, where my application will hang if the call to the service times out. The call to the service is as follows:

```<code>ServiceClient client = new ServiceClient(binding, endpointAddress);
client.AuthenticateCompleted += (sender, e) =>
{
    if (e.Error != null)
        throw e.Error;
};
client.AuthenticateAsync(username, password);
</code>```

Browsing through countless other questions, the general consensus is that any exceptions should be caught by WCF and found in e.Error above. However, when my service times out, this is not the case, the error is either null, or in some other tests I've run, the app has crashed before reaching this point in the code. Another user suggested wrapping the above code in a try/catch block, however, doing this also fails to catch the exception.

I have also tried placing try/catch blocks inside the completion handler, as well as numerous other more complicated methods which are beyond the scope of the question, as I really just need this working in its simplest form to continue.

It may also be worth mentioning that while many of these failures occurred on the live service with a open, close, send, and receive timeout of 30 seconds each, I have also been attempting to test fixes to the issue by bringing the timeout down to <1 second. I presume this would still be generating Timeout Exceptions and not causing any other issues, but I'm not 100% sure.

I also did not create the WCF service, so if something specific needs to be done on the server side to throw exceptions back to the client, it is possible this element is missing. If this is the case, is there any way around this?

答:
It turns out the error is thrown by the IService.EndMethodName method which is not accessible through the class that is generated by Visual Studio.

Instead I decided to access the channel directly so I have more control over things. The final implementation looks like the following (IService being the interface generated by Visual Studio):

```<code>ChannelFactory<IService> factory = new ChannelFactory<IService>(binding, endpointAddress);

// CreateChannel may not require any parameters outside of Mono
IService channel = factory.CreateChannel(endpointAddress);

channel.BeginAuthenticate(new AuthenticateRequest(arg0, arg1), result =>
{
    try
    {
        channel.EndAuthenticate(result);
    }
    catch(Exception ex)
    {
        throw;
    }
}, channel);
</code>```

This is in its simplest form, but the general idea is that the call is ended in the AsyncCallback within a try/catch block to do any exception handling there.

Body:
I am consuming a WCF service using an event-based proxy generated by Visual Studio. I have run into an issue, where my application will hang if the call to the service times out. The call to the service is as follows:

ServiceClient client = new ServiceClient(binding, endpointAddress);
client.AuthenticateCompleted += (sender, e) =>
{
    if (e.Error != null)
        throw e.Error;
};
client.AuthenticateAsync(username, password);

Browsing through countless other questions, the general consensus is that any exceptions should be caught by WCF and found in e.Error above. However, when my service times out, this is not the case, the error is either null, or in some other tests I've run, the app has crashed before reaching this point in the code. Another user suggested wrapping the above code in a try/catch block, however, doing this also fails to catch the exception.

I have also tried placing try/catch blocks inside the completion handler, as well as numerous other more complicated methods which are beyond the scope of the question, as I really just need this working in its simplest form to continue.

It may also be worth mentioning that while many of these failures occurred on the live service with a open, close, send, and receive timeout of 30 seconds each, I have also been attempting to test fixes to the issue by bringing the timeout down to <1 second. I presume this would still be generating Timeout Exceptions and not causing any other issues, but I'm not 100% sure.

I also did not create the WCF service, so if something specific needs to be done on the server side to throw exceptions back to the client, it is possible this element is missing. If this is the case, is there any way around this?

Body:
It turns out the error is thrown by the IService.EndMethodName method which is not accessible through the class that is generated by Visual Studio.

Instead I decided to access the channel directly so I have more control over things. The final implementation looks like the following (IService being the interface generated by Visual Studio):

ChannelFactory<IService> factory = new ChannelFactory<IService>(binding, endpointAddress);

// CreateChannel may not require any parameters outside of Mono
IService channel = factory.CreateChannel(endpointAddress);

channel.BeginAuthenticate(new AuthenticateRequest(arg0, arg1), result =>
{
    try
    {
        channel.EndAuthenticate(result);
    }
    catch(Exception ex)
    {
        throw;
    }
}, channel);

This is in its simplest form, but the general idea is that the call is ended in the AsyncCallback within a try/catch block to do any exception handling there.


问:
mysql connection not working on JSP deployment using tomcat
I developed my enterprise application using Java EE. This uses JDBC for mysql connection. The project works fine when its run from the intellij idea IDE. But after i deployed it with the same version of tomcat, JDBC connector and all the other libraries as used during development.
The login page is browsed but as soon i login after providing all the credentials, it throws out an error in form of exception along with 500 error which i believe is due to connection failure to mysql.
The error message is:

```<code>java.lang.NullPointerException
    utils.DatabaseConnection.getPreparedStatement(DatabaseConnection.java:34)
    services.UserService.getUser(UserService.java:31)
    controller.SessionServlet.doPost(SessionServlet.java:30)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
</code>```

snapshot of error after login page

答: This was because Java could not communicate with mysql. This led null pointer for a variable related to username and password. It was due to misconfiguration for database connection. I entered wrong informations. </p>

Body:
I developed my enterprise application using Java EE. This uses JDBC for mysql connection. The project works fine when its run from the intellij idea IDE. But after i deployed it with the same version of tomcat, JDBC connector and all the other libraries as used during development.
The login page is browsed but as soon i login after providing all the credentials, it throws out an error in form of exception along with 500 error which i believe is due to connection failure to mysql.
The error message is:

java.lang.NullPointerException
    utils.DatabaseConnection.getPreparedStatement(DatabaseConnection.java:34)
    services.UserService.getUser(UserService.java:31)
    controller.SessionServlet.doPost(SessionServlet.java:30)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)

snapshot of error after login page


问:
count the number of zero group bits in a number
How do you count the number of zero group bits in a number? group bits
is any consecutive zero or one bits, for example, 2 is represented
as ....0000000000000000010 has two zero bits groups the least
significant bit and the group starts after one.
Also, I am in a bad need for algorithms on bits manipulation if any
one has a reference, please share</p>

答:
You can repeatedly use integer division and the modulo operator to extract the bits, and keep track of the groups within your loop. It sounds like a homework question, so I'm not sure how much of a service it does you to give you a full solution? Consider that you can use this algorithm to get the base-2 representation of a positive integer (in fact it works with any base >= 2):

```<code>int example = 40;
while (example > 0) {
    printf("%d\n", example % 2);
    example /= 2;
}
</code>```

This will print out the bits in reverse order (that is, starting from the least significant). From here there's not much work to be done to count the groups you want to count. Should I go further or can you take it from here?

ContentLicense: CC BY-SA 2.5

Body:
You can repeatedly use integer division and the modulo operator to extract the bits, and keep track of the groups within your loop. It sounds like a homework question, so I'm not sure how much of a service it does you to give you a full solution? Consider that you can use this algorithm to get the base-2 representation of a positive integer (in fact it works with any base >= 2):

int example = 40;
while (example > 0) {
    printf("%d\n", example % 2);
    example /= 2;
}

This will print out the bits in reverse order (that is, starting from the least significant). From here there's not much work to be done to count the groups you want to count. Should I go further or can you take it from here?


问:
Is it possible to anchor an element to a centered element?
Is it possible to anchor a textarea to an image that is centered in the middle of the page, so that it doesn't move out of the image when the screen size changes?

Example on jsfiddle: https://jsfiddle.net/rxg7t2ca/1/

.container {
  width: 60%;
  margin: 0 auto;
  /* border: 2px solid blue; */
}

#cat {
  display: block;
  margin: 0 auto;
}

.box1 {
  position: relative;
  top: -250px;
  left: 30px;
  width: 100px;
  height: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <img src="http://i.imgur.com/a2Wd9D2.jpg" height=300px id="cat" />
  <textarea class="box1"> This is a text box </textarea>

</div></code>```

答:
In the container use 'position:relative', and in the textarea and in the image use 'position: absolute'.

CSS absolute property: The element is positioned relative to its first positioned (not static) ancestor element.

```<code>.container{
  width: 60%;
  margin: 0 auto;
  position:relative;
  /* border: 2px solid blue; */
}

#cat{
  position: absolute;
  top: 0px;
  left: 0px;
  display: block;
  margin: 0 auto;
}

.box1{
  position: absolute;
  top: 25px;
  left: 30px;
  width: 100px;
  height: 100px;
}
</code>```

Body:
Is it possible to anchor a textarea to an image that is centered in the middle of the page, so that it doesn't move out of the image when the screen size changes?

Example on jsfiddle: https://jsfiddle.net/rxg7t2ca/1/

.container {
  width: 60%;
  margin: 0 auto;
  /* border: 2px solid blue; */
}

#cat {
  display: block;
  margin: 0 auto;
}

.box1 {
  position: relative;
  top: -250px;
  left: 30px;
  width: 100px;
  height: 100px;
}

  <textarea class="box1"> This is a text box </textarea>

Body:
In the container use 'position:relative', and in the textarea and in the image use 'position: absolute'.

CSS absolute property: The element is positioned relative to its first positioned (not static) ancestor element.

.container{
  width: 60%;
  margin: 0 auto;
  position:relative;
  /* border: 2px solid blue; */
}

#cat{
  position: absolute;
  top: 0px;
  left: 0px;
  display: block;
  margin: 0 auto;
}

.box1{
  position: absolute;
  top: 25px;
  left: 30px;
  width: 100px;
  height: 100px;
}


问:
How can I install lxml dependencies on Amazon EC2 linux?
I tried:

```<code>sudo yum install libxml2-dev libxslt-dev python-dev
</code>```

and I got:

```<code>Loaded plugins: priorities, update-motd, upgrade-helper
amzn-main/latest                                         | 2.1 kB     00:00
amzn-updates/latest                                      | 2.3 kB     00:00
No package libxml2-dev available.
No package libxslt-dev available.
No package python-dev available.
</code>```

pip did not work either.

I got the package like this:

```<code>git clone --branch lxml-3.2.4 https://github.com/lxml/lxml
</code>```

Then I tried without cython because sudo python setup.py install gave me RuntimeError: ERROR: Trying to build without Cython, but pre-generated 'src/lxml/lxml.etree.c' is not available

```<code>sudo python setup.py install --without-cython
</code>```

Then I got:

```<code>sudo python setup.py install --without-cython
Building lxml version 3.2.4.
WARNING: Trying to build without Cython, but pre-generated 'src/lxml/lxml.etree.c' is not available.
WARNING: Trying to build without Cython, but pre-generated 'src/lxml/lxml.objectify.c' is not available.
Building without Cython.
ERROR: /bin/sh: xslt-config: command not found

** make sure the development packages of libxml2 and libxslt are installed **

Using build configuration of libxslt
/usr/lib64/python2.6/distutils/dist.py:266: UserWarning: Unknown distribution option: 'bugtrack_url'
  warnings.warn(msg)
running install
running bdist_egg
running egg_info
writing src/lxml.egg-info/PKG-INFO
writing top-level names to src/lxml.egg-info/top_level.txt
writing dependency_links to src/lxml.egg-info/dependency_links.txt
reading manifest file 'src/lxml.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching 'lxml.etree.c' under directory 'src/lxml'
warning: no files found matching 'lxml.objectify.c' under directory 'src/lxml'
warning: no files found matching 'lxml.etree.h' under directory 'src/lxml'
warning: no files found matching 'lxml.etree_api.h' under directory 'src/lxml'
warning: no files found matching '*.txt' under directory 'src/lxml/tests'
warning: no files found matching '*.html' under directory 'doc'
writing manifest file 'src/lxml.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_py
copying src/lxml/includes/lxml-version.h -> build/lib.linux-x86_64-2.6/lxml/includes
running build_ext
building 'lxml.etree' extension
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/home/ec2-user/lxml/src/lxml/includes -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-x86_64-2.6/src/lxml/lxml.etree.o
gcc: error: src/lxml/lxml.etree.c: No such file or directory
gcc: fatal error: no input files
compilation terminated.
error: command 'gcc' failed with exit status 4
[ec2-user@ip-172-31-14-83 lxml]$
</code>```

It really wants me to make sure the development packages of libxml2 and libxslt are installed.

If I can do that I hope it will work.  Any ideas?  Thanks!  It seems people have related issues to this, but most are on other systems.

UPDATE:
Based on Vor's suggestion I used the -devel extension and that worked to install the dependencies.

```<code>sudo yum install libxml2-devel libxslt-devel python-devel
</code>```

Unfortunately I get this:

```<code>$sudo python setup.py install --without-cython

Building lxml version 3.4.0.
WARNING: Trying to build without Cython, but pre-generated 'src/lxml/lxml.etree.c' is not available.
WARNING: Trying to build without Cython, but pre-generated 'src/lxml/lxml.objectify.c' is not available.
Building without Cython.
Using build configuration of libxslt 1.1.28
Building against libxml2/libxslt in the following directory: /usr/lib64
/usr/lib64/python2.6/distutils/dist.py:266: UserWarning: Unknown distribution option: 'bugtrack_url'
  warnings.warn(msg)
running install
running bdist_egg
running egg_info
writing requirements to src/lxml.egg-info/requires.txt
writing src/lxml.egg-info/PKG-INFO
writing top-level names to src/lxml.egg-info/top_level.txt
writing dependency_links to src/lxml.egg-info/dependency_links.txt
reading manifest file 'src/lxml.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching 'lxml.etree.c' under directory 'src/lxml'
warning: no files found matching 'lxml.objectify.c' under directory 'src/lxml'
warning: no files found matching 'lxml.etree.h' under directory 'src/lxml'
warning: no files found matching 'lxml.etree_api.h' under directory 'src/lxml'
warning: no files found matching '*.html' under directory 'doc'
writing manifest file 'src/lxml.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_py
copying src/lxml/includes/lxml-version.h -> build/lib.linux-x86_64-2.6/lxml/includes
running build_ext
building 'lxml.etree' extension
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/include/libxml2 -I/home/ec2-user/lxml/src/lxml/includes -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-x86_64-2.6/src/lxml/lxml.etree.o -w
gcc: error: src/lxml/lxml.etree.c: No such file or directory
gcc: fatal error: no input files
compilation terminated.
error: command 'gcc' failed with exit status 4
</code>```

答:
Add on to huapito's answer. Following code work for me.

sudo yum install gcc libxml2-devel libxslt-devel python-devel
sudo pip install lxml

Body:
I tried:

sudo yum install libxml2-dev libxslt-dev python-dev

and I got:

Loaded plugins: priorities, update-motd, upgrade-helper
amzn-main/latest                                         | 2.1 kB     00:00
amzn-updates/latest                                      | 2.3 kB     00:00
No package libxml2-dev available.
No package libxslt-dev available.
No package python-dev available.

pip did not work either.

I got the package like this:

git clone --branch lxml-3.2.4 https://github.com/lxml/lxml

Then I tried without cython because sudo python setup.py install gave me RuntimeError: ERROR: Trying to build without Cython, but pre-generated 'src/lxml/lxml.etree.c' is not available

sudo python setup.py install --without-cython

Then I got:

sudo python setup.py install --without-cython
Building lxml version 3.2.4.
WARNING: Trying to build without Cython, but pre-generated 'src/lxml/lxml.etree.c' is not available.
WARNING: Trying to build without Cython, but pre-generated 'src/lxml/lxml.objectify.c' is not available.
Building without Cython.
ERROR: /bin/sh: xslt-config: command not found

** make sure the development packages of libxml2 and libxslt are installed **

Using build configuration of libxslt
/usr/lib64/python2.6/distutils/dist.py:266: UserWarning: Unknown distribution option: 'bugtrack_url'
  warnings.warn(msg)
running install
running bdist_egg
running egg_info
writing src/lxml.egg-info/PKG-INFO
writing top-level names to src/lxml.egg-info/top_level.txt
writing dependency_links to src/lxml.egg-info/dependency_links.txt
reading manifest file 'src/lxml.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching 'lxml.etree.c' under directory 'src/lxml'
warning: no files found matching 'lxml.objectify.c' under directory 'src/lxml'
warning: no files found matching 'lxml.etree.h' under directory 'src/lxml'
warning: no files found matching 'lxml.etree_api.h' under directory 'src/lxml'
warning: no files found matching '*.txt' under directory 'src/lxml/tests'
warning: no files found matching '*.html' under directory 'doc'
writing manifest file 'src/lxml.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_py
copying src/lxml/includes/lxml-version.h -> build/lib.linux-x86_64-2.6/lxml/includes
running build_ext
building 'lxml.etree' extension
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/home/ec2-user/lxml/src/lxml/includes -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-x86_64-2.6/src/lxml/lxml.etree.o
gcc: error: src/lxml/lxml.etree.c: No such file or directory
gcc: fatal error: no input files
compilation terminated.
error: command 'gcc' failed with exit status 4
[ec2-user@ip-172-31-14-83 lxml]$

It really wants me to make sure the development packages of libxml2 and libxslt are installed.

If I can do that I hope it will work.  Any ideas?  Thanks!  It seems people have related issues to this, but most are on other systems.

UPDATE:
Based on Vor's suggestion I used the -devel extension and that worked to install the dependencies.

sudo yum install libxml2-devel libxslt-devel python-devel

Unfortunately I get this:

$sudo python setup.py install --without-cython

Building lxml version 3.4.0.
WARNING: Trying to build without Cython, but pre-generated 'src/lxml/lxml.etree.c' is not available.
WARNING: Trying to build without Cython, but pre-generated 'src/lxml/lxml.objectify.c' is not available.
Building without Cython.
Using build configuration of libxslt 1.1.28
Building against libxml2/libxslt in the following directory: /usr/lib64
/usr/lib64/python2.6/distutils/dist.py:266: UserWarning: Unknown distribution option: 'bugtrack_url'
  warnings.warn(msg)
running install
running bdist_egg
running egg_info
writing requirements to src/lxml.egg-info/requires.txt
writing src/lxml.egg-info/PKG-INFO
writing top-level names to src/lxml.egg-info/top_level.txt
writing dependency_links to src/lxml.egg-info/dependency_links.txt
reading manifest file 'src/lxml.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching 'lxml.etree.c' under directory 'src/lxml'
warning: no files found matching 'lxml.objectify.c' under directory 'src/lxml'
warning: no files found matching 'lxml.etree.h' under directory 'src/lxml'
warning: no files found matching 'lxml.etree_api.h' under directory 'src/lxml'
warning: no files found matching '*.html' under directory 'doc'
writing manifest file 'src/lxml.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_py
copying src/lxml/includes/lxml-version.h -> build/lib.linux-x86_64-2.6/lxml/includes
running build_ext
building 'lxml.etree' extension
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/include/libxml2 -I/home/ec2-user/lxml/src/lxml/includes -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-x86_64-2.6/src/lxml/lxml.etree.o -w
gcc: error: src/lxml/lxml.etree.c: No such file or directory
gcc: fatal error: no input files
compilation terminated.
error: command 'gcc' failed with exit status 4


问:
Passing two php variables to another page from a link
Ok so I'm building a simple question/answer site and this is a loop that outputs all the questions asked previously in link form.  I'm trying to concat two variables to the next page url so I can get them and work with them there but it will only allow one?  I've tried everything but not working?  See the only comment section of my code for the crux of the issue.  Thank you.</p>

```<code><?php
$servername = "127.0.0.1";
$username = "dylan326";
$password = "";
$dbname = "questions87";
$port = 3306;

$conn = mysqli_connect($servername, $username, $password, $dbname,
$port);

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<a href='index.html'> Log out </a><br>
<a href='ask.php'> Ask a question</a><br>
<br />
<br />";

echo "Answer another users question: <br><br />";

$sql = "SELECT q_id,question, username FROM questions";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {

while($row = mysqli_fetch_array($result))
{

$q_id = $row['q_id'];
$question = $row['question'];
$username = $row['username'];

//right here I need to add(concat) the second variable $username
//I need to get both on the next page url but not allowing me to

echo ('<a href="totalqs.php?q_id=' . $q_id .'   " >' . $question .
'</a>'  . '<br>');
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>
</code>```

答:
Try this (assuming that $username has a value):

```<code>echo ('<a href="totalqs.php?q_id=' . $q_id .'   " >' . $question . " Username:" . $username . '</a>'  . '<br>');
</code>```

Body:
Ok so I'm building a simple question/answer site and this is a loop that outputs all the questions asked previously in link form.  I'm trying to concat two variables to the next page url so I can get them and work with them there but it will only allow one?  I've tried everything but not working?  See the only comment section of my code for the crux of the issue.  Thank you.

<?php
$servername = "127.0.0.1";
$username = "dylan326";
$password = "";
$dbname = "questions87";
$port = 3306;

$conn = mysqli_connect($servername, $username, $password, $dbname,
$port);

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo " Log out

 Ask a question

";

echo "Answer another users question:

";

$sql = "SELECT q_id,question, username FROM questions";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {

while($row = mysqli_fetch_array($result))
{

$q_id = $row['q_id'];
$question = $row['question'];
$username = $row['username'];

//right here I need to add(concat) the second variable $username
//I need to get both on the next page url but not allowing me to

echo ('' . $question .
''  . '
');
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>

Body:
Try this (assuming that $username has a value):

echo ('<a href="totalqs.php?q_id=' . $q_id .'   " >' . $question . " Username:" . $username . '</a>'  . '<br>');


问:
Python- checking for letters, numbers, and underscore character.
I have to write a program that checks if a user's variable name is valid. These are the rules I am checking for: Only letters, numbers, and the underscore character are allowed. The first character cannot be a number.

I am not sure what I am doing wrong. Every time I run the program, it tells me that it's a valid variable, even for invalid inputs.

Here is my program:

```<code>import string

def valid(name):
    for character in (name):
        if name[0].isdigit():
            name==False
            break
        else:
            if character.isalnum() and character is ('_'):
                name==True
            else:
                name==False
    return

def main():
    name=input("Enter your Python variable name: ")

    while name != "done":
        valid(name)

        if True:
            print("This is a valid variable name.")

        else:
            print("This is not a valid variable name.")

        name=input("Enter your Python variable name or 'done': ")

main()
</code>```

Here is a sample output (if done right):

```<code>Enter your Python variable name: high_temp
This is a valid variable name.

Enter your Python variable name or "done": highTemp2
This is a valid variable name.

Enter your Python variable name or "done": 2_high_temp
This is not a valid variable name.

Enter your Python variable name or "done": done
</code>```

Thank you in advance!

答:
Looks like you can get away with isidentifier method

```<code>return name.isidentifier()
</code>```

Body:
I have to write a program that checks if a user's variable name is valid. These are the rules I am checking for: Only letters, numbers, and the underscore character are allowed. The first character cannot be a number.

I am not sure what I am doing wrong. Every time I run the program, it tells me that it's a valid variable, even for invalid inputs.

Here is my program:

import string

def valid(name):
    for character in (name):
        if name[0].isdigit():
            name==False
            break
        else:
            if character.isalnum() and character is ('_'):
                name==True
            else:
                name==False
    return

def main():
    name=input("Enter your Python variable name: ")

    while name != "done":
        valid(name)

        if True:
            print("This is a valid variable name.")

        else:
            print("This is not a valid variable name.")

        name=input("Enter your Python variable name or 'done': ")

main()

Here is a sample output (if done right):

Enter your Python variable name: high_temp
This is a valid variable name.

Enter your Python variable name or "done": highTemp2
This is a valid variable name.

Enter your Python variable name or "done": 2_high_temp
This is not a valid variable name.

Enter your Python variable name or "done": done

Thank you in advance!

Body:
Looks like you can get away with isidentifier method

return name.isidentifier()


问:
Equivalence of static methods in Go
Let's say in Java, I have class CryptoFormat, which has a static method named getLegacyFormat(). When I want to use the method, I just need to call CryptoFormat.getLegacyFormat(). This is clear because I know where the method comes from.

In Go, there is no static method. I don't really want to just make a file called crypto_format.go and define the method there. The reason is that whenever I need the method, I just call GetLegacyFormat(), which doesn't contain the context where the method comes from.

I could think of two ways to solve the problem:

Make a separate package named cryptoformat, and define the method as a global function in the package. This way, I need to make a new package for just few methods. Also, whenever I need static methods like this, I have to define new packages.

Define a struct named cryptoFormat containing method GetLegacyFormat(). Also, define a <s>global</s> public variable named CryptoFormat, which points to an instance of struct cryptoFormat. This way, I can call CryptoFormat.GetLegacyFormat() when I need the method.

I am not sure which one is better, or whether there is better way.

答:
whenever I need the method, I just call GetLegacyFormat(), which doesn't contain the context where the method comes from.

So add context to the function name.

```<code>GetLegacyCryptoFormat()
</code>```

Title: Equivalence of static methods in Go

Body:
whenever I need the method, I just call GetLegacyFormat(), which doesn't contain the context where the method comes from.

So add context to the function name.

GetLegacyCryptoFormat()