问:
Start listening again with Socket after a disconnect
I'm writing a small C# Sockets application. Actually I have two, a server and a client.

The user runs the client, enters the IP and port for the server, presses 'connect', and then once connected they can enter text into a textbox and send it to the server.

The server simply displays either "No connection" or "Connection from [ip]:[port]", and the most recent received message underneath.

The server successfully receives messages, and even handles the client disconnect fine.
Now I'm trying to make it listen again after the client has disconnected but for some reason nothing I try will allow it to start listening again.

Here is part of my code:

```<code>    Socket socket;
    private void listen()
    {
        socket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);
        socket.Bind(new IPEndPoint(IPAddress.Any, 12345));
        socket.Listen(10);
        socket.BeginAccept(new AsyncCallback(acceptAsync), socket);
    }
</code>```

and

```<code>    private void receiveAsync(IAsyncResult res)
    {
        Socket socket = (Socket)res.AsyncState;

        try
        {
            int nBytes = socket.EndReceive(res);
            if (nBytes > 0)
            {
                Invoke(new MethodInvoker(delegate()
                {
                    lMessage.Text = encoder.GetString(buffer);
                }));
                setupReceiveAsync(socket);
            }
            else
            {
                Invoke(new MethodInvoker(delegate()
                {
                    lConnections.Text = "No Connections.";
                    lMessage.Text = "No Messages.";
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                    listen();
                }));
            }
        }
        catch { }
    }
</code>```

The last line: listen(); is what throws the error.
I have tried simply calling socket.BeginAccept() again, but that also throws an exception.

The message I'm getting is:

Only one usage of each socket address (protocol/network address/port) is normally permitted

If I don't call my listen() function and instead just call socket.BeginAccept(), then I get "You must first call socket.listen()"

If I call the socket.listen() function, then it tells me it's already connected and cart start listening.

Once I have made an asynchronous connection, and received several asynchronous messages, how then do I begin receiving again?

答: Your socket variable already has an listening socket assigned to it the second time you call listen(), which is why it tells you only one usage is permitted. All you need to repeat is the socket.BeginAccept(new AsyncCallback(acceptAsync), socket) call. So try replacing the call to listen() inside your receiveAsync(...) method with socket.BeginAccept(new AsyncCallback(acceptAsync), socket).

Body:
I'm writing a small C# Sockets application. Actually I have two, a server and a client.

The user runs the client, enters the IP and port for the server, presses 'connect', and then once connected they can enter text into a textbox and send it to the server.

The server simply displays either "No connection" or "Connection from [ip]:[port]", and the most recent received message underneath.

The server successfully receives messages, and even handles the client disconnect fine.
Now I'm trying to make it listen again after the client has disconnected but for some reason nothing I try will allow it to start listening again.

Here is part of my code:

    Socket socket;
    private void listen()
    {
        socket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);
        socket.Bind(new IPEndPoint(IPAddress.Any, 12345));
        socket.Listen(10);
        socket.BeginAccept(new AsyncCallback(acceptAsync), socket);
    }

and

    private void receiveAsync(IAsyncResult res)
    {
        Socket socket = (Socket)res.AsyncState;

        try
        {
            int nBytes = socket.EndReceive(res);
            if (nBytes > 0)
            {
                Invoke(new MethodInvoker(delegate()
                {
                    lMessage.Text = encoder.GetString(buffer);
                }));
                setupReceiveAsync(socket);
            }
            else
            {
                Invoke(new MethodInvoker(delegate()
                {
                    lConnections.Text = "No Connections.";
                    lMessage.Text = "No Messages.";
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                    listen();
                }));
            }
        }
        catch { }
    }

The last line: listen(); is what throws the error.
I have tried simply calling socket.BeginAccept() again, but that also throws an exception.

The message I'm getting is:

Only one usage of each socket address (protocol/network address/port) is normally permitted

If I don't call my listen() function and instead just call socket.BeginAccept(), then I get "You must first call socket.listen()"

If I call the socket.listen() function, then it tells me it's already connected and cart start listening.

Once I have made an asynchronous connection, and received several asynchronous messages, how then do I begin receiving again?


来源: stackexchange

问:
For my data, why can tree-based learning algorithms have accuracies only about 50%?
For my data, I have tried several tree-based algorithms with grid search, such as XGBoostClassifier, RandomForestClassifier, but the accuracies are only about 50%.

Then I tried SVC, the testing accuracy can up to 80% in the grid search.

Is there any method(visualization is preferred) can help us to tell the reasons behind?

答:
As a rule of thumb, SVMs are great for relatively small data sets with fewer outliers. Random forests require more data but in my experience tend to be a pretty robust model. In practice, the decision which classifier to choose really depends on your dataset and the general complexity of the problem which I'm not sure of exactly in your case.

    I should mention another potential deviation can be the parameters to tune. In a random forest tree there are limited parameters to tune (maybe except for the number of trees; typically, the more trees we have the better). Whereas for SVMs you have to choose the "right" kernel, regularization penalties, the slack variable, etc. which is another reason that usually Random Forest "out of the box" tend to perform better.

If it comes to predictive performance, there are cases where SVMs do better than random forests and vice versa. See paper below.

```<code>Caruana, Rich, and Alexandru Niculescu-Mizil. "An empirical comparison of supervised learning algorithms." Proceedings of the 23rd international conference on Machine learning. ACM, 2006.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
As a rule of thumb, SVMs are great for relatively small data sets with fewer outliers. Random forests require more data but in my experience tend to be a pretty robust model. In practice, the decision which classifier to choose really depends on your dataset and the general complexity of the problem which I'm not sure of exactly in your case.

    I should mention another potential deviation can be the parameters to tune. In a random forest tree there are limited parameters to tune (maybe except for the number of trees; typically, the more trees we have the better). Whereas for SVMs you have to choose the "right" kernel, regularization penalties, the slack variable, etc. which is another reason that usually Random Forest "out of the box" tend to perform better.

If it comes to predictive performance, there are cases where SVMs do better than random forests and vice versa. See paper below.

Caruana, Rich, and Alexandru Niculescu-Mizil. "An empirical comparison of supervised learning algorithms." Proceedings of the 23rd international conference on Machine learning. ACM, 2006.


问:
Better subsetting and counting values in a dataframe
I have a data frame with two columns and 70,000 rows.  One column serves an identifier for a household, column b in the example below.  The other column refers to the individuals in the household, numbering them from 1 to n with some error (could be 1,2,3 or 1,4,5), column a in the example below.

I'm trying to use hierarchical clustering with the number of individuals in a household as a feature.  The code I've written below counts the number of individuals in a household and puts them in the proper column and row, however takes several minutes with the actual data set I have, I assume due to its size.  Is there a better way of going about getting this information?

```<code>fake.data <- data.frame(a = c(1,1,5,6,7,1,2,3,1,2,4), b = c("a", "a", "a", "a", "a", "b", "b", "b", "c", "c", "c"))
fake.cluster <- data.frame(b = unique(fake.data$b))
fake.cluster$members <- sapply(fake.cluster$b, function(x)     length(unique(subset(fake.data, fake.data$b == x)$a)))
</code>```

答:
Don't know if this is quicker, but you could use dplyr in various ways. One approach: get the distinct rows and then count b.

```<code>library(dplyr)
fake.cluster <- fake.data %>%
  distinct() %>%
  count(b)
</code>```

Body:
I have a data frame with two columns and 70,000 rows.  One column serves an identifier for a household, column b in the example below.  The other column refers to the individuals in the household, numbering them from 1 to n with some error (could be 1,2,3 or 1,4,5), column a in the example below.

I'm trying to use hierarchical clustering with the number of individuals in a household as a feature.  The code I've written below counts the number of individuals in a household and puts them in the proper column and row, however takes several minutes with the actual data set I have, I assume due to its size.  Is there a better way of going about getting this information?

fake.data <- data.frame(a = c(1,1,5,6,7,1,2,3,1,2,4), b = c("a", "a", "a", "a", "a", "b", "b", "b", "c", "c", "c"))
fake.cluster <- data.frame(b = unique(fake.data$b))
fake.cluster$members <- sapply(fake.cluster$b, function(x)     length(unique(subset(fake.data, fake.data$b == x)$a)))

Body:
Don't know if this is quicker, but you could use dplyr in various ways. One approach: get the distinct rows and then count b.

library(dplyr)
fake.cluster <- fake.data %>%
  distinct() %>%
  count(b)


问:
CsvReader Next function
i am given a csv file but i want to skip the first row of data and move on to the next. Here is my code:

```<code>def read_csv(inputfile):
    return list(csv.reader(inputfile)) #<-----

def generate_xml(reader,outfile):
    root = Element('Solution')
    root.set('version','1.0')
    tree = ElementTree(root)
    head = SubElement(root, 'DrillHoles')
    description = SubElement(head,'description')
    current_group = None
    i = 1
    for row in reader.next(): #<-----
        x1,y1,z1,x2,y2,z2,cost = row
        if current_group is None or i != current_group.text:
            current_group = SubElement(description, 'hole',{'hole_id':"%s"%i})

            collar = SubElement(current_group,'collar')
            toe = SubElement(current_group,'toe')
            cost1 = SubElement(current_group,'cost')
            collar.text = ','.join((x1,y1,z1))
            toe.text = ','.join((x2,y2,z2))
            cost1.text = cost
        i+=1
    head.set('total_holes', '%s'%i)
    indent.indent(root)
    tree.write(outfile)
</code>```

As you can see, i return the csv file as a list then i pass it onto the generate_xml function. However when i run the complete program there is an

```<code>error: 'list' object has no attribute 'next'
</code>```

答:
For python 2.x, the code is:

```<code>data = []
with open('xxx.csv') as f:
    r = csv.reader(f)
    name = r.next()[1] # assume the first 2 rows are name and unit
    unit = r.next()
    for row in r:
        data.append(row)
</code>```

For python 3.x, use next(r) instead of r.next()

Title: CsvReader Next function

Body:
i am given a csv file but i want to skip the first row of data and move on to the next. Here is my code:

def read_csv(inputfile):
    return list(csv.reader(inputfile)) #<-----

def generate_xml(reader,outfile):
    root = Element('Solution')
    root.set('version','1.0')
    tree = ElementTree(root)
    head = SubElement(root, 'DrillHoles')
    description = SubElement(head,'description')
    current_group = None
    i = 1
    for row in reader.next(): #<-----
        x1,y1,z1,x2,y2,z2,cost = row
        if current_group is None or i != current_group.text:
            current_group = SubElement(description, 'hole',{'hole_id':"%s"%i})

            collar = SubElement(current_group,'collar')
            toe = SubElement(current_group,'toe')
            cost1 = SubElement(current_group,'cost')
            collar.text = ','.join((x1,y1,z1))
            toe.text = ','.join((x2,y2,z2))
            cost1.text = cost
        i+=1
    head.set('total_holes', '%s'%i)
    indent.indent(root)
    tree.write(outfile)

As you can see, i return the csv file as a list then i pass it onto the generate_xml function. However when i run the complete program there is an

error: 'list' object has no attribute 'next'

Body:
For python 2.x, the code is:

data = []
with open('xxx.csv') as f:
    r = csv.reader(f)
    name = r.next()[1] # assume the first 2 rows are name and unit
    unit = r.next()
    for row in r:
        data.append(row)

For python 3.x, use next(r) instead of r.next()


问:
JavaScript / Socket.io web application not executing any JS commands
I am trying to create a simple live LAN messaging web application.  I am using HTML, CSS, Javascript, Socket.io, and JQuery to do this.  I have built a similar application to this before, so I have some experience with these types of projects.  I have no idea why, but every time I try to execute any javascript command, it doesn't work.  I have a button trying to start a function called joingame().  It says that the function is undefined.  I also tried to define a variable as "test value", and it keeps coming up as ''.  If anybody could help me out, it would be great!  It's probably something really basic, but I can't figure it out.  Thank you!</p>

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

<head>
<style>
#start {
width: 400px;
height: 120px;
border: 1px solid black;
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translateY(-50%) translateX(-50%);
}

#chat {
width: 80%;
height: 80%;
border: 1px solid black;
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translateY(-50%) translateX(-50%);
}
</style>
</head>

<body>
<div id="start">
<center>
<h2>Enter your username below:</h2>
<input type="text" placeholder="Username here..." id="usernameid" />
<input type="button" value="Submit" onclick="joingame()" >
</center>
</div>

<div id="chat" style="display: none;">
<center>
<div id="chatbox">
<div id="inputarea">
<textarea id="chatinp" placeholder="Enter message here..." cols='50' rows='2' />
<input type="button" value="Send" onclick="sendchat()" id="sendbut" />
</div>
</div>
</center>
</div>
<script src="socket.io.js"></script>
<script src="jquery-3.2.0.js"></script>
<script type='text/javascript'>
var socket = io();
var usernameasdf = "test value";

function joingame() {
usernameasdf = document.getElementById("usernameid").value;
socket.emit('player', usernameasdf);
document.getElementById("start").style.display = "none";
document.getElementById("chat").style.display = "inline";
}

socket.on('player', function(name) {
alert(name);
});

function sendchat() {
alert("chat sent");
}
</script>
</body>
</html>
</code>```

答:
Textare isn't self closing. Check this SO answer
When I changed closing tag, it worked for me in firefox as <textarea id="chatinp" placeholder="Enter message here..." cols='50' rows='2'></textarea>

Body:
I am trying to create a simple live LAN messaging web application.  I am using HTML, CSS, Javascript, Socket.io, and JQuery to do this.  I have built a similar application to this before, so I have some experience with these types of projects.  I have no idea why, but every time I try to execute any javascript command, it doesn't work.  I have a button trying to start a function called joingame().  It says that the function is undefined.  I also tried to define a variable as "test value", and it keeps coming up as ''.  If anybody could help me out, it would be great!  It's probably something really basic, but I can't figure it out.  Thank you!

<!DOCTYPE HTML>

Enter your username below:

<input type="text" placeholder="Username here..." id="usernameid" />
<input type="button" value="Submit" onclick="joingame()" >

<textarea id="chatinp" placeholder="Enter message here..." cols='50' rows='2' />
<input type="button" value="Send" onclick="sendchat()" id="sendbut" />


问:
WordPress Blogs Avatar Link/URL in Database?
i was looking that where the wordpress  save the URL/Link of the Avatar of the blog in the Database of wordpress anyone can help?</p>

答:
the avatar link is not saved in the database.

it is found  even Stack Overflow/Stack Exchange uses this.

ContentLicense: CC BY-SA 2.5

Body:
the avatar link is not saved in the database.

it is found <img src="http://gravatar.com/avatar/your-emailadress-hashed-by-md5"> even Stack Overflow/Stack Exchange uses this.


问:
Error message when trying to install package offline in conda
I have a laptop that can't connect to the internet that I have a working version of Anaconda 3 version 4.2 on.  I also want to install the PyVISA package.

I downloaded the tar.bz2 file and copied it to the Anaconda3/pkgs folder.  I navigate to the directory and use the command:

```<code>C:\Program Files\Anaconda3\pkgs>conda install --offline --use-local --use-index-cache pyvisa-1.8-py35_0.tar.bz2
</code>```

And the response I get is:

```<code>Extracting packages ...
An unexpected error has occurred.                                     |   0%
Please consider posting the following information to the
conda GitHub issue tracker at:

https://github.com/conda/conda/issues

Current conda install:

           platform : win-32
      conda version : 4.2.9
   conda is private : False
  conda-env version : 4.2.9
conda-build version : 2.0.2
     python version : 3.5.2.final.0
   requests version : 2.11.1
   root environment : C:\Program Files\Anaconda3  (read only)
default environment : C:\Program Files\Anaconda3
   envs directories : C:\Users\Name\.conda\envs
                      C:\Program Files\Anaconda3\envs
      package cache : C:\Users\Name\.conda\envs\.pkgs
                      C:\Program Files\Anaconda3\pkgs
       channel URLs : https://repo.continuum.io/pkgs/free/win-32/  (offline)

                      https://repo.continuum.io/pkgs/free/noarch/  (offline)

                      https://repo.continuum.io/pkgs/pro/win-32/  (offline)
                      https://repo.continuum.io/pkgs/pro/noarch/  (offline)
                      https://repo.continuum.io/pkgs/msys2/win-32/  (offline)
                      https://repo.continuum.io/pkgs/msys2/noarch/  (offline)
        config file : None
       offline mode : True

`$ C:\Program Files\Anaconda3\Scripts\conda-script.py install --offline --use-local --use-index-cache pyvisa-1.8-py35_0.tar.bz2`

Traceback (most recent call last):
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\exceptions.py", l
ine 473, in conda_exception_handler
    return_value = func(*args, **kwargs)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main.py", lin
e 144, in _main
    exit_code = args.func(args, p)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main_install.
py", line 80, in execute
    install(args, parser, 'install')
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\install.py",
line 209, in install
    explicit(args.packages, prefix, verbose=not context.quiet)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\misc.py", line 18
7, in explicit
    execute_actions(actions, index=index, verbose=verbose)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\plan.py", line 64
3, in execute_actions
    inst.execute_instructions(plan, index, verbose)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\instructions.py",
line 134, in execute_instructions
    cmd(state, arg)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\instructions.py",
line 58, in EXTRACT_CMD
    extract(arg)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\install.py", line
792, in extract
    url = rec['urls'][0]
IndexError: list index out of range
</code>```

From "list index out of range" I figured that it might not be finding the file, so I used the full path for it:

```<code>C:\Program Files\Anaconda3\pkgs>conda install --offline --use-local --use-index-cache C:\Program%20Files\Anaconda3\pkgs\pyvisa-1.8-py35_0.tar.bz2
</code>```

The response I get is:

```<code>Traceback (most recent call last):
File "C:\Program Files\Anaconda3\lib\site-packages\conda\exceptions.py", line
473, in conda_exception_handler
return_value = func(*args, **kwargs)
File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main.py", line 14
4, in _main
exit_code = args.func(args, p)
File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main_install.py",
line 80, in execute
install(args, parser, 'install')
File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\install.py", line
209, in install
explicit(args.packages, prefix, verbose=not context.quiet)
File "C:\Program Files\Anaconda3\lib\site-packages\conda\misc.py", line 70, in
explicit
raise CondaFileNotFoundError(join(url_p, fn))
conda.exceptions.CondaFileNotFoundError: <exception str() failed>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Program Files\Anaconda3\Scripts\conda-script.py", line 5, in <module>

sys.exit(conda.cli.main())
File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main.py", line 15
0, in main
return conda_exception_handler(_main)
File "C:\Program Files\Anaconda3\lib\site-packages\conda\exceptions.py", line
487, in conda_exception_handler
print_conda_exception(e)
File "C:\Program Files\Anaconda3\lib\site-packages\conda\exceptions.py", line
393, in print_conda_exception
stderrlogger.info(repr(exception))
File "C:\Program Files\Anaconda3\lib\site-packages\conda\__init__.py", line 42
, in __repr__
return '%s: %s\n' % (self.__class__.__name__, text_type(self))
File "C:\Program Files\Anaconda3\lib\site-packages\conda\__init__.py", line 45
, in __str__
return text_type(self.message % self._kwargs)
TypeError: a float is required
</code>```

What's going on here?  Is there a way to install this package offline?

UPDATE 1:

Following the advice below I tried

```<code>C:\Program Files\Anaconda3\pkgs>conda install --offline --use-local --use-index-cache --debug "C:\Program Files\Anaconda3\pkgs\pyvisa-1.8-py35_0.tar.bz2"
</code>```

And now I'm getting:

```<code>CondaValueError: Value error: invalid package specification
</code>```

as a default error message, and if I use debug, it's the following:

```<code>DEBUG conda.models.channel:__init__(140): making channel object for url:https://repo.continuum.io/pkgs/free/win-32/alabaster-0.7.9-py35_0.tar.bz2
DEBUG conda.common.url:path_to_url(26): C:\Users\Name\conda-bld converted to file:///C:/Users/Name/conda-bld
DEBUG conda.models.channel:__init__(140): making channel object for url:file:///C:/Users/Name/conda-bld
DEBUG conda.models.channel:__init__(140): making channel object for url:https://repo.continuum.io/pkgs/free
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/pro
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/msys2
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/free/win-32/anaconda-4.2.0-np111py35_0.tar.bz2
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/free/win-32/anaconda-clean-1.0.0-py35_0.tar.bz2
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/free/win-32/anaconda-client-1.5.1-py35_0.tar.bz2
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/free/win-32/anaconda-navigator-1.3.1-py35_0.tar.bz2
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/free/win-32/argcomplete-1.0.0-py35_1.tar.bz2
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/free/win-32/astroid-1.4.7-py35_0.tar.bz2
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/free/win-32/astropy-1.2.1-np111py35_0.tar.bz2
</code>```

And so on for what looks like all my packages, followed by

```<code>An unexpected error has occurred.
Please consider posting the following information to the
conda GitHub issue tracker at:

https://github.com/conda/conda/issues

INFO conda.common.io:captured(27): overtaking stderr and stdout
DEBUG conda.models.channel:__init__(161): making channel object for named channel: defaults
INFO conda.common.io:captured(33): stderr and stdout yielded back
Current conda install:

           platform : win-32
      conda version : 4.2.9
   conda is private : False
  conda-env version : 4.2.9
conda-build version : 2.0.2
     python version : 3.5.2.final.0
   requests version : 2.11.1
   root environment : C:\Program Files\Anaconda3  (read only)
default environment : C:\Program Files\Anaconda3
   envs directories : C:\Users\Name\.conda\envs
                      C:\Program Files\Anaconda3\envs
      package cache : C:\Users\Name\.conda\envs\.pkgs
                      C:\Program Files\Anaconda3\pkgs
       channel URLs : https://repo.continuum.io/pkgs/free/win-32/  (offline)

                      https://repo.continuum.io/pkgs/free/noarch/  (offline)

                      https://repo.continuum.io/pkgs/pro/win-32/  (offline)
                      https://repo.continuum.io/pkgs/pro/noarch/  (offline)
                      https://repo.continuum.io/pkgs/msys2/win-32/  (offline)
                      https://repo.continuum.io/pkgs/msys2/noarch/  (offline)
        config file : None
       offline mode : True

`$ C:\Program Files\Anaconda3\Scripts\conda-script.py install --offline --use-local --use-index-cache --debug C:\Program Files\Anaconda3\pkgs\pyvisa-1.8-py35_0.tar.bz2`

Traceback (most recent call last):
File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\common.py", line 466, in arg2spec
    spec = MatchSpec(spec_from_line(arg), normalize=True)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\resolve.py", line 43, in __new__
    spec, _, oparts = spec.partition('(')
AttributeError: 'NoneType' object has no attribute 'partition'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\exceptions.py", line 473, in conda_exception_handler
    return_value = func(*args, **kwargs)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main.py", line 144, in _main
    exit_code = args.func(args, p)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main_install.py", line 80, in execute
    install(args, parser, 'install')
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\install.py",line 198, in install
    specs.extend(common.specs_from_args(args.packages, json=context.json))
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\common.py", line 483, in specs_from_args
    return [arg2spec(arg, json=json) for arg in args]
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\common.py", line 483, in <listcomp>
    return [arg2spec(arg, json=json) for arg in args]
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\common.py", line 468, in arg2spec
    raise CondaValueError('invalid package specification: %s' % arg)
conda.exceptions.CondaValueError: Value error: invalid package specification
: C:\Program Files\Anaconda3\pkgs\pyvisa-1.8-py35_0.tar.bz2
</code>```

答:
Replace ...

```<code>conda install --offline --use-local --use-index-cache C:\Program%20Files\Anaconda3\pkgs\pyvisa-1.8-py35_0.tar.bz2
</code>```

... with:

```<code>conda install --offline --use-local --use-index-cache "C:\Program Files\Anaconda3\pkgs\pyvisa-1.8-py35_0.tar.bz2"
</code>```

Basically, don't URI encode the absolute path.

Body:
I have a laptop that can't connect to the internet that I have a working version of Anaconda 3 version 4.2 on.  I also want to install the PyVISA package.

I downloaded the tar.bz2 file and copied it to the Anaconda3/pkgs folder.  I navigate to the directory and use the command:

C:\Program Files\Anaconda3\pkgs>conda install --offline --use-local --use-index-cache pyvisa-1.8-py35_0.tar.bz2

And the response I get is:

Extracting packages ...
An unexpected error has occurred.                                     |   0%
Please consider posting the following information to the
conda GitHub issue tracker at:

https://github.com/conda/conda/issues

Current conda install:

           platform : win-32
      conda version : 4.2.9
   conda is private : False
  conda-env version : 4.2.9
conda-build version : 2.0.2
     python version : 3.5.2.final.0
   requests version : 2.11.1
   root environment : C:\Program Files\Anaconda3  (read only)
default environment : C:\Program Files\Anaconda3
   envs directories : C:\Users\Name\.conda\envs
                      C:\Program Files\Anaconda3\envs
      package cache : C:\Users\Name\.conda\envs\.pkgs
                      C:\Program Files\Anaconda3\pkgs
       channel URLs : https://repo.continuum.io/pkgs/free/win-32/  (offline)

                      https://repo.continuum.io/pkgs/free/noarch/  (offline)

                      https://repo.continuum.io/pkgs/pro/win-32/  (offline)
                      https://repo.continuum.io/pkgs/pro/noarch/  (offline)
                      https://repo.continuum.io/pkgs/msys2/win-32/  (offline)
                      https://repo.continuum.io/pkgs/msys2/noarch/  (offline)
        config file : None
       offline mode : True

`$ C:\Program Files\Anaconda3\Scripts\conda-script.py install --offline --use-local --use-index-cache pyvisa-1.8-py35_0.tar.bz2`

Traceback (most recent call last):
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\exceptions.py", l
ine 473, in conda_exception_handler
    return_value = func(*args, **kwargs)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main.py", lin
e 144, in _main
    exit_code = args.func(args, p)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main_install.
py", line 80, in execute
    install(args, parser, 'install')
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\install.py",
line 209, in install
    explicit(args.packages, prefix, verbose=not context.quiet)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\misc.py", line 18
7, in explicit
    execute_actions(actions, index=index, verbose=verbose)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\plan.py", line 64
3, in execute_actions
    inst.execute_instructions(plan, index, verbose)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\instructions.py",
line 134, in execute_instructions
    cmd(state, arg)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\instructions.py",
line 58, in EXTRACT_CMD
    extract(arg)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\install.py", line
792, in extract
    url = rec['urls'][0]
IndexError: list index out of range

From "list index out of range" I figured that it might not be finding the file, so I used the full path for it:

C:\Program Files\Anaconda3\pkgs>conda install --offline --use-local --use-index-cache C:\Program%20Files\Anaconda3\pkgs\pyvisa-1.8-py35_0.tar.bz2

The response I get is:

Traceback (most recent call last):
File "C:\Program Files\Anaconda3\lib\site-packages\conda\exceptions.py", line
473, in conda_exception_handler
return_value = func(*args, **kwargs)
File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main.py", line 14
4, in _main
exit_code = args.func(args, p)
File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main_install.py",
line 80, in execute
install(args, parser, 'install')
File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\install.py", line
209, in install
explicit(args.packages, prefix, verbose=not context.quiet)
File "C:\Program Files\Anaconda3\lib\site-packages\conda\misc.py", line 70, in
explicit
raise CondaFileNotFoundError(join(url_p, fn))
conda.exceptions.CondaFileNotFoundError: <exception str() failed>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Program Files\Anaconda3\Scripts\conda-script.py", line 5, in <module>

sys.exit(conda.cli.main())
File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main.py", line 15
0, in main
return conda_exception_handler(_main)
File "C:\Program Files\Anaconda3\lib\site-packages\conda\exceptions.py", line
487, in conda_exception_handler
print_conda_exception(e)
File "C:\Program Files\Anaconda3\lib\site-packages\conda\exceptions.py", line
393, in print_conda_exception
stderrlogger.info(repr(exception))
File "C:\Program Files\Anaconda3\lib\site-packages\conda\__init__.py", line 42
, in __repr__
return '%s: %s\n' % (self.__class__.__name__, text_type(self))
File "C:\Program Files\Anaconda3\lib\site-packages\conda\__init__.py", line 45
, in __str__
return text_type(self.message % self._kwargs)
TypeError: a float is required

What's going on here?  Is there a way to install this package offline?

UPDATE 1:

Following the advice below I tried

C:\Program Files\Anaconda3\pkgs>conda install --offline --use-local --use-index-cache --debug "C:\Program Files\Anaconda3\pkgs\pyvisa-1.8-py35_0.tar.bz2"

And now I'm getting:

CondaValueError: Value error: invalid package specification

as a default error message, and if I use debug, it's the following:

DEBUG conda.models.channel:__init__(140): making channel object for url:https://repo.continuum.io/pkgs/free/win-32/alabaster-0.7.9-py35_0.tar.bz2
DEBUG conda.common.url:path_to_url(26): C:\Users\Name\conda-bld converted to file:///C:/Users/Name/conda-bld
DEBUG conda.models.channel:__init__(140): making channel object for url:file:///C:/Users/Name/conda-bld
DEBUG conda.models.channel:__init__(140): making channel object for url:https://repo.continuum.io/pkgs/free
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/pro
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/msys2
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/free/win-32/anaconda-4.2.0-np111py35_0.tar.bz2
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/free/win-32/anaconda-clean-1.0.0-py35_0.tar.bz2
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/free/win-32/anaconda-client-1.5.1-py35_0.tar.bz2
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/free/win-32/anaconda-navigator-1.3.1-py35_0.tar.bz2
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/free/win-32/argcomplete-1.0.0-py35_1.tar.bz2
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/free/win-32/astroid-1.4.7-py35_0.tar.bz2
DEBUG conda.models.channel:__init__(140): making channel object for url: https://repo.continuum.io/pkgs/free/win-32/astropy-1.2.1-np111py35_0.tar.bz2

And so on for what looks like all my packages, followed by

An unexpected error has occurred.
Please consider posting the following information to the
conda GitHub issue tracker at:

https://github.com/conda/conda/issues

INFO conda.common.io:captured(27): overtaking stderr and stdout
DEBUG conda.models.channel:__init__(161): making channel object for named channel: defaults
INFO conda.common.io:captured(33): stderr and stdout yielded back
Current conda install:

           platform : win-32
      conda version : 4.2.9
   conda is private : False
  conda-env version : 4.2.9
conda-build version : 2.0.2
     python version : 3.5.2.final.0
   requests version : 2.11.1
   root environment : C:\Program Files\Anaconda3  (read only)
default environment : C:\Program Files\Anaconda3
   envs directories : C:\Users\Name\.conda\envs
                      C:\Program Files\Anaconda3\envs
      package cache : C:\Users\Name\.conda\envs\.pkgs
                      C:\Program Files\Anaconda3\pkgs
       channel URLs : https://repo.continuum.io/pkgs/free/win-32/  (offline)

                      https://repo.continuum.io/pkgs/free/noarch/  (offline)

                      https://repo.continuum.io/pkgs/pro/win-32/  (offline)
                      https://repo.continuum.io/pkgs/pro/noarch/  (offline)
                      https://repo.continuum.io/pkgs/msys2/win-32/  (offline)
                      https://repo.continuum.io/pkgs/msys2/noarch/  (offline)
        config file : None
       offline mode : True

`$ C:\Program Files\Anaconda3\Scripts\conda-script.py install --offline --use-local --use-index-cache --debug C:\Program Files\Anaconda3\pkgs\pyvisa-1.8-py35_0.tar.bz2`

Traceback (most recent call last):
File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\common.py", line 466, in arg2spec
    spec = MatchSpec(spec_from_line(arg), normalize=True)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\resolve.py", line 43, in __new__
    spec, _, oparts = spec.partition('(')
AttributeError: 'NoneType' object has no attribute 'partition'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\exceptions.py", line 473, in conda_exception_handler
    return_value = func(*args, **kwargs)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main.py", line 144, in _main
    exit_code = args.func(args, p)
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\main_install.py", line 80, in execute
    install(args, parser, 'install')
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\install.py",line 198, in install
    specs.extend(common.specs_from_args(args.packages, json=context.json))
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\common.py", line 483, in specs_from_args
    return [arg2spec(arg, json=json) for arg in args]
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\common.py", line 483, in <listcomp>
    return [arg2spec(arg, json=json) for arg in args]
  File "C:\Program Files\Anaconda3\lib\site-packages\conda\cli\common.py", line 468, in arg2spec
    raise CondaValueError('invalid package specification: %s' % arg)
conda.exceptions.CondaValueError: Value error: invalid package specification
: C:\Program Files\Anaconda3\pkgs\pyvisa-1.8-py35_0.tar.bz2

Body:
Replace ...

conda install --offline --use-local --use-index-cache C:\Program%20Files\Anaconda3\pkgs\pyvisa-1.8-py35_0.tar.bz2

... with:

conda install --offline --use-local --use-index-cache "C:\Program Files\Anaconda3\pkgs\pyvisa-1.8-py35_0.tar.bz2"

Basically, don't URI encode the absolute path.


问:
Why my directive work weird in angularJS
i just need display the bouton with ng-show=true and none with ng-show=false with a directory but this one work weird i don t know why i dont recup the scope (ng-show="editNucleo")

this is my code

```<code>   <!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myCtrl">
<table>
<tr dom-directive ng-repeat="x in records">
<td>{{x}}</td>
<td>
<div class="editNucleo" ng-show="editNucleo">
<input type="image" id="myimage" style="width:20px;" src="http://www.iconsdb.com/icons/download/green/edit-512.png" />
</div>
</td>
</tr>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.records = [
    "Alfreds Futterkiste",
    "Berglunds snabbköp",
    "Centro comercial Moctezuma",
    "Ernst Handel",
  ]
});

app.directive('domDirective', function () {
    return {
        restrict: 'A',
        link: function ($scope, element, attrs) {
            element.on('click', function () {
                element.html('You clicked me!');
            });
            element.on('mouseover', function () {
                $scope.editNucleo=false;
                element.css('background-color', 'yellow');

            });
            element.on('mouseleave', function () {
                element.css('background-color', 'white');
                $scope.editNucleo=true;
            });
        }
    };
});

</script>
</code>```

if some one can help me please

thanks in advance

EDIT

SOLUTION FOUND WITH $digest

my new directive

```<code>.directive('domDirective', function() {
        // I bind the JavaScript events to the scope.
        function link( $scope, element, attributes ) {

            $scope.editNucleo = false;
            // I activate the element on mouse-enter.
            element.on('mouseenter', function () {
                    element.css('background-color', 'yellow');
                    $scope.editNucleo=true;
                    // NOTE: By calling the $digest() instead of the more typical
                    // $apply() method, we will only trigger watchers on the local
                    // scope (and its children). We will NOT trigger any watchers
                    // on the parent scope.
                    $scope.$digest();
                }
            );
            // I deactivate the element on mouse-leave.
            element.on('mouseleave', function () {
                element.css('background-color', 'white');
                    $scope.editNucleo=false;
                    // NOTE: By calling the $digest() instead of the more typical
                    // $apply() method, we will only trigger watchers on the local
                    // scope (and its children). We will NOT trigger any watchers
                    // on the parent scope.
                    $scope.$digest();
                }
            );
        }
        // NOTE: By setting scope to TRUE, the directive creates a new child scope
        // that separates it from the parent scope (creating a isolated part of
        // the scope chain).
        return({
            link: link,
            restrict: "A",
            scope: true
        });
    }
);
</code>```

i have no latence problems with this directive

答:
I recommend against accessing dom elements inside of your directive. Instead, you should be calling back into your directive when the dom elements happen.

So, you should be using the ng-mouseenter and ng-mouseleave events.  Here is how I would do it. Notice the implementation of doShow and doHide and how they are invoked directly from the template.

```<code><!DOCTYPE html>
<html>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
  <body ng-app="myApp" ng-controller="myCtrl">
    <table>
      <tr dom-directive ng-repeat="x in records" ng-mouseenter="doShow()" ng-mouseleave="doHide()">
        <td>{{x}}</td>
        <td>
          <div ng-show="show">
            <input type="image" id="myimage" style="width:20px;" src="http://www.iconsdb.com/icons/download/green/edit-512.png" />
          </div>
        </td>
      </tr>
    </table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.records = [
    "Alfreds Futterkiste",
    "Berglunds snabbköp",
    "Centro comercial Moctezuma",
    "Ernst Handel",
  ]
});

app.directive('domDirective', function () {
    return {
        restrict: 'A',
        link: function ($scope, element, attrs) {
          $scope.doShow = () => $scope.show = true;
          $scope.doHide = () => $scope.show = false;
        }
    };
});
</script>
</body>
</html>
</code>```

Body:
i just need display the bouton with ng-show=true and none with ng-show=false with a directory but this one work weird i don t know why i dont recup the scope (ng-show="editNucleo")

this is my code

   <!DOCTYPE html>

{{x}}

<input type="image" id="myimage" style="width:20px;" src="http://www.iconsdb.com/icons/download/green/edit-512.png" />

if some one can help me please

thanks in advance

EDIT

SOLUTION FOUND WITH $digest

my new directive

.directive('domDirective', function() {
        // I bind the JavaScript events to the scope.
        function link( $scope, element, attributes ) {

            $scope.editNucleo = false;
            // I activate the element on mouse-enter.
            element.on('mouseenter', function () {
                    element.css('background-color', 'yellow');
                    $scope.editNucleo=true;
                    // NOTE: By calling the $digest() instead of the more typical
                    // $apply() method, we will only trigger watchers on the local
                    // scope (and its children). We will NOT trigger any watchers
                    // on the parent scope.
                    $scope.$digest();
                }
            );
            // I deactivate the element on mouse-leave.
            element.on('mouseleave', function () {
                element.css('background-color', 'white');
                    $scope.editNucleo=false;
                    // NOTE: By calling the $digest() instead of the more typical
                    // $apply() method, we will only trigger watchers on the local
                    // scope (and its children). We will NOT trigger any watchers
                    // on the parent scope.
                    $scope.$digest();
                }
            );
        }
        // NOTE: By setting scope to TRUE, the directive creates a new child scope
        // that separates it from the parent scope (creating a isolated part of
        // the scope chain).
        return({
            link: link,
            restrict: "A",
            scope: true
        });
    }
);

i have no latence problems with this directive

Body:
I recommend against accessing dom elements inside of your directive. Instead, you should be calling back into your directive when the dom elements happen.

So, you should be using the ng-mouseenter and ng-mouseleave events.  Here is how I would do it. Notice the implementation of doShow and doHide and how they are invoked directly from the template.

<!DOCTYPE html>
<html>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
  <body ng-app="myApp" ng-controller="myCtrl">
    <table>
      <tr dom-directive ng-repeat="x in records" ng-mouseenter="doShow()" ng-mouseleave="doHide()">
        <td>{{x}}</td>
        <td>
          <div ng-show="show">
            <input type="image" id="myimage" style="width:20px;" src="http://www.iconsdb.com/icons/download/green/edit-512.png" />
          </div>
        </td>
      </tr>
    </table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.records = [
    "Alfreds Futterkiste",
    "Berglunds snabbköp",
    "Centro comercial Moctezuma",
    "Ernst Handel",
  ]
});

app.directive('domDirective', function () {
    return {
        restrict: 'A',
        link: function ($scope, element, attrs) {
          $scope.doShow = () => $scope.show = true;
          $scope.doHide = () => $scope.show = false;
        }
    };
});
</script>
</body>
</html>


问:
Trying to understand (function(func) { func(); } in JavaScript
Coming from C, every function needs a name that is used to call that specific function. but in the JavaScript code below. There is no name at all. So how does function(func) { func(); } calls the something.push(function() ?

Not to mention that something.push(function() doesn't even have an argument, which from C perspective, this is wrong

```<code>var something = [],
  object = {
    a: true,
    b: true,
    c: true
}

 for (let key in object){
   something.push(function() {
   console.log(key);
   });
 }

 something.forEach(function(func) { func(); }):
</code>```

答:
JavaScript is more abstract language than C. In JavaScript interpretter internally saves types and pointers of every variable. When you declare a function, it is internally saved somewhere in memory and pointer of that function is passed to whatever you passed it (here to something.forEach).

But, this is not pointer like in C, you cannot access its value (function address) nor you can change it. In JavaScript these pseudo-pointers are called "references". Simply, when you try to call something, interpretter engine will check its type. If its type type is a function, thread will do some preparations and then execute jump to memory location which function pointer is pointing to.

Body:
Coming from C, every function needs a name that is used to call that specific function. but in the JavaScript code below. There is no name at all. So how does function(func) { func(); } calls the something.push(function() ?

Not to mention that something.push(function() doesn't even have an argument, which from C perspective, this is wrong

var something = [],
  object = {
    a: true,
    b: true,
    c: true
}

 for (let key in object){
   something.push(function() {
   console.log(key);
   });
 }

 something.forEach(function(func) { func(); }):


答:
The something array is storing references to functions, but not invoking them. In the forEach loop, each function within the array is being invoked.

To be fair, the naming is confusing. You could just as easily write:

```<code>something.forEach(function(storedFunction) { storedFunction(); }):
</code>```

since it's a temporary variable

Title: Trying to understand (function(func) { func(); } in JavaScript

Body:
The something array is storing references to functions, but not invoking them. In the forEach loop, each function within the array is being invoked.

To be fair, the naming is confusing. You could just as easily write:

something.forEach(function(storedFunction) { storedFunction(); }):

since it's a temporary variable


答:
So, what's happening here is in the loop, we are pushing a function to something on each iteration. Assuming something is an array in this case.

Then, we call the collection's foreach() function. The first argument in this function is always the current item over which we are iterating. In this case, we're iterating over the list of functions we built in the loop. Since these are functions, we can call them, which is what's happening for each one.

Here's an example to help illustrate:

```<code>// declare some functions
function a(){console.log('hi');}
function b(){console.log('there');}
function c(){console.log('friend');}
const ar = [];

// push the functions to the array
ar.push(a);
ar.push(b);
ar.push(c);
ar.push(a);

ar.forEach(function(func) {func();});

// console output:
// hi
// there
// friend
// hi
</code>```

EDIT: I highly recommend you read Mozilla's documentation of the function type. If you go there and thoroughly read through it I think you'll have a very solid grasp of this concept.

Body:
So, what's happening here is in the loop, we are pushing a function to something on each iteration. Assuming something is an array in this case.

Then, we call the collection's foreach() function. The first argument in this function is always the current item over which we are iterating. In this case, we're iterating over the list of functions we built in the loop. Since these are functions, we can call them, which is what's happening for each one.

Here's an example to help illustrate:

// declare some functions
function a(){console.log('hi');}
function b(){console.log('there');}
function c(){console.log('friend');}
const ar = [];

// push the functions to the array
ar.push(a);
ar.push(b);
ar.push(c);
ar.push(a);

ar.forEach(function(func) {func();});

// console output:
// hi
// there
// friend
// hi

EDIT: I highly recommend you read Mozilla's documentation of the function type. If you go there and thoroughly read through it I think you'll have a very solid grasp of this concept.


问:
trim(both) doesnt not trim the leading character
Table qqq:

```<code>|**type**  | **ColB** |

-+-----------+-----------+-
| A     | 0030-0000     |
| A     | 0234-0001     |
| A     | 0001-0003     |
</code>```

type is Varchar,
ColB is Varchar

I would like to trim all zeroes in leading and trailing poisition. The expected outcome is :

```<code>|**type**  | **ColB** |

-+-----------+-----------+-
| A     | 30-        |
| A     | 234-0001   |
| A     | 1-0003     |
</code>```

This is query I wrote:

select type, TRIM(both '0' FROM colB) From qqq
where type = 'A';

However, my output is:

```<code>|**type**  | **ColB** |

-+-----------+-----------+-
| A     | 0030-         |
| A     | 0234-0001     |
| A     | 0001-0003     |
</code>```

the trim (both does not working out...

答:
After much diagnosis via chat I began to suspect that there was a leading space in the strings.  I suggested the following as an answer...</p>

```<code>SELECT TRIM( '0' FROM TRIM( fieldName ) )
FROM tableName;
</code>```

Body:
Table qqq:

|**type**  | **ColB** |

-+-----------+-----------+-
| A     | 0030-0000     |
| A     | 0234-0001     |
| A     | 0001-0003     |

type is Varchar,
ColB is Varchar

I would like to trim all zeroes in leading and trailing poisition. The expected outcome is :

|**type**  | **ColB** |

-+-----------+-----------+-
| A     | 30-        |
| A     | 234-0001   |
| A     | 1-0003     |

This is query I wrote:

select type, TRIM(both '0' FROM colB) From qqq
where type = 'A';

However, my output is:

|**type**  | **ColB** |

-+-----------+-----------+-
| A     | 0030-         |
| A     | 0234-0001     |
| A     | 0001-0003     |

the trim (both does not working out...

Body:
After much diagnosis via chat I began to suspect that there was a leading space in the strings.  I suggested the following as an answer...

SELECT TRIM( '0' FROM TRIM( fieldName ) )
FROM tableName;


答:
In JavaScript, functions are treated as objects. And in C you must be aware that not every object (value) needs to have a name, or doesn't need to be stored in a variable. Just like you can have sum (4, 5);. 4 and 5 are values not stored in variables.

To answer your question about how they will be called if they have no name, the function is passed as an argument to the push function. There the formal parameter must have some name. So it can be called by that name. In this case push doesn't call it but stores it in an array to be called later. It can be called by indexing into the array.


问:
Excel VBA - Subscript out of range - Sheets name as a variable
I am trying to work on a Worksheet whose name is a variable.

I have a main sheet, called "data" where I go to catch a list of names of existing sheets.

My code is as follows :

```<code>Dim data as Worksheet
dim sheet_name as String
Dim i as Integer
Set data = ThisWorkbook.Sheets("Data")

For i = 2 to 10
    sheet_name = data.Range("A"&i).Value
    With ThisWorkbook.Sheets(sheet_name)
        'Operations on the worksheet
    End With
Next i
</code>```

The error prompted is "Runtime Error 9 : Subscript Out of Range" for the specific line :

```<code>With This Workbook.Sheets(sheet_name)
</code>```

It is as if the object Sheets didn't understand the string sheet_name.
The Sheet "sheet_name" exists for sure, I double-checked.

Unfortunately, I cannot call the sheet by its name because I have too many sheets to operate on, this is why I wanted to do a loop.

I tried not working with the "With" clause but just referring to every object of the sheets with "ThisWorkbook.Sheets(sheet_name) in front but doesn't work either.

Do you know if it is possible to call a string variable inside a Sheets()?

Thanks a lot for your help !

Kind regards,

答:
The reason for your error was given in the comments above by @chris neilsen

You could use the code below to check or avoid having these kind of errors:

```<code>Option Explicit

Sub CheckShtExists()

Dim data As Worksheet
Dim sheet_name As String

Set data = ThisWorkbook.Sheets("Data")

Dim ws As Worksheet
Dim ShtNamesArr() As String
Dim i As Long

ReDim ShtNamesArr(0 To ThisWorkbook.Worksheets.Count - 1) ' resize array to number of worksheets in This Workbook

' loop thourgh all worksheets and store their names in array
For Each ws In ThisWorkbook.Worksheets
    ShtNamesArr(i) = ws.Name
    i = i + 1
Next ws

For i = 2 To 10
    If data.Range("A" & i).Value <> "" Then ' ignore blank cells
        sheet_name = data.Range("A" & i).Value
        If Not IsError(Application.Match(sheet_name, ShtNamesArr, 0)) Then ' use Application.Match to see there is a sheet with this name
            With ThisWorkbook.Sheets(sheet_name)
                'Operations on the worksheet
            End With
        Else ' No Match
            MsgBox sheet_name & " doesn't exists in your workbook"
        End If
    End If
Next i

End Sub
</code>```

Body:
I am trying to work on a Worksheet whose name is a variable.

I have a main sheet, called "data" where I go to catch a list of names of existing sheets.

My code is as follows :

Dim data as Worksheet
dim sheet_name as String
Dim i as Integer
Set data = ThisWorkbook.Sheets("Data")

For i = 2 to 10
    sheet_name = data.Range("A"&i).Value
    With ThisWorkbook.Sheets(sheet_name)
        'Operations on the worksheet
    End With
Next i

The error prompted is "Runtime Error 9 : Subscript Out of Range" for the specific line :

With This Workbook.Sheets(sheet_name)

It is as if the object Sheets didn't understand the string sheet_name.
The Sheet "sheet_name" exists for sure, I double-checked.

Unfortunately, I cannot call the sheet by its name because I have too many sheets to operate on, this is why I wanted to do a loop.

I tried not working with the "With" clause but just referring to every object of the sheets with "ThisWorkbook.Sheets(sheet_name) in front but doesn't work either.

Do you know if it is possible to call a string variable inside a Sheets()?

Thanks a lot for your help !

Kind regards,

Body:
The reason for your error was given in the comments above by @chris neilsen

You could use the code below to check or avoid having these kind of errors:

Option Explicit

Sub CheckShtExists()

Dim data As Worksheet
Dim sheet_name As String

Set data = ThisWorkbook.Sheets("Data")

Dim ws As Worksheet
Dim ShtNamesArr() As String
Dim i As Long

ReDim ShtNamesArr(0 To ThisWorkbook.Worksheets.Count - 1) ' resize array to number of worksheets in This Workbook

' loop thourgh all worksheets and store their names in array
For Each ws In ThisWorkbook.Worksheets
    ShtNamesArr(i) = ws.Name
    i = i + 1
Next ws

For i = 2 To 10
    If data.Range("A" & i).Value <> "" Then ' ignore blank cells
        sheet_name = data.Range("A" & i).Value
        If Not IsError(Application.Match(sheet_name, ShtNamesArr, 0)) Then ' use Application.Match to see there is a sheet with this name
            With ThisWorkbook.Sheets(sheet_name)
                'Operations on the worksheet
            End With
        Else ' No Match
            MsgBox sheet_name & " doesn't exists in your workbook"
        End If
    End If
Next i

End Sub


问:
VSTS website view Git tags
I am using Visual Studio Team Services with a project, using Git for the source control.

I am using the Git command line to tag the last commit with a version number before doing a release, then pushing it to VSTS, as follows:

```<code>git tag -a 1.2.4 -m "Some Message"
git push origin master --tags
</code>```

This appears to complete successfully.

When I go to the "Code" tab on the VSTS website, I can see all of the commits in the branch history, but I cannot see the version tag that I created and pushed.

How can I view these tags on the VSTS website?

答: In the History Tab, you should also mark sure Branch Updates tab is selected -> click s-resize on the right of master branch -> select tag 1.2.4 in Tags tab -> then you will find the commit that tag 1.2.4 is on.

Title: VSTS website view Git tags

Body:
I am using Visual Studio Team Services with a project, using Git for the source control.

I am using the Git command line to tag the last commit with a version number before doing a release, then pushing it to VSTS, as follows:

git tag -a 1.2.4 -m "Some Message"
git push origin master --tags

This appears to complete successfully.

When I go to the "Code" tab on the VSTS website, I can see all of the commits in the branch history, but I cannot see the version tag that I created and pushed.

How can I view these tags on the VSTS website?


问:
PyCharm not using my configured virtualenv interpreter
I've added my virtualenv on the settings and selected it to be the default interpreter like so:

Now when I try to run a script, I notice that it's actually not using the virtualenv's interpreter:

What am I doing wrong? I've tried restarting, I've tried selecting another interpreter and re-selecting. And so far no luck.

答:
Check your script configurations.

Is your script using a different python interpreter?


问:
Swift: Overlay rectangle with text over view
If our app has a network connectivity error we would like to overlay a colored and transparent rectangle over the top of the screen with some "Network not available" like text.  The rectangle should cover the full width of the screen and the height should be enough to just show the text.   We would use a timer to only show the rectangle for a brief period of time.  How can you do this?

The actual view may be a UITableViewController, a UIViewController, or something else...

答:
You can do this:</p>

```<code>let deadlineTime = DispatchTime.now() + .seconds(2)

let window = UIApplication.shared.keyWindow!

let rectangleView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 20))
rectangleView.backgroundColor = UIColor.red

let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 20))
label.text = "Network not available"

rectangleView.addSubview(label)

window.addSubview(rectangleView)

DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
    rectangleView.removeFromSuperview()
}
</code>```

Body:
You can do this:

let deadlineTime = DispatchTime.now() + .seconds(2)

let window = UIApplication.shared.keyWindow!

let rectangleView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 20))
rectangleView.backgroundColor = UIColor.red

let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 20))
label.text = "Network not available"

rectangleView.addSubview(label)

window.addSubview(rectangleView)

DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
    rectangleView.removeFromSuperview()
}


问:
AnjularJs integration with Spring boot
I need to call index() method in java class. But I tried this way it is not working.

It is going up to console.log('coming here....'); in controller.js, after that http path is not recognizing.

```<code>@RestController
public class DatumBoxShedule {

    @Autowired
    private DatumService datumService;

    @RequestMapping(value = "/loadIndex", produces = MediaType.APPLICATION_JSON_VALUE,  method = RequestMethod.GET)
    public String index() throws IOException {

    }
}
</code>```

controller.js

```<code>app.controller('datumBoxShedule', function($scope, $http) {
    $scope.newTodo = {};

    $scope.loadIndex = function(){
         console.log('coming here....');
        $http.get('loadIndex')
        .success(function(data, status, headers, config) {
            $scope.todos = data;
         })
        .error(function(data, status, headers, config) {
              alert('Error loading DatumBoxShedule');
        });
    };

    $scope.loadIndex();
});
</code>```

答:
I figureout ,issue is not in the anujularjs.Issue is in the spring.

my componantscan is not working

package main.java.datumbox;

@Configuration
@SpringBootApplication
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
@ComponentScan({"main.java.datumbox.service.impl","main.java.datumbox.controller","main.java.datumbox.service"})
public class Application{

```<code>public static void main(String[] args) throws Exception {

    SpringApplication.run(Application.class,args);

}
</code>```

}

package main.java.datumbox.service.impl;

public class DatumServiceImpl{

```<code>@Autowired(required = true)
DatumDataRepository datumDataRepository;
</code>```

}

package main.java.datumbox.controller;

@RestController
public class DatumBoxController {

```<code>@Autowired
private DatumService datumService;

@Autowired
private DatumServiceImpl datumServiceImpl;

@RequestMapping( value = "/loadIndex" , produces = MediaType.APPLICATION_JSON_VALUE,  method = RequestMethod.GET)
public String index() throws IOException {

}
</code>```

}

package main.java.datumbox.service;

@Service
public class DatumService{

```<code>@Autowired
HitApiService hitApiService;
</code>```

}

error is coming..

APPLICATION FAILED TO START

Description:

Field datumServiceImpl in main.java.datumbox.controller.DatumBoxController required a bean of type 'main.java.datumbox.service.impl.DatumServiceImpl' that could not be found.

Action:

Consider defining a bean of type 'main.java.datumbox.service.impl.DatumServiceImpl' in your configuration.

Title: AnjularJs integration with Spring boot

Body:
I need to call index() method in java class. But I tried this way it is not working.

It is going up to console.log('coming here....'); in controller.js, after that http path is not recognizing.

@RestController
public class DatumBoxShedule {

    @Autowired
    private DatumService datumService;

    @RequestMapping(value = "/loadIndex", produces = MediaType.APPLICATION_JSON_VALUE,  method = RequestMethod.GET)
    public String index() throws IOException {

    }
}

controller.js

app.controller('datumBoxShedule', function($scope, $http) {
    $scope.newTodo = {};

    $scope.loadIndex = function(){
         console.log('coming here....');
        $http.get('loadIndex')
        .success(function(data, status, headers, config) {
            $scope.todos = data;
         })
        .error(function(data, status, headers, config) {
              alert('Error loading DatumBoxShedule');
        });
    };

    $scope.loadIndex();
});

Body:
I figureout ,issue is not in the anujularjs.Issue is in the spring.

my componantscan is not working

package main.java.datumbox;

@Configuration
@SpringBootApplication
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
@ComponentScan({"main.java.datumbox.service.impl","main.java.datumbox.controller","main.java.datumbox.service"})
public class Application{

public static void main(String[] args) throws Exception {

    SpringApplication.run(Application.class,args);

}

}

package main.java.datumbox.service.impl;

public class DatumServiceImpl{

@Autowired(required = true)
DatumDataRepository datumDataRepository;

}

package main.java.datumbox.controller;

@RestController
public class DatumBoxController {

@Autowired
private DatumService datumService;

@Autowired
private DatumServiceImpl datumServiceImpl;

@RequestMapping( value = "/loadIndex" , produces = MediaType.APPLICATION_JSON_VALUE,  method = RequestMethod.GET)
public String index() throws IOException {

}

}

package main.java.datumbox.service;

@Service
public class DatumService{

@Autowired
HitApiService hitApiService;

}

error is coming..

APPLICATION FAILED TO START

Description:

Field datumServiceImpl in main.java.datumbox.controller.DatumBoxController required a bean of type 'main.java.datumbox.service.impl.DatumServiceImpl' that could not be found.

Action:

Consider defining a bean of type 'main.java.datumbox.service.impl.DatumServiceImpl' in your configuration.


问:
Linq - how to replace a lists property with value from another list where both keys are equal
I have 2 lists groupoptions and dataIndicator

```<code>class groupoptions{
  ...
  GroupName string
}

class dataIndicator{
  ...
 HeaderID int
 IndicatorDescription
}
</code>```

currently my groupname possible values are 4 or 5 or 11

first i want to get all dataindicators where headerid  is equal to GroupName, then replace those GroupNames with dataindicator's IndicatorDescription

What would be the Linq syntax for this?

UPDATE

using join

```<code>var newList = from first in dataIndicator
                      join second in groupedoptions
                      on first.HeaderID.ToString() equals second.GroupName
                      select new { first,second };
</code>```

What next?
PROBLEM: i want to do it inside a constructor that is being created inside a Linq Select

```<code>var list = xyz.Select(x => new groupoptions(){
   GroupName = x.Key.ToString();
 })
</code>```

答:
this little for loop gets what you are looking to do done in just a few lines. No need to use linq if all you're looking to do is be efficient.

```<code>class ConsoleApplication1
{
    public static void Main()
    {

        List<groupOptions> g = new List<groupOptions>();
        List<dataIndicator> d = new List<dataIndicator>();

        for (int i = 0; i < 4; i++)
        {
            g.Add(new groupOptions() { groupName = i.ToString() });
            d.Add(new dataIndicator() { headerID = i, indicatorDescription = "id:" + i});
            Console.Write(g[i].groupName + ":");
            Console.WriteLine(d[i].headerID);
        }

        Console.WriteLine("enter to change");
        Console.ReadLine();
</code>```

this is the pertinent part:

```<code>        for(int i = 0; i < g.Count(); i++)
        {
            if (g[i].groupName == d[i].headerID.ToString())
                g[i].groupName = d[i].indicatorDescription;
        }
</code>```

the rest just is just to make sure it worked.

```<code>        for(int i = 0; i < d.Count(); i++)
        {
            Console.WriteLine(g[i].groupName);
        }

        Console.ReadLine();
    }
}

public class groupOptions
{

    public string groupName { get; set; }

}

class dataIndicator
{
    public int headerID { get; set; }
    public string indicatorDescription { get; set; }
}
</code>```

Body:
I have 2 lists groupoptions and dataIndicator

class groupoptions{
  ...
  GroupName string
}

class dataIndicator{
  ...
 HeaderID int
 IndicatorDescription
}

currently my groupname possible values are 4 or 5 or 11

first i want to get all dataindicators where headerid  is equal to GroupName, then replace those GroupNames with dataindicator's IndicatorDescription

What would be the Linq syntax for this?

UPDATE

using join

var newList = from first in dataIndicator
                      join second in groupedoptions
                      on first.HeaderID.ToString() equals second.GroupName
                      select new { first,second };

What next?
PROBLEM: i want to do it inside a constructor that is being created inside a Linq Select

var list = xyz.Select(x => new groupoptions(){
   GroupName = x.Key.ToString();
 })

Body:
this little for loop gets what you are looking to do done in just a few lines. No need to use linq if all you're looking to do is be efficient.

class ConsoleApplication1
{
    public static void Main()
    {

        List<groupOptions> g = new List<groupOptions>();
        List<dataIndicator> d = new List<dataIndicator>();

        for (int i = 0; i < 4; i++)
        {
            g.Add(new groupOptions() { groupName = i.ToString() });
            d.Add(new dataIndicator() { headerID = i, indicatorDescription = "id:" + i});
            Console.Write(g[i].groupName + ":");
            Console.WriteLine(d[i].headerID);
        }

        Console.WriteLine("enter to change");
        Console.ReadLine();

this is the pertinent part:

        for(int i = 0; i < g.Count(); i++)
        {
            if (g[i].groupName == d[i].headerID.ToString())
                g[i].groupName = d[i].indicatorDescription;
        }

the rest just is just to make sure it worked.

        for(int i = 0; i < d.Count(); i++)
        {
            Console.WriteLine(g[i].groupName);
        }

        Console.ReadLine();
    }
}

public class groupOptions
{

    public string groupName { get; set; }

}

class dataIndicator
{
    public int headerID { get; set; }
    public string indicatorDescription { get; set; }
}


问:
Print in Local Printer but Connected to Server PHP
I have a direct printing in PHP using printer functions but we have two printers and only one printer can be added in printer_open(printer name). How can the other pc with different printer can print in their respective local printer?</p>

答:
Use google cloud print as an alternative, it's easy and fast to configure

or you can symple use the javascript in your php code to make the client browser open the print option, use this in your php code

```<code><?php

echo '<script language="Javascript1.2">

  window.print();

</script>';

?>
</code>```

Body:
Use google cloud print as an alternative, it's easy and fast to configure

or you can symple use the javascript in your php code to make the client browser open the print option, use this in your php code

<?php

echo '<script language="Javascript1.2">

  window.print();

</script>';

?>


问:
Why input from file faster and faster?
I hava 10 files, each file is 500M.

I use Long randomValue = Math.abs(random.nextLong()); to generate those files. Every line in the file is a randomValue. And a file has about 26374000 lines.

When I read those files one by one in another program and count cost time, I find the input become more faster. Why?

```<code>read 0 file 26373542 lines time : 27046ms
read 1 file 26373627 lines time : 24155ms
read 2 file 26373676 lines time : 19227ms
read 3 file 26373768 lines time : 22875ms
read 4 file 26373681 lines time : 20813ms
read 5 file 26373774 lines time : 18297ms
read 6 file 26373787 lines time : 10556ms
read 7 file 26373557 lines time : 11614ms
read 8 file 26373566 lines time : 9751ms
read 9 file 26373653 lines time : 13372ms
</code>```

This is my program:

```<code>Long start = new Date().getTime();
FileReader fr = new FileReader(inFile);
BufferedReader br = new BufferedReader(fr);
String num;
while((num = br.readLine()) != null) {
    sorted[j++] = Long.parseLong(num);
    count++;
}
Long end = new Date().getTime();
System.out.println("read " + i + " file " + j + "lines time : " + (mid - start) + "ms");
br.close();
fr.close();
</code>```

答:
A few things:

As has been noted in the comments, the JVM does often improve performance once it has warmed up - although it's not clear from your code snippet whether you're launching a fresh JVM per file or not.

You're reading files from disk. It's not clear if it's a spinning disk or an SSD - these have dramatically different performance characteristics. Nonetheless, there are a large number of variables when reading data from disk that makes it difficult to do direct benchmarks on the underlying algorithm you're testing unless you load the data into memory first and then hit start on your stopwatch.

Your files are not identical (different number of lines, probably different contents, etc.)

Once you've considered the above, you probably need to think about whether you have done enough repeatable tests, whether the test duration is sufficiently long, etc. before drawing too many concrete conclusions about performance.

Title: Why input from file faster and faster?

Body:
I hava 10 files, each file is 500M.

I use Long randomValue = Math.abs(random.nextLong()); to generate those files. Every line in the file is a randomValue. And a file has about 26374000 lines.

When I read those files one by one in another program and count cost time, I find the input become more faster. Why?

read 0 file 26373542 lines time : 27046ms
read 1 file 26373627 lines time : 24155ms
read 2 file 26373676 lines time : 19227ms
read 3 file 26373768 lines time : 22875ms
read 4 file 26373681 lines time : 20813ms
read 5 file 26373774 lines time : 18297ms
read 6 file 26373787 lines time : 10556ms
read 7 file 26373557 lines time : 11614ms
read 8 file 26373566 lines time : 9751ms
read 9 file 26373653 lines time : 13372ms

This is my program:

Long start = new Date().getTime();
FileReader fr = new FileReader(inFile);
BufferedReader br = new BufferedReader(fr);
String num;
while((num = br.readLine()) != null) {
    sorted[j++] = Long.parseLong(num);
    count++;
}
Long end = new Date().getTime();
System.out.println("read " + i + " file " + j + "lines time : " + (mid - start) + "ms");
br.close();
fr.close();


问:
Why Android EditText have to click the second time to trigger the event?
The xml file:

```<code><EditText
        android:drawableLeft="@drawable/icon_lock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:id="@+id/et_pwd"
        android:drawableRight="@drawable/icon_closeeye_32"
        style="@style/editText_base"
        android:hint="@string/pwd_input"/>
</code>```

Outside is LinearLayout

The code:

```<code>private boolean isTouch = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN :
            Drawable drawableRight = etPwd.getCompoundDrawables()[2];

            if(drawableRight == null && event.getAction() != MotionEvent.ACTION_UP) {
                return false;
            }
            if (event.getX() > etPwd.getWidth()
                    - etPwd.getPaddingRight()
                    - drawableRight.getIntrinsicWidth()){
                Drawable drawableLeft = getResources().getDrawable(R.drawable.icon_lock);
                drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());
                if (isTouch) {
                    etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    Drawable drawableOpenEye = getResources().getDrawable(R.drawable.icon_openeye_32);
                    drawableOpenEye.setBounds(0, 0, drawableOpenEye.getMinimumWidth(), drawableOpenEye.getMinimumHeight());
                    etPwd.setCompoundDrawables(drawableLeft, null, drawableOpenEye, null);
                } else {
                    etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    Drawable drawableCloseEye = getResources().getDrawable(R.drawable.icon_closeeye_32);
                    drawableCloseEye.setBounds(0, 0, drawableCloseEye.getMinimumWidth(), drawableCloseEye.getMinimumHeight());
                    etPwd.setCompoundDrawables(drawableLeft, null, drawableCloseEye, null);
                }
                isTouch = !isTouch;
                etPwd.setSelection(etPwd.getText().toString().length());
            }

            break;
        case MotionEvent.ACTION_MOVE :

            break;
        case MotionEvent.ACTION_UP :

            break;
    }

    return false;
}
</code>```

Now! Did not respond for the first time , Click the second time to show the icon open , to show / hide the password.

And i`ve already implements View.OnTouchListener , find the relevant controls to do the click event . Help me , thanks!

答:
You need to either change

```<code>private boolean isTouch = false;
</code>```

to true.

```<code>private boolean isTouch = true;
</code>```

Or you need to switch the blocks inside the if statement around.

The reason for this is because the first time it goes through the codeblock, isTouch is false, and it sets the transformation to password - which it's already in! Now isTouch is set to true, and the second time it goes through the expected code block to show the password.

Body:
The xml file:

<EditText
        android:drawableLeft="@drawable/icon_lock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:id="@+id/et_pwd"
        android:drawableRight="@drawable/icon_closeeye_32"
        style="@style/editText_base"
        android:hint="@string/pwd_input"/>

Outside is LinearLayout

The code:

private boolean isTouch = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN :
            Drawable drawableRight = etPwd.getCompoundDrawables()[2];

            if(drawableRight == null && event.getAction() != MotionEvent.ACTION_UP) {
                return false;
            }
            if (event.getX() > etPwd.getWidth()
                    - etPwd.getPaddingRight()
                    - drawableRight.getIntrinsicWidth()){
                Drawable drawableLeft = getResources().getDrawable(R.drawable.icon_lock);
                drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());
                if (isTouch) {
                    etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    Drawable drawableOpenEye = getResources().getDrawable(R.drawable.icon_openeye_32);
                    drawableOpenEye.setBounds(0, 0, drawableOpenEye.getMinimumWidth(), drawableOpenEye.getMinimumHeight());
                    etPwd.setCompoundDrawables(drawableLeft, null, drawableOpenEye, null);
                } else {
                    etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    Drawable drawableCloseEye = getResources().getDrawable(R.drawable.icon_closeeye_32);
                    drawableCloseEye.setBounds(0, 0, drawableCloseEye.getMinimumWidth(), drawableCloseEye.getMinimumHeight());
                    etPwd.setCompoundDrawables(drawableLeft, null, drawableCloseEye, null);
                }
                isTouch = !isTouch;
                etPwd.setSelection(etPwd.getText().toString().length());
            }

            break;
        case MotionEvent.ACTION_MOVE :

            break;
        case MotionEvent.ACTION_UP :

            break;
    }

    return false;
}

Now! Did not respond for the first time , Click the second time to show the icon open , to show / hide the password.

And i`ve already implements View.OnTouchListener , find the relevant controls to do the click event . Help me , thanks!

Body:
You need to either change

private boolean isTouch = false;

to true.

private boolean isTouch = true;

Or you need to switch the blocks inside the if statement around.

The reason for this is because the first time it goes through the codeblock, isTouch is false, and it sets the transformation to password - which it's already in! Now isTouch is set to true, and the second time it goes through the expected code block to show the password.


问:
Panel Control Windows Forms
I am just wondering if anybody knows anything about the speed of the WinsForms panel control relative to the number of controls placed in it.

I have panels that I need to populate with hundreds of controls and it seems to slow down exponentially.  I have tried making the panel invisible when populating it and this doesn't seem to help.

I am asking for two reasons:

To determine if this slow down is the result of the panel control or
a quite complicated (for me) bit of code that is handling the panel
and adding the items to it.

If it is the result of the panel, then I would like to determine if there
is anything I can do about it.  I am quite a ways into the project
and the project depends upon panels that contain these controls.

Thanks for your time.

My level of expertise is fairly amateur BTW.

答:
You have not shown your code to load the panel. Moreover you need to add more information in your problem about the controls and loading process. With general assumptions, to speed up you can do :-

Lazy load. User will not interact with hundreds of control at a given time. So, load the controls on demand.

Populate the controls in background thread, and make them ready just before they are required to be shown.

Load them based on the priority of the user interaction.

Title: Panel Control Windows Forms


问:
Hiding tableHeaderView behind of the Navigation Bar
I have used following line of code for adding a search bar as a tableHeaderView:

```<code>self.tableView.tableHeaderView = self.searchController.searchBar
</code>```

But my problem is hiding it like the iOS apps. On the iBooks app's search bar always behind of the Navigation Bar. I don't found any related documentations from the Apple's Documentations.

答:
To hide this bar from the start, you can use setContentOffset, as demonstrated in this answer:

```<code>self.tableView.setContentOffset(CGPoint(x: 0, y: 44), animated: false)
</code>```

This should hide the search bar from the start.

Body:
I have used following line of code for adding a search bar as a tableHeaderView:

self.tableView.tableHeaderView = self.searchController.searchBar

But my problem is hiding it like the iOS apps. On the iBooks app's search bar always behind of the Navigation Bar. I don't found any related documentations from the Apple's Documentations.

Body:
To hide this bar from the start, you can use setContentOffset, as demonstrated in this answer:

self.tableView.setContentOffset(CGPoint(x: 0, y: 44), animated: false)

This should hide the search bar from the start.


问:
How to close browser popup in robot framework?
After login in Chrome browser, I am getting a save password popup from the browser. I want to handle that popup and want to close that using Robot Framework
Browse popup window
Thanks</p>

答:
Three Ways To do do it.

1) Many a times, Once pop-up appear on screen and Disappear a cookie is set which you can view in developer console-> application. If you set this cookie with value using Add Cookie keyword. Pop- up wont appear.

2) if first doesn't work, then open developer tools and monitor the local store from developer tools -> application and close the pop-up. U will notice some variable with a value is stored in local storage. You can set that value using your script and u wont see the pop-up while executing variable.

3) If first and second doesn't work, the pop-up is most likely linked to a javascript variable. set java script variable using Execute Javascript Keyword and your problem must be solved.

Talk with your dev team, to see which way will work for you.


问:
panel background image only shows EVT_SET_CURSOR
I have been working fruitless in animation with wxpython.
Is it just that wxpython is not suitable for animation ?

I created a frame and then a panel in the frame.
The panel is for the animation canvas.
I draw the animation to the staticBitmap attribute of that panel.

Then on the panel, there are several buttons.
The canvas need frequent changes.

I have two issues here that I would appreciate any help.
First, the canvas panel is supposed to intercept EVT_LEFT_DOWN and EVT_LEFT_UP.

But the event handlers are never called.
I checked the event watcher of wxpython widget inspector.

It seems that every time I move the mouse, the only events are EVT_SET_CURSOR.

No EVT_LEFT_DOWN and EVT_LEFT_UP.

The following is my code to bind the events.

```<code>self.Bind(wx.EVT_LEFT_DOWN, self.canvas.canvasClickDown, id = self.GetId())
self.Bind(wx.EVT_LEFT_UP, self.canvas.canvasClickUp, id = self.GetId())
self.canvas.Bind(wx.EVT_LEFT_UP, self.canvas.canvasClickUp)
self.canvas.Bind(wx.EVT_LEFT_DOWN, self.canvas.canvasClickUp)
self.canvas.staticBitmap.Bind(wx.EVT_LEFT_UP, self.canvas.canvasClickUp)
self.canvas.staticBitmap.Bind(wx.EVT_LEFT_DOWN, self.canvas.canvasClickUp)
</code>```

I guess that I am in panic now since I tried to bind the events to the staticbitmap, the panel, and the frame all together.
But only I saw EVT_SET_CURSOR.

Can anyone help ?

Thanks

答:
Still the flickering problem is serious.
I changed to PyGame.</p>

Body:
I have been working fruitless in animation with wxpython.
Is it just that wxpython is not suitable for animation ?

I created a frame and then a panel in the frame.
The panel is for the animation canvas.
I draw the animation to the staticBitmap attribute of that panel.

Then on the panel, there are several buttons.
The canvas need frequent changes.

I have two issues here that I would appreciate any help.
First, the canvas panel is supposed to intercept EVT_LEFT_DOWN and EVT_LEFT_UP.

But the event handlers are never called.
I checked the event watcher of wxpython widget inspector.

It seems that every time I move the mouse, the only events are EVT_SET_CURSOR.

No EVT_LEFT_DOWN and EVT_LEFT_UP.

The following is my code to bind the events.

self.Bind(wx.EVT_LEFT_DOWN, self.canvas.canvasClickDown, id = self.GetId())
self.Bind(wx.EVT_LEFT_UP, self.canvas.canvasClickUp, id = self.GetId())
self.canvas.Bind(wx.EVT_LEFT_UP, self.canvas.canvasClickUp)
self.canvas.Bind(wx.EVT_LEFT_DOWN, self.canvas.canvasClickUp)
self.canvas.staticBitmap.Bind(wx.EVT_LEFT_UP, self.canvas.canvasClickUp)
self.canvas.staticBitmap.Bind(wx.EVT_LEFT_DOWN, self.canvas.canvasClickUp)

I guess that I am in panic now since I tried to bind the events to the staticbitmap, the panel, and the frame all together.
But only I saw EVT_SET_CURSOR.

Can anyone help ?

Thanks


问:
strange for loop? C#

Possible Duplicate:

  In C# is a for(;;) safe and what does it really do?

So i recently came across something ive never seen before..

```<code>        for (; ; )
        {

        }
</code>```

What is exactly happening when the feilds are left blank like that?

答:
It's an infinite loop.

Somewhere inside there should be a break; statement, or possibly an exception thrown in order for control to pass beyond the loop.

You could also achieve the same thing (probably more obviously) by doing

```<code>while (true)
{
    // do stuff
}
</code>```

Title: strange for loop? C#

Body:
Possible Duplicate:

  In C# is a for(;;) safe and what does it really do?

So i recently came across something ive never seen before..

        for (; ; )
        {

        }

What is exactly happening when the feilds are left blank like that?

Body:
It's an infinite loop.

Somewhere inside there should be a break; statement, or possibly an exception thrown in order for control to pass beyond the loop.

You could also achieve the same thing (probably more obviously) by doing

while (true)
{
    // do stuff
}


问:
how to edit Javascript in Html in Chrome Dev Tools
We can edit and execute JavaScript code from the *.js file in the Sources panel of Chrome DevTools. However, if the js code comes from the *.html file, how can we edit and execute them besides adding breakpoints?  </p>

答:
In Chrome Dev Tools you can setup a 'workspace' and when you make changes to a file it will save locally and also show changes in the browser.

Please follow this Google guide on setting it up. It's easy to follow and with screenshots, if you need further help then please message back.

Link with instructions: https://developers.google.com/web/tools/setup/setup-workflow

ContentLicense: CC BY-SA 4.0


问:
Qt auto generated form provides wrong path to source code files
I have added qcustomplot.h/.c files to my Qt project. They are located in: "QT_PROJECT_DIR/QCustomPlot/".

Every time I use the designer in Qt Creator and build I get this error in ui_mainwindow.h:

```<code>error: ../../qcustomplot.h: No such file or directory
#include "../../qcustomplot.h"
</code>```

This is of course true as it is located in: "QT_PROJECT_DIR/QCustomPlot/"

How do I change how Qt Designer auto generate this path?

If it helps, here is my .pro:

```<code>#-------------------------------------------------
#
# Project created by QtCreator 2014-01-12T00:44:44
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets widgets opengl printsupport

TARGET = Test
TEMPLATE = app

SOURCES += main.cpp\
        mainwindow.cpp \
    QCustomPlot/qcustomplot.cpp

HEADERS  += mainwindow.h \
    QCustomPlot/qcustomplot.h

FORMS    += mainwindow.ui

CONFIG += mobility
MOBILITY =
</code>```

答:
I met the same problem and have solved it.

It was caused by the path of qcustomplot object in xxx.ui.

Step 1: Open the ***.ui file which contains the qcustomplot item.

Step 2: Right click the qcustomplot item

Step 3: Double click the path of QCustomPlot, then change it to QCustomPlot/qcustomplot.cpp from ../../customplot.

Finally, the header of ui_***.h can auto include QCustomPlot/qcustomplot.cpp, instead of ../../qcustomplot.h.

My native language isn't English. If you find grammar mistake in my reply, please inform me. Let me correct it.

Body:
I have added qcustomplot.h/.c files to my Qt project. They are located in: "QT_PROJECT_DIR/QCustomPlot/".

Every time I use the designer in Qt Creator and build I get this error in ui_mainwindow.h:

error: ../../qcustomplot.h: No such file or directory
#include "../../qcustomplot.h"

This is of course true as it is located in: "QT_PROJECT_DIR/QCustomPlot/"

How do I change how Qt Designer auto generate this path?

If it helps, here is my .pro:

#-------------------------------------------------
#
# Project created by QtCreator 2014-01-12T00:44:44
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets widgets opengl printsupport

TARGET = Test
TEMPLATE = app

SOURCES += main.cpp\
        mainwindow.cpp \
    QCustomPlot/qcustomplot.cpp

HEADERS  += mainwindow.h \
    QCustomPlot/qcustomplot.h

FORMS    += mainwindow.ui

CONFIG += mobility
MOBILITY =


问:
Scikit: How do i display actual labels instead of 0 and 1's as indexes for confusion matrix
I have a confusion matrix but it has 0,1,2 as indexes/labels instead of actual labels. Is there any way to display the actual labels as index for confusion matrix in scikit?</p>

答:
If you are using inbuilt confusion-matrix function, then there is a parameter labels in it, in which you can pass the actual labels.

From the documentation:

labels : array, shape = [n_classes], optional List of labels to index
  the matrix. This may be used to reorder or select a subset of labels.
  If none is given, those that appear at least once in y_true or y_pred
  are used in sorted order.

And if you are talking about or want to plot the confusion matrix, then you can follow this official scikit example:

http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py


问:
Link to Apple Wallet or Android Pay from a MVC Web Application
I’m looking for a way to add Apple Wallet/Android Pay links with in a web application (https://www.somewebsite.com) where I can pass membership card parameters (card name, member name, card number).  Is this possible? I have found some examples within mobile apps but nothing from a browser to mobile app.</p>

答:
For Android you can integrate using Payment request API. It is supporting Chrome browser.

https://developers.google.com/web/fundamentals/discovery-and-monetization/payment-request/android-pay

https://developers.google.com/web/fundamentals/discovery-and-monetization/payment-request/