答:
We need to specify the sep.  Otherwise, it will automatically detect some of the other characters like _ and would separate the columns.

```<code>library(tidyr)
df %>%
  separate(united_sample_names, c("header1","header2","header3"), sep="[.]")
#      header1                         header2 header3
#1  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_86
#2  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_87
#3  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_88
#4  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_89
#5  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_90
#6  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_92
#7  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_93
#8  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_95
#9  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_97
#10 Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_99
</code>```

Title: How to separate string with "." as delimiter in a data frame using dplyr

Body:
I have the following data frame:

df <- structure(list(united_sample_names = structure(92:101, .Label = c("1-XX_iv.161202_NB501621_0042_AHV7NWBGXY.KK_208",
"1-XX_iv.161202_NB501621_0042_AHV7NWBGXY.KK_209", "1-XX_iv.161202_NB501621_0042_AHV7NWBGXY.KK_210",
"1-XX_iv.161202_NB501621_0042_AHV7NWBGXY.KK_211", "1-XX_iv.161202_NB501621_0042_AHV7NWBGXY.KK_212",
"1-XX_iv.161202_NB501621_0042_AHV7NWBGXY.KK_213", "1-XX_iv.161202_NB501621_0042_AHV7NWBGXY.KK_214",
"1-XX_iv.161202_NB501621_0042_AHV7NWBGXY.KK_215", "1-XX_iv.161202_NB501621_0042_AHV7NWBGXY.KK_216",
"1-XX_iv.161202_NB501621_0042_AHV7NWBGXY.KK_218", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_172",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_173", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_174",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_175", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_176",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_177", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_178",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_179", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_180",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_181", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_182",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_183", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_184",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_185", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_186",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_187", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_188",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_189", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_190",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_191", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_192",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_193", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_194",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_195", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_196",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_197", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_198",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_199", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_200",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_201", "1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_202",
"1-XX_iv.161205_NB501621_0043_AHVFM5BGXY.KK_203", "1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_359",
"1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_360", "1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_361",
"1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_362", "1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_363",
"1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_364", "1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_365",
"1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_366", "1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_367",
"1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_368", "1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_369",
"1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_370", "1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_371",
"1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_372", "1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_373",
"1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_374", "1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_375",
"1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_376", "1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_377",
"1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_378", "1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_379",
"1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_381", "1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_382",
"1-XX_iv.170125_NB501621_0067_AHW3MGBGXY.KK_383", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_100",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_101", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_102",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_103", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_104",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_106", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_107",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_109", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_110",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_111", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_112",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_113", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_114",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_115", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_116",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_117", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_118",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_119", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_120",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_122", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_124",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_125", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_126",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_127", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_128",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_86", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_87",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_88", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_89",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_90", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_92",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_93", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_95",
"Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_97", "Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_99"
), class = "factor")), .Names = "united_sample_names", row.names = c(NA,
10L), class = "data.frame")

df
#>                                 united_sample_names
#> 1  Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_86
#> 2  Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_87
#> 3  Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_88
#> 4  Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_89
#> 5  Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_90
#> 6  Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_92
#> 7  Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_93
#> 8  Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_95
#> 9  Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_97
#> 10 Vehicle_iv.170414_NB501621_0118_AHLTYHBGX2.KK_99

What I want to do is to split it into:

   header1    header2                         header3
   Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2 KK_86
   Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2 KK_87
   Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2 KK_88
   Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2 KK_89
   Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2 KK_90
   Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2 KK_92
   Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2 KK_93
   Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2 KK_95
   Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2 KK_97
   Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2 KK_99

I tried this and fail:

> df %>% separate(united_sample_names, c("header1","header2","header3"))
   header1 header2 header3
1  Vehicle      iv  170414
2  Vehicle      iv  170414
3  Vehicle      iv  170414
4  Vehicle      iv  170414
5  Vehicle      iv  170414
6  Vehicle      iv  170414
7  Vehicle      iv  170414
8  Vehicle      iv  170414
9  Vehicle      iv  170414
10 Vehicle      iv  170414
Warning message:
Too many values at 10 locations: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

What's the right way to do it?

Body:
We need to specify the sep.  Otherwise, it will automatically detect some of the other characters like _ and would separate the columns.

library(tidyr)
df %>%
  separate(united_sample_names, c("header1","header2","header3"), sep="[.]")
#      header1                         header2 header3
#1  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_86
#2  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_87
#3  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_88
#4  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_89
#5  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_90
#6  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_92
#7  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_93
#8  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_95
#9  Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_97
#10 Vehicle_iv 170414_NB501621_0118_AHLTYHBGX2   KK_99


来源: stackexchange

问:
How to run OpenAI Gym .render() over a server
I am running a python 2.7 script on a p2.xlarge AWS server through Jupyter (Ubuntu 14.04). I would like to be able to render my simulations.

Minimal working example

```<code>import gym
env = gym.make('CartPole-v0')
env.reset()
env.render()
</code>```

env.render() makes (among other things) the following errors:

```<code>...
HINT: make sure you have OpenGL install. On Ubuntu, you can run
'apt-get install python-opengl'. If you're running on a server,
you may need a virtual frame buffer; something like this should work:
'xvfb-run -s \"-screen 0 1400x900x24\" python <your_script.py>'")
...
NoSuchDisplayException: Cannot connect to "None"
</code>```

I would like to some how be able to see the simulations. It would be ideal if I could get it inline, but any display method would be nice.

Edit: This is only an issue with some environments, like classic control.

Update I

Inspired by this I tried the following, instead of the xvfb-run -s \"-screen 0 1400x900x24\" python <your_script.py> (which I couldn't get to work).

```<code>xvfb-run -a jupyter notebook
</code>```

Running the original script I now get instead

```<code>GLXInfoException: pyglet requires an X server with GLX
</code>```

Update II

Issue #154 seems relevant. I tried disabling the pop-up, and directly creating the RGB colors

```<code>import gym
env = gym.make('CartPole-v0')
env.reset()

img = env.render(mode='rgb_array', close=True)
print(type(img)) # <--- <type 'NoneType'>

img = env.render(mode='rgb_array', close=False) # <--- ERROR
print(type(img))
</code>```

I get ImportError: cannot import name gl_info.

Update III

With inspiration from @Torxed I tried creating a video file, and then rendering it (a fully satisfying solution).

Using the code from 'Recording and uploading results'

```<code>import gym

env = gym.make('CartPole-v0')
env.monitor.start('/tmp/cartpole-experiment-1', force=True)
observation = env.reset()
for t in range(100):
#    env.render()
    print(observation)
    action = env.action_space.sample()
    observation, reward, done, info = env.step(action)
    if done:
        print("Episode finished after {} timesteps".format(t+1))
        break

env.monitor.close()
</code>```

I tried following your suggestions, but got ImportError: cannot import name gl_info from when running env.monitor.start(....

From my understanding the problem is that OpenAI uses pyglet, and pyglet 'needs' a screen in order to compute the RGB colors of the image that is to be rendered. It is therefore necessary to trick python to think that there is a monitor connected

Update IV

FYI there are solutions online using bumblebee that seem to work. This should work if you have control over the server, but since AWS run in a VM I don't think you can use this.

Update V

Just if you have this problem, and don't know what to do (like me) the state of most environments are simple enough that you can create your own rendering mechanism. Not very satisfying, but.. you know.

答:
This GitHub issue gave an answer that worked great for me. It's nice because it doesn't require any additional dependencies (I assume you already have matplotlib) or configuration of the server.

Just run, e.g.:

```<code>import gym
import matplotlib.pyplot as plt
%matplotlib inline

env = gym.make('Breakout-v0') # insert your favorite environment
render = lambda : plt.imshow(env.render(mode='rgb_array'))
env.reset()
render()
</code>```

Using mode='rgb_array' gives you back a numpy.ndarray with the RGB values for each position, and matplotlib's imshow (or other methods) displays these nicely.

Note that if you're rendering multiple times in the same cell, this solution will plot a separate image each time. This is probably not what you want. I'll try to update this if I figure out a good workaround for that.

Update to render multiple times in one cell

Based on this StackOverflow answer, here's a working snippet (note that there may be more efficient ways to do this with an interactive plot; this way seems a little laggy on my machine):

```<code>import gym
from IPython import display
import matplotlib.pyplot as plt
%matplotlib inline

env = gym.make('Breakout-v0')
env.reset()
for _ in range(100):
    plt.imshow(env.render(mode='rgb_array'))
    display.display(plt.gcf())
    display.clear_output(wait=True)
    action = env.action_space.sample()
    env.step(action)
</code>```

Update to increase efficiency

On my machine, this was about 3x faster. The difference is that instead of calling imshow each time we render, we just change the RGB data on the original plot.

```<code>import gym
from IPython import display
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline

env = gym.make('Breakout-v0')
env.reset()
img = plt.imshow(env.render(mode='rgb_array')) # only call this once
for _ in range(100):
    img.set_data(env.render(mode='rgb_array')) # just update the data
    display.display(plt.gcf())
    display.clear_output(wait=True)
    action = env.action_space.sample()
    env.step(action)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am running a python 2.7 script on a p2.xlarge AWS server through Jupyter (Ubuntu 14.04). I would like to be able to render my simulations.

Minimal working example

import gym
env = gym.make('CartPole-v0')
env.reset()
env.render()

env.render() makes (among other things) the following errors:

...
HINT: make sure you have OpenGL install. On Ubuntu, you can run
'apt-get install python-opengl'. If you're running on a server,
you may need a virtual frame buffer; something like this should work:
'xvfb-run -s \"-screen 0 1400x900x24\" python <your_script.py>'")
...
NoSuchDisplayException: Cannot connect to "None"

I would like to some how be able to see the simulations. It would be ideal if I could get it inline, but any display method would be nice.

Edit: This is only an issue with some environments, like classic control.

Update I

Inspired by this I tried the following, instead of the xvfb-run -s \"-screen 0 1400x900x24\" python <your_script.py> (which I couldn't get to work).

xvfb-run -a jupyter notebook

Running the original script I now get instead

GLXInfoException: pyglet requires an X server with GLX

Update II

Issue #154 seems relevant. I tried disabling the pop-up, and directly creating the RGB colors

import gym
env = gym.make('CartPole-v0')
env.reset()

img = env.render(mode='rgb_array', close=True)
print(type(img)) # <--- <type 'NoneType'>

img = env.render(mode='rgb_array', close=False) # <--- ERROR
print(type(img))

I get ImportError: cannot import name gl_info.

Update III

With inspiration from @Torxed I tried creating a video file, and then rendering it (a fully satisfying solution).

Using the code from 'Recording and uploading results'

import gym

env = gym.make('CartPole-v0')
env.monitor.start('/tmp/cartpole-experiment-1', force=True)
observation = env.reset()
for t in range(100):
#    env.render()
    print(observation)
    action = env.action_space.sample()
    observation, reward, done, info = env.step(action)
    if done:
        print("Episode finished after {} timesteps".format(t+1))
        break

env.monitor.close()

I tried following your suggestions, but got ImportError: cannot import name gl_info from when running env.monitor.start(....

From my understanding the problem is that OpenAI uses pyglet, and pyglet 'needs' a screen in order to compute the RGB colors of the image that is to be rendered. It is therefore necessary to trick python to think that there is a monitor connected

Update IV

FYI there are solutions online using bumblebee that seem to work. This should work if you have control over the server, but since AWS run in a VM I don't think you can use this.

Update V

Just if you have this problem, and don't know what to do (like me) the state of most environments are simple enough that you can create your own rendering mechanism. Not very satisfying, but.. you know.

Body:
This GitHub issue gave an answer that worked great for me. It's nice because it doesn't require any additional dependencies (I assume you already have matplotlib) or configuration of the server.

Just run, e.g.:

import gym
import matplotlib.pyplot as plt
%matplotlib inline

env = gym.make('Breakout-v0') # insert your favorite environment
render = lambda : plt.imshow(env.render(mode='rgb_array'))
env.reset()
render()

Using mode='rgb_array' gives you back a numpy.ndarray with the RGB values for each position, and matplotlib's imshow (or other methods) displays these nicely.

Note that if you're rendering multiple times in the same cell, this solution will plot a separate image each time. This is probably not what you want. I'll try to update this if I figure out a good workaround for that.

Update to render multiple times in one cell

Based on this StackOverflow answer, here's a working snippet (note that there may be more efficient ways to do this with an interactive plot; this way seems a little laggy on my machine):

import gym
from IPython import display
import matplotlib.pyplot as plt
%matplotlib inline

env = gym.make('Breakout-v0')
env.reset()
for _ in range(100):
    plt.imshow(env.render(mode='rgb_array'))
    display.display(plt.gcf())
    display.clear_output(wait=True)
    action = env.action_space.sample()
    env.step(action)

Update to increase efficiency

On my machine, this was about 3x faster. The difference is that instead of calling imshow each time we render, we just change the RGB data on the original plot.

import gym
from IPython import display
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline

env = gym.make('Breakout-v0')
env.reset()
img = plt.imshow(env.render(mode='rgb_array')) # only call this once
for _ in range(100):
    img.set_data(env.render(mode='rgb_array')) # just update the data
    display.display(plt.gcf())
    display.clear_output(wait=True)
    action = env.action_space.sample()
    env.step(action)


问:
jQuery Clone Then InsertAfter Cloning Numerous Times
I'm trying to create a dynamic form to demonstrate to a business partner.

The goal is to be able to add select elements as necessary when the button is clicked. However, when it's clicked it duplicates the template twice, not just once.

Here are just a few of the variations of the code I've tried and here is the JSFiddle:

```<code>$("#serviceTemplate").eq(0).clone().insertAfter(".serviceField:last");

$("#serviceTemplate").clone().insertAfter(".serviceField:last");

$("#serviceTemplate").eq(0).clone().insertAfter($(".serviceField").last());
</code>```

答:
The idea is simple since you are using $('select').material_select(); to initiate all select element (therefore it is unique and clone it might have some unexpected issue).

Solution:

When you click ADD call $('select').material_select('destroy'); to destroy and get the original element

now you can clone it and append

initiate all select use $('select').material_select();

(Note: since the clone will also copy the id="serviceTemplate" it is a bad practice since id should be unique. Remove the id and use something like $(".serviceField").first() to target the original element.)

$(document).ready(function() {
  $('select').material_select();
});

$("#addBtn").click(function() {
  $('select').material_select('destroy');
  $(".serviceField").last().after($(".serviceField").first().clone());
  $('select').material_select();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -ms-box-sizing: border-box;
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  min-width: 100%;
  width: 100%;
  max-width: 100%;
  min-height: 100%;
  height: 100%;
  max-height: 100%;
}

form {
  padding: 2rem 0;
}

nav li a {
  padding: 0 .65rem;
}

nav,
#search {
  background: #eee !important;
}

.brand-logo h4 {
  color: #444;
}

.brand-logo:before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 99;
}

#table {
  display: none;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css" rel="stylesheet" />

    <form name="demo" id="demo" class="row">

          <input type="text" class="validate" placeholder="Your name..." />
          Full Name

          <input type="text" class="validate" placeholder="mm/dd/yyyy" required/>

          Desired Appointment Date

          <select class="service" required>
       <option value="" disabled selected>-Please Select Service-</option>
       <option value="1" data-cost="90">Virus Removal - $90</option>
       <option value="2" data-cost="20">PC Tune-Up - $20</option>
     </select>

          Service Required

Add Another Service

    </form>

```

Body:
I'm trying to create a dynamic form to demonstrate to a business partner.

The goal is to be able to add select elements as necessary when the button is clicked. However, when it's clicked it duplicates the template twice, not just once.

Here are just a few of the variations of the code I've tried and here is the JSFiddle:

$("#serviceTemplate").eq(0).clone().insertAfter(".serviceField:last");

$("#serviceTemplate").clone().insertAfter(".serviceField:last");

$("#serviceTemplate").eq(0).clone().insertAfter($(".serviceField").last());

Body:
The idea is simple since you are using $('select').material_select(); to initiate all select element (therefore it is unique and clone it might have some unexpected issue).

Solution:

When you click ADD call $('select').material_select('destroy'); to destroy and get the original element

now you can clone it and append

initiate all select use $('select').material_select();

(Note: since the clone will also copy the id="serviceTemplate" it is a bad practice since id should be unique. Remove the id and use something like $(".serviceField").first() to target the original element.)

$(document).ready(function() {
  $('select').material_select();
});

$("#addBtn").click(function() {
  $('select').material_select('destroy');
  $(".serviceField").last().after($(".serviceField").first().clone());
  $('select').material_select();
});

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -ms-box-sizing: border-box;
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  min-width: 100%;
  width: 100%;
  max-width: 100%;
  min-height: 100%;
  height: 100%;
  max-height: 100%;
}

form {
  padding: 2rem 0;
}

nav li a {
  padding: 0 .65rem;
}

nav,
#search {
  background: #eee !important;
}

.brand-logo h4 {
  color: #444;
}

.brand-logo:before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 99;
}

#table {
  display: none;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/js/materialize.min.js"></script>

<div class="container">
  <div class="row">
    <form name="demo" id="demo" class="row">
      <div class="row">
        <div class="input-field col s12 m4">
          <input type="text" class="validate" placeholder="Your name..." />
          <label for="name">Full Name</label>
        </div>

        <div class="input-field col s12 m4">
          <input type="text" class="validate" placeholder="mm/dd/yyyy" required/>

          <label>Desired Appointment Date</label>
        </div>
      </div>

      <div class="row serviceField">
        <div class="input-field col s12 m3">

          <select class="service" required>
       <option value="" disabled selected>-Please Select Service-</option>
       <option value="1" data-cost="90">Virus Removal - $90</option>
       <option value="2" data-cost="20">PC Tune-Up - $20</option>
     </select>

          <label>Service Required</label>
        </div>
      </div>

      <div class="row">
        <div class="input-field col s12 m3">
          <div id="addBtn" class="btn black white-text">Add Another Service</div>
        </div>
      </div>
    </form>
  </div>
</div>


问:
How to insert element as nth record using XSLT
Consider following input:

```<code><SettleList>
<SettleObject>
  <ExternalVar>5</ExternalVar>
 </SettleObject>
 <SettleObject>
  <ExternalVar>10</ExternalVar>
</SettleObject>
</SettleList>
</code>```

Now the requirement: All the records except 5th and 10th need to be zeroes while  the 5th and 10th will contain values.
The prob is using apply-templates no parameters can be sent as for the second object and hence the index again starts from 1 instead of 6th record.

I am trying this using XSLT

答:
Keep it simple.

Input:

```<code><SettleList xmlns="http://xmlns.oracle.com/TestApp/TestAppComposite/BPELProcess1">
   <SettleObject>
      <ExternalVar>1</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>2</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>3</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>4</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>5</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>6</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>7</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>8</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>9</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>10</ExternalVar>
   </SettleObject>
</SettleList>
</code>```

XSL:

```<code><xsl:template match="/">
    <ns0:SettleList>
        <xsl:for-each select="/ns0:SettleList/ns0:SettleObject">
        <xsl:variable name="pos" select="position()"/>
           <xsl:choose>
           <xsl:when test="$pos = 5 or $pos = 10">
           <ns0:SettleObject>
              <ns0:ExternalVar>
                 <xsl:value-of select="ns0:ExternalVar"/>
              </ns0:ExternalVar>
           </ns0:SettleObject>
           </xsl:when>
           <xsl:otherwise>
           <ns0:SettleObject>
              <ns0:ExternalVar>
                 <xsl:text disable-output-escaping="no">0</xsl:text>
              </ns0:ExternalVar>
           </ns0:SettleObject>
           </xsl:otherwise>
           </xsl:choose>
        </xsl:for-each>
    </ns0:SettleList>
</xsl:template>
</code>```

Output:

```<code><?xml version = '1.0' encoding = 'UTF-8'?>
<ns0:SettleList xmlns:plnk="http://docs.oasis-open.org/wsbpel/2.0/plnktype" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:ns0="http://xmlns.oracle.com/TestApp/TestAppComposite/BPELProcess1">
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>5</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>10</ns0:ExternalVar>
   </ns0:SettleObject>
</ns0:SettleList>
</code>```

Body:
Consider following input:

<SettleList>
<SettleObject>
  <ExternalVar>5</ExternalVar>
 </SettleObject>
 <SettleObject>
  <ExternalVar>10</ExternalVar>
</SettleObject>
</SettleList>

Now the requirement: All the records except 5th and 10th need to be zeroes while  the 5th and 10th will contain values.
The prob is using apply-templates no parameters can be sent as for the second object and hence the index again starts from 1 instead of 6th record.

I am trying this using XSLT

Body:
Keep it simple.

Input:

<SettleList xmlns="http://xmlns.oracle.com/TestApp/TestAppComposite/BPELProcess1">
   <SettleObject>
      <ExternalVar>1</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>2</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>3</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>4</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>5</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>6</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>7</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>8</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>9</ExternalVar>
   </SettleObject>
   <SettleObject>
      <ExternalVar>10</ExternalVar>
   </SettleObject>
</SettleList>

XSL:

<xsl:template match="/">
    <ns0:SettleList>
        <xsl:for-each select="/ns0:SettleList/ns0:SettleObject">
        <xsl:variable name="pos" select="position()"/>
           <xsl:choose>
           <xsl:when test="$pos = 5 or $pos = 10">
           <ns0:SettleObject>
              <ns0:ExternalVar>
                 <xsl:value-of select="ns0:ExternalVar"/>
              </ns0:ExternalVar>
           </ns0:SettleObject>
           </xsl:when>
           <xsl:otherwise>
           <ns0:SettleObject>
              <ns0:ExternalVar>
                 <xsl:text disable-output-escaping="no">0</xsl:text>
              </ns0:ExternalVar>
           </ns0:SettleObject>
           </xsl:otherwise>
           </xsl:choose>
        </xsl:for-each>
    </ns0:SettleList>
</xsl:template>

Output:

<?xml version = '1.0' encoding = 'UTF-8'?>
<ns0:SettleList xmlns:plnk="http://docs.oasis-open.org/wsbpel/2.0/plnktype" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:ns0="http://xmlns.oracle.com/TestApp/TestAppComposite/BPELProcess1">
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>5</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>0</ns0:ExternalVar>
   </ns0:SettleObject>
   <ns0:SettleObject>
      <ns0:ExternalVar>10</ns0:ExternalVar>
   </ns0:SettleObject>
</ns0:SettleList>


问:
Is System.Threading.Semaphore weak?
There are two types of Semaphore

Strong Semaphore: maintains an order internally.

Weak semaphore: which does not provide any ordered access to a critical section which can cause starvation.

“There is no guaranteed order, such as FIFO or LIFO, in which blocked threads enter the semaphore.” from MSDN remarks in System.Threading.Semaphore.

I would like to confirm what type of semaphore implementation is provided by .Net Framework ?

答:
```<code>    static int count = 0;
    static Semaphore writerSem = new Semaphore(0, 10);

    static void Main(string[] args)
    {
        Thread[] readers = new Thread[10];
        for (int i = 0; i < readers.Length; i++)
        {
            readers[i] = new Thread(new ThreadStart(Reader));
            readers[i].Name = "Reader: " + i;
            readers[i].Start();
        }
        Thread writer = new Thread(new ThreadStart(Writer));

        writer.Start();

        for (int i = 0; i < readers.Length; i++)
        {
            readers[i].Join();
        }
        writer.Join();

    }
    static void Reader()
    {
        while (true)
        {
            writerSem.WaitOne();
            Console.WriteLine(count + " " + Thread.CurrentThread.Name);
        }
    }
    static void Writer()
    {
        while (true)
        {
            count++;
            writerSem.Release(10);
            Thread.Sleep(1000);
        }
    }
</code>```

I have tested it by writing this program. It is just confirmed that System.Threading.Semaphore is implemented as Weak Semaphore.

Title: Is System.Threading.Semaphore weak?

Body:
    static int count = 0;
    static Semaphore writerSem = new Semaphore(0, 10);

    static void Main(string[] args)
    {
        Thread[] readers = new Thread[10];
        for (int i = 0; i < readers.Length; i++)
        {
            readers[i] = new Thread(new ThreadStart(Reader));
            readers[i].Name = "Reader: " + i;
            readers[i].Start();
        }
        Thread writer = new Thread(new ThreadStart(Writer));

        writer.Start();

        for (int i = 0; i < readers.Length; i++)
        {
            readers[i].Join();
        }
        writer.Join();

    }
    static void Reader()
    {
        while (true)
        {
            writerSem.WaitOne();
            Console.WriteLine(count + " " + Thread.CurrentThread.Name);
        }
    }
    static void Writer()
    {
        while (true)
        {
            count++;
            writerSem.Release(10);
            Thread.Sleep(1000);
        }
    }

I have tested it by writing this program. It is just confirmed that System.Threading.Semaphore is implemented as Weak Semaphore.


问:
Bootstrap Grid Mixin Overriding Previous Declarations
I'm using Bootstrap 3.3.7s Less mixins for their grid system, found here.

My basic concept is to increase gutter size as my screen size increases. Here is an example of my html:

```<code><div class="container">
  <div class="row-intro">
    <div class="col-intro-content">
      <p>Sugar grounds half and half, percolator that, crema ut cup dark ristretto lungo. Carajillo bar steamed, milk spoon to go, wings qui caramelization beans that.</p>
    </div>
  </div>
</div>
</code>```

And less:

```<code>.row-intro {
  .make-row(40px);
    .col-intro-content {
      .make-xs-column(12, 40px);
      .make-md-column(10, 60px);
      .make-md-column-offset(1);
    }
}
</code>```

Now what happens is that even on the xs screen sizes, I have a gutter size of 60px, regardless of declaring it 40px earlier. Any idea as to why this is getting overridden? I've tried it without the offset and the issue remains. I've tried different gutter widths and the same relative issue still exists.

答:
That is because you are missing

```<code> .col-xs-@{index}, .col-sm-@{index}, .col-md-@{index}, .col-lg-@{index}";
</code>```

you need the .make-sm as well

info

Body:
I'm using Bootstrap 3.3.7s Less mixins for their grid system, found here.

My basic concept is to increase gutter size as my screen size increases. Here is an example of my html:

Sugar grounds half and half, percolator that, crema ut cup dark ristretto lungo. Carajillo bar steamed, milk spoon to go, wings qui caramelization beans that.

And less:

.row-intro {
  .make-row(40px);
    .col-intro-content {
      .make-xs-column(12, 40px);
      .make-md-column(10, 60px);
      .make-md-column-offset(1);
    }
}

Now what happens is that even on the xs screen sizes, I have a gutter size of 60px, regardless of declaring it 40px earlier. Any idea as to why this is getting overridden? I've tried it without the offset and the issue remains. I've tried different gutter widths and the same relative issue still exists.

Body:
That is because you are missing

 .col-xs-@{index}, .col-sm-@{index}, .col-md-@{index}, .col-lg-@{index}";

you need the .make-sm as well

info


问:
Buidlbot Tutorial: URL for runtests under Waterfall view doesn't show?
Doing this tutorial, the URL for runtests in the Waterfall view does not appear. The worker is connected (confirmed by logs of both master and worker). Why doesn't runtests show under the Waterfall view?

I've tried the 2 ways that was shown in the tutorial in python's buildbot. (The first way is via the virtualenv and the second way is via the docker.) The link for the this is found here.

Both are supposed to show a URL (the tilted blue text) in waterfall view as seen in this image:

But both ways I tried only show a blank white screen. I ran the virtualenv way in both Linux Mint Serena and Ubuntu 16.04. I ran the docker way only in Ubuntu 16.04.

答:
go to Menu Builds -> Builders, click runtests and then you can see a "force" button on the top right hand corner. Click that button (before that make sure your worker is attached) and then you can see runtests in the waterfall view.
https://i.stack.imgur.com/s7OXr.png</p>

ContentLicense: CC BY-SA 4.0


问:
How to create number list 1 until 9 and plus 1 at another row in php?
How to create number list in php 1 until 9 with this out put

1 2 3 4 5 6 7 8 9

2 3 4 5 6 7 8 9 1

3 4 5 6 7 8 9 1 2

4 5 6 7 8 9 1 2 3

5 6 7 8 9 1 2 3 4

6 7 8 9 1 2 3 4 5

7 8 9 1 2 3 4 5 6

8 9 1 2 3 4 5 6 7

9 1 2 3 4 5 6 7 8

Please Let me know ...

Body:
Sorry....I like being fancy:

$array = [1,2,3,4,5,6,7,8,9];

for($i = 0; $i < count($array); $i++) {
    foreach($array as &$item)
        echo ($item >= 10 ? $item++ - 9 : $item++), ' ';
    echo '<br>';
}

or

$array = [1,2,3,4,5,6,7,8,9];

do {
    echo implode(' ', $array), '<br>';
} while(($array[] = $array[0]) && array_shift($array) && $array[0] != 1);


问:
Saving an email as an html file using Python
The company I am doing some contract development work for saves emails as .htm files so that they open correctly in their Intranet (.msg files don't open correctly). I am working on automating a set of tasks that include saving the emails. What is the best way to save an email as an html file in Python?</p>

答:
Can you give some code so we know what variables/methods you have for obtaining the email in the first place? I.e., do you have different fields ('from', 'to', 'subject', 'date'...) in different variables already?

Here's a template for writing a plain HTML file:

```<code>f=open('saved_email_1.htm','wb')
f.write ('<!doctype html>')
f.write ('<html><head><title>Email Subject</title>')
f.write ('</head><body>')
f.write ('<h1>Email Subject</h1>')
f.write ('<p><b>From: EMAIL@EMAIL.COM</b></p>')
f.write ('<p><b>To: EMAIL@EMAIL.COM</b></p>')
f.write ('<p><b>Date: DATE</b></p>')
f.write ('<p><b>Subject: DATE</b></p>')
f.write ('<p style="border-bottom:1px solid black"><b>Contents:</b></p>')
f.write (varEmailContents)
f.write ('</body></html>')
f.close
</code>```

All you need now is some CSS, some email-data-in-variables, and to remember to .HTMLescape() the variables before writing them to file (else lots of characters will mess with the HTML).

In Python3, there's a html module to do the escaping/encoding of special chars. So, it'd look like:

```<code>import html
... ... ...
f.write ('<p><b>Date: '    + varEmailDate                   + '</b></p>')
f.write ('<p><b>Subject: ' + html.escape(varEmailSubject)   + '</b></p>')
f.write ('<p style="border-bottom:1px solid black"><b>Contents:</b></p>')
f.write (html.escape(varEmailContents))
f.write ('</body></html>')
f.close
</code>```

Body:
Can you give some code so we know what variables/methods you have for obtaining the email in the first place? I.e., do you have different fields ('from', 'to', 'subject', 'date'...) in different variables already?

Here's a template for writing a plain HTML file:

f=open('saved_email_1.htm','wb')
f.write ('<!doctype html>')
f.write ('<html><head><title>Email Subject</title>')
f.write ('</head><body>')
f.write ('<h1>Email Subject</h1>')
f.write ('<p><b>From: EMAIL@EMAIL.COM</b></p>')
f.write ('<p><b>To: EMAIL@EMAIL.COM</b></p>')
f.write ('<p><b>Date: DATE</b></p>')
f.write ('<p><b>Subject: DATE</b></p>')
f.write ('<p style="border-bottom:1px solid black"><b>Contents:</b></p>')
f.write (varEmailContents)
f.write ('</body></html>')
f.close

All you need now is some CSS, some email-data-in-variables, and to remember to .HTMLescape() the variables before writing them to file (else lots of characters will mess with the HTML).

In Python3, there's a html module to do the escaping/encoding of special chars. So, it'd look like:

import html
... ... ...
f.write ('<p><b>Date: '    + varEmailDate                   + '</b></p>')
f.write ('<p><b>Subject: ' + html.escape(varEmailSubject)   + '</b></p>')
f.write ('<p style="border-bottom:1px solid black"><b>Contents:</b></p>')
f.write (html.escape(varEmailContents))
f.write ('</body></html>')
f.close


问:
TeamCity deployment in Tomcat
How to create autodeployment in Tomcat with TeamCity. I used container deployer but it always says me filed to deploy. </p>

<pre class="lang-none prettyprint-override"><code>    [Step 6/8] org.codehaus.cargo.container.ContainerException: Failed to deploy [/home/aecktann/JetBrains/TeamCity/buildAgent/work/f8bcef79481c6bb2/target/ChatBot-1.0-SNAPSHOT.war]
, root cause is org.codehaus.cargo.container.*******.internal.TomcatManagerException: The Tomcat Manager responded "FAIL - Deployed application at context path /ChatBot-1.0-SNAPSHOT but context failed to start
" instead of the expected "OK" message
[16:41:40]  [Step 6/8] Step TomcatDeployer (Container Deployer) failed
</code>```

答: it doesn't look like the deploy failed, so not jenkins, it might be the actual app not starting, have you done a manual deploy with the same jenkins user? might be a permission issue also. </p>

Title: TeamCity deployment in Tomcat

Body:
How to create autodeployment in Tomcat with TeamCity. I used container deployer but it always says me filed to deploy.

    [Step 6/8] org.codehaus.cargo.container.ContainerException: Failed to deploy [/home/aecktann/JetBrains/TeamCity/buildAgent/work/f8bcef79481c6bb2/target/ChatBot-1.0-SNAPSHOT.war]
, root cause is org.codehaus.cargo.container.*******.internal.TomcatManagerException: The Tomcat Manager responded "FAIL - Deployed application at context path /ChatBot-1.0-SNAPSHOT but context failed to start
" instead of the expected "OK" message
[16:41:40]  [Step 6/8] Step TomcatDeployer (Container Deployer) failed


问:
Concatenating 2 bytes in Java efficiently
I am working on a program where I am trying to reduce the amount of memory allocated, I previously use to concatenate strings but the problem was that I do this process several million times and the more I did it the longer it took to allocate these strings. Instead now I am trying work with bytes. I want to do something like this:

```<code>byte[] arr = new byte[5];
byte cat = arr[0] + arr[1]  //this addition would give me an error obviously. It's for demostration purposes

System.out.println(cat);
</code>```

I just want to take the first byte and put the second one right after it without using any form of String Class as it requires more overhead to concatenate strings as such. Is there a way I can do this with minimal operations?

答:
If you want to "concatenate" two or more bytes, into a new byte array, just use the array initializer syntax:

```<code>byte a = 1;
byte b = 42;
byte c = 99;

byte[] cat = {a,b,c};

System.out.println(Arrays.toString(cat)); // prints: [1, 42, 99]
</code>```

Your example is however more akin to a substring() call, and for that you should use Arrays.copyOfRange(), e.g.

```<code>byte[] arr = {5,4,3,2,1};

byte[] cat = Arrays.copyOfRange(arr, 0, 2);

System.out.println(Arrays.toString(cat)); // prints: [5, 4]
</code>```

Body:
I am working on a program where I am trying to reduce the amount of memory allocated, I previously use to concatenate strings but the problem was that I do this process several million times and the more I did it the longer it took to allocate these strings. Instead now I am trying work with bytes. I want to do something like this:

byte[] arr = new byte[5];
byte cat = arr[0] + arr[1]  //this addition would give me an error obviously. It's for demostration purposes

System.out.println(cat);

I just want to take the first byte and put the second one right after it without using any form of String Class as it requires more overhead to concatenate strings as such. Is there a way I can do this with minimal operations?

Body:
If you want to "concatenate" two or more bytes, into a new byte array, just use the array initializer syntax:

byte a = 1;
byte b = 42;
byte c = 99;

byte[] cat = {a,b,c};

System.out.println(Arrays.toString(cat)); // prints: [1, 42, 99]

Your example is however more akin to a substring() call, and for that you should use Arrays.copyOfRange(), e.g.

byte[] arr = {5,4,3,2,1};

byte[] cat = Arrays.copyOfRange(arr, 0, 2);

System.out.println(Arrays.toString(cat)); // prints: [5, 4]


问:
Command to copy a line from text and create a new text file
Please suggest me a command that will copy a line from all the text files and create one file with all the lines in it.

I am on a Linux machine where a particular directory has around 11000 files in it and each file has 3 or 4 lines of data.

What I wanted to do is to combine all data into one file which I can refer.... let's say 11000*3 = 3000 lines. I want to copy all 3000 lines in one single file line by line.

These are the few txt files and directories and even the directories has a list of txt files

```<code>Jan 2007 abc.txt
Jan 2007 siele.txt
Jan 2007 regel.txt
Jan 2007 sne.txt
Jan 2007 marshwlo.txt
Jan 2007 ziplist.txt
Jan 2007 listider.txt
Jan 2007 kindle.txt
Jan 2007 list.txt
Jan 2007 Codelevel
Jan 2007 Ziplevel
</code>```

答:
This?</p>

```<code>cat *.txt > newfile.txt
</code>```

Body:
Please suggest me a command that will copy a line from all the text files and create one file with all the lines in it.

I am on a Linux machine where a particular directory has around 11000 files in it and each file has 3 or 4 lines of data.

What I wanted to do is to combine all data into one file which I can refer.... let's say 11000*3 = 3000 lines. I want to copy all 3000 lines in one single file line by line.

These are the few txt files and directories and even the directories has a list of txt files

Jan 2007 abc.txt
Jan 2007 siele.txt
Jan 2007 regel.txt
Jan 2007 sne.txt
Jan 2007 marshwlo.txt
Jan 2007 ziplist.txt
Jan 2007 listider.txt
Jan 2007 kindle.txt
Jan 2007 list.txt
Jan 2007 Codelevel
Jan 2007 Ziplevel

Body:
This?

cat *.txt > newfile.txt


问:
"this" pointer in C (not C++)
I'm trying to create a stack in C for fun, and came up with the idea of using struct to represent the stack. Then I add function pointers to the struct for push() and pop() operations.

So far all is good it seems, but, for the implementation of the push() and pop() functions I need to refer to *this somehow. How can that (can it?) be done?

This is my struct

```<code>struct Stack {
    int *data;
    int current_size;
    int max_size;
    int (*push)(int);
    int (*pop)();
};
</code>```

And as an example here's push

```<code>int push(int val) {
    if(current_size == max_size -1)
            return 0;

    data[current_size] = val;
    current_size++;

    return 1;
}
</code>```

As you can imagine, the compiler has no idea what current_size is, as it would expect something like stack->current_size.

Is this possible to overcome somehow?

答:
Since your are going to have only one Stack structure (that you named stack, apparently), you could define it as a global variable. This would allow pop/push to refer to the stack variable directly.

You would do something like:

stack.current_size += 4;

or use the -> operator if you decide to declare stack as a memory pointer to Stack.

ContentLicense: CC BY-SA 2.5

Title: "this" pointer in C (not C++)

Body:
I'm trying to create a stack in C for fun, and came up with the idea of using struct to represent the stack. Then I add function pointers to the struct for push() and pop() operations.

So far all is good it seems, but, for the implementation of the push() and pop() functions I need to refer to *this somehow. How can that (can it?) be done?

This is my struct

struct Stack {
    int *data;
    int current_size;
    int max_size;
    int (*push)(int);
    int (*pop)();
};

And as an example here's push

int push(int val) {
    if(current_size == max_size -1)
            return 0;

    data[current_size] = val;
    current_size++;

    return 1;
}

As you can imagine, the compiler has no idea what current_size is, as it would expect something like stack->current_size.

Is this possible to overcome somehow?


问:
How can I do the opposite .include?
So the goal here is to print the index of the element if the element is in the array or print -1 if the element is not in the array. I have to do this using loops. PLEASE HELP!</p>

```<code>def element_index(element, my_array)
  while my_array.map.include? element do
    puts my_array.index(element)
    break
  end

  until my_array.include? element do
    puts -1
    break
  end
end

p element_index("c", ["a","b","c"])
</code>```

答:
This is an easy way but maybe it doesn't meet the criteria for "using loops":

```<code>def element_index(x, arr)
  arr.index(x) || -1
end

element_index("c", ["a","b","c"]) #=> 2
element_index("d", ["a","b","c"]) #=> -1
</code>```

To explicitly use a loop:

```<code>def element_index(x, arr)
  arr.each_index.find { |i| arr[i] == x } || -1
end
</code>```

As pointed out in the comments, we could instead write

```<code>arr.each_index.find(->{-1}) { |i| arr[i] == x }

element_index("c", ["a","b","c"]) #=>  2
element_index("d", ["a","b","c"]) #=> -1
</code>```

Title: How can I do the opposite .include?

Body:
So the goal here is to print the index of the element if the element is in the array or print -1 if the element is not in the array. I have to do this using loops. PLEASE HELP!

def element_index(element, my_array)
  while my_array.map.include? element do
    puts my_array.index(element)
    break
  end

  until my_array.include? element do
    puts -1
    break
  end
end

p element_index("c", ["a","b","c"])

Body:
This is an easy way but maybe it doesn't meet the criteria for "using loops":

def element_index(x, arr)
  arr.index(x) || -1
end

element_index("c", ["a","b","c"]) #=> 2
element_index("d", ["a","b","c"]) #=> -1

To explicitly use a loop:

def element_index(x, arr)
  arr.each_index.find { |i| arr[i] == x } || -1
end

As pointed out in the comments, we could instead write

arr.each_index.find(->{-1}) { |i| arr[i] == x }

element_index("c", ["a","b","c"]) #=>  2
element_index("d", ["a","b","c"]) #=> -1


问:
Missing Info.plist key

I need to internationalize those tips, but i got this!Any idea?

答:
I also face this type of error.
I think you can describe the message like this.

I think it's help for you.

You should use InfoPlist.strings file to localize values of Info.plist. To do this, go to File->New->File, choose Strings File under Resource tab of iOS, name it InfoPlist, and create. Open and insert the Info.plist values you want to localize like:

```<code>"NSLocationWhenInUseUsageDescription" = "Description of this";
</code>```

EDIT:

select the localization options, or enable localization if needed,

you should be able to see the file also on the left side editor.

Title: Missing Info.plist key

Body:
I also face this type of error.
I think you can describe the message like this.

I think it's help for you.

You should use InfoPlist.strings file to localize values of Info.plist. To do this, go to File->New->File, choose Strings File under Resource tab of iOS, name it InfoPlist, and create. Open and insert the Info.plist values you want to localize like:

"NSLocationWhenInUseUsageDescription" = "Description of this";

EDIT:

select the localization options, or enable localization if needed,

you should be able to see the file also on the left side editor.


问:
Login issue with gconnect() in gtrendsR package
I am trying to log into my Google account in R using gconnect() in the gtrendsR package, but am running into issues. I have been doing research using Google Trends data for the last month, and have never had a problem with this.

Please let me know if you have any thoughts. I had Google Support take a look at my account to see if there were any holds or something, but nothing showed up. Also tried logging in through another account which didnt work..

This is what I am trying to do:

```<code>usr <- 'my_username@gmail.com'
psw <- 'my_password'
gconnect(usr, psw)
</code>```

And then I am returned with the following error:

Google login failed! Check your login information.NULL

答: See this page: https://www.google.com/settings/security/lesssecureapps.  Try switching to "on" if the setting is "off".</p>

Body:
I am trying to log into my Google account in R using gconnect() in the gtrendsR package, but am running into issues. I have been doing research using Google Trends data for the last month, and have never had a problem with this.

Please let me know if you have any thoughts. I had Google Support take a look at my account to see if there were any holds or something, but nothing showed up. Also tried logging in through another account which didnt work..

This is what I am trying to do:

usr <- 'my_username@gmail.com'
psw <- 'my_password'
gconnect(usr, psw)

And then I am returned with the following error:

Google login failed! Check your login information.NULL


问:
Looking for WP 3.0 sample posts data
I'm looking for quality sample posts data for WP 3.0 and up (for theme development). Any suggestion ?</p>

答:
http://codex.wordpress.org/Theme_Unit_Test

This has more than the lipsum text; it should have everything you need to see if you've styled the theme entirely and appropriately.

Title: Looking for WP 3.0 sample posts data


问:
How to compare two colors for similarity/difference
I want to design a program that can help me assess between 5 pre-defined colors which one is more similar to a variable color, and with what percentage.  The thing is that I don't know how to do that manually step by step. So it is even more difficult to think of a program.

More details: The colors are from photographs of tubes with gel that as different colors. I have 5 tubes with different colors were each is representative of 1 of 5 levels. I want to take photographs of other samples and on the computer assess to which level that sample belongs by comparing colors, and I want to know that with a percentage of approximation too. I would like a program that does something like this: http://www.colortools.net/color_matcher.html

If you can tell me what steps to take, even if they are things for me to think and do manually. It would be very helpful.

答:
For quick and dirty, you can do

import java.awt.Color;
private Color dropPrecision(Color c,int threshold){
    return new Color((c.getRed()/threshold),
                     (c.getGreen()/threshold),
                     (c.getBlue()/threshold));
}
public boolean inThreshold(Color _1,Color _2,int threshold){
    return dropPrecision(_1,threshold)==dropPrecision(_2,threshold);
}
```

making use of integer division to quantize the colors.

Body:
For quick and dirty, you can do

import java.awt.Color;
private Color dropPrecision(Color c,int threshold){
    return new Color((c.getRed()/threshold),
                     (c.getGreen()/threshold),
                     (c.getBlue()/threshold));
}
public boolean inThreshold(Color _1,Color _2,int threshold){
    return dropPrecision(_1,threshold)==dropPrecision(_2,threshold);
}

making use of integer division to quantize the colors.


问:
I want to force a render, but only draw as fast as possible (InvalidateVisual / CompositionTarget.Rendering)
I'm working on a real-time WPF/Silverlight (and soon WP7) visualization component and I'm looking for the best solution to force a redraw of the entire component in a Game-loop style. Redraw should be on-demand, but I don't want to back up the message pump with re-draw calls. Most of the drawing in my component is done using non-WPF primitives (e.g. Bitmap Interop, Direct2D) so my code does not use InvalidateVisual, and as a result, currently looks like this

```<code>// Pseudocode, doesnt compile, just to convey the meaning
public void InvalidateElement()
{
    if (CurrentlyDrawing)
        return;

    Dispatcher.BeginInvoke(() =>
    {
        CurrentlyDrawing = true;

        DoDrawInternal();

        CurrentlyDrawing = false;
    }
}
</code>```

Ok so this is great. If I call InvalidateElement lots of times I get good responsiveness. However, what I want to do is ensure I can push data to my visualization component as fast as possible but only draw when the component is able to draw, and not keep drawing to catch up with the data once the input stream completes.

No I can't override OnRender, I'm using non-WPF drawing inside WPF ;-)

Basically what I want is something like the old Invalidate() / OnPaint in WindowsForms, or better yet, a game loop in DirectX.

At the moment I get the situation where if I have an external thread that pushes data to the visualization component at a high rate then if I Stop pushing data I get another 20 seconds worth of refreshes to get through before the component stops drawing. I want to stop drawing as soon as data has gone in.

Another idea I had was to handle CompositionTarget.Rendering in the visualization component then implement some sort of rudimentary Queue to push data to and the Rendering event consumes this data as fast as it can.

In Summary

Given a WPF visualization component, V, and a datasource which pushes it data every 1ms, D, how can I ensure that no matter the datarate of D, V draws data at 30FPS (or whatever it can do) and updates itself in chunks, sort of how a game render loop does in DirectX?

When the data stops, V should redraw everything it has up to now in one go. When the data is too fast, V draws larger chunks at a time to compensate.

If you need more information I'd be happy to share it. Right now I've just posted a synopsis to gauge if there are any quick fixes but a fuller Q with code examples can be provided on request.

Best regards,

答:
You can listen to the CompositionTarget.Rendering event, which is triggered right before WPF renders the UI, and do your drawing in there.

Another tidbit.. InvalidateVisuals() is nothing like Form.Invalidate(), as it also causes re-layout which is expensive. If you want something like Form.Invalidate(), then create a DrawingGroup (or bitmap image) "backingStore", place it in the DrawingContext during OnRender(), and then update it whenever you want. WPF will automatically update and repaint the UI.

Body:
I'm working on a real-time WPF/Silverlight (and soon WP7) visualization component and I'm looking for the best solution to force a redraw of the entire component in a Game-loop style. Redraw should be on-demand, but I don't want to back up the message pump with re-draw calls. Most of the drawing in my component is done using non-WPF primitives (e.g. Bitmap Interop, Direct2D) so my code does not use InvalidateVisual, and as a result, currently looks like this

// Pseudocode, doesnt compile, just to convey the meaning
public void InvalidateElement()
{
    if (CurrentlyDrawing)
        return;

    Dispatcher.BeginInvoke(() =>
    {
        CurrentlyDrawing = true;

        DoDrawInternal();

        CurrentlyDrawing = false;
    }
}

Ok so this is great. If I call InvalidateElement lots of times I get good responsiveness. However, what I want to do is ensure I can push data to my visualization component as fast as possible but only draw when the component is able to draw, and not keep drawing to catch up with the data once the input stream completes.

No I can't override OnRender, I'm using non-WPF drawing inside WPF ;-)

Basically what I want is something like the old Invalidate() / OnPaint in WindowsForms, or better yet, a game loop in DirectX.

At the moment I get the situation where if I have an external thread that pushes data to the visualization component at a high rate then if I Stop pushing data I get another 20 seconds worth of refreshes to get through before the component stops drawing. I want to stop drawing as soon as data has gone in.

Another idea I had was to handle CompositionTarget.Rendering in the visualization component then implement some sort of rudimentary Queue to push data to and the Rendering event consumes this data as fast as it can.

In Summary

Given a WPF visualization component, V, and a datasource which pushes it data every 1ms, D, how can I ensure that no matter the datarate of D, V draws data at 30FPS (or whatever it can do) and updates itself in chunks, sort of how a game render loop does in DirectX?

When the data stops, V should redraw everything it has up to now in one go. When the data is too fast, V draws larger chunks at a time to compensate.

If you need more information I'd be happy to share it. Right now I've just posted a synopsis to gauge if there are any quick fixes but a fuller Q with code examples can be provided on request.

Best regards,


问:
combobox data bind (C# winforms)
where is the problem with this code? When i start the program there is no values to choose from comboBox. There is no problems with compiling and starting an application. I have no idea what is wrong here. Maybe someone have solution for this problem.

Link to pastebin https://pastebin.com/pASVNWq

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

namespace parKing_new
{
    public partial class editClient : Form
    {
        public editClient()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {}

    //Load customer ID to a combobox
        private void LoadCustomersId()
        {
            var connectionString =
"Server=localhost;Port=3306;Database=ewisys;Uid=root;password=;";
            using (var connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                var query = "SELECT clientID FROM clients";
                using (var command = new MySqlCommand(query, connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        //Iterate through the rows and add it to the
combobox's items
                        while (reader.Read())
                        {
                        comboBox1.Items.Add(reader.GetString("clientID"));
                        }
                    }
                }
            }
       }

        //Load customer details using the ID
        private void LoadCustomerDetailsById(int id)
        {
            var connectionString =
"Server=localhost;Port=3306;Database=ewisys;Uid=root;password=;";
            using (var connection = new MySqlConnection(connectionString))
           {
               connection.Open();
               var query = "SELECT clientID, name, surName FROM clients WHERE
Id = @clientID";
                using (var command = new MySqlCommand(query, connection))
                {
                //Always use SQL parameters to avoid SQL injection and it
automatically escapes characters
                    command.Parameters.AddWithValue("@clientID", id);
                    using (var reader = command.ExecuteReader())
                    {
                        //No customer found by supplied ID
                        if (!reader.HasRows)
                            return;

                        ClientIDTextBox.Text =
                    reader.GetInt32("clientID").ToString();
                    nameTextBox.Text = reader.GetString("name");
                    surNameTextBox.Text = reader.GetString("surName");
                    }
                }
           }
       }

      private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var clientID = Convert.ToInt32(comboBox1.Text);
            LoadCustomerDetailsById(clientID);
        }
   }
}
</code>```

答:
Add this to your code.

The reason behind this is that when you launch your application, nothing is calling LoadCustomersId() function to populate the data on your comboBox. So use the Load event handler and populate your combobox from there:

```<code>private void editClient_Load(object sender, EventArgs e)
    {
       LoadCustomersId();
    }
</code>```

Title: combobox data bind (C# winforms)

Body:
where is the problem with this code? When i start the program there is no values to choose from comboBox. There is no problems with compiling and starting an application. I have no idea what is wrong here. Maybe someone have solution for this problem.

Link to pastebin https://pastebin.com/pASVNWq

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

namespace parKing_new
{
    public partial class editClient : Form
    {
        public editClient()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {}

    //Load customer ID to a combobox
        private void LoadCustomersId()
        {
            var connectionString =
"Server=localhost;Port=3306;Database=ewisys;Uid=root;password=;";
            using (var connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                var query = "SELECT clientID FROM clients";
                using (var command = new MySqlCommand(query, connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        //Iterate through the rows and add it to the
combobox's items
                        while (reader.Read())
                        {
                        comboBox1.Items.Add(reader.GetString("clientID"));
                        }
                    }
                }
            }
       }

        //Load customer details using the ID
        private void LoadCustomerDetailsById(int id)
        {
            var connectionString =
"Server=localhost;Port=3306;Database=ewisys;Uid=root;password=;";
            using (var connection = new MySqlConnection(connectionString))
           {
               connection.Open();
               var query = "SELECT clientID, name, surName FROM clients WHERE
Id = @clientID";
                using (var command = new MySqlCommand(query, connection))
                {
                //Always use SQL parameters to avoid SQL injection and it
automatically escapes characters
                    command.Parameters.AddWithValue("@clientID", id);
                    using (var reader = command.ExecuteReader())
                    {
                        //No customer found by supplied ID
                        if (!reader.HasRows)
                            return;

                        ClientIDTextBox.Text =
                    reader.GetInt32("clientID").ToString();
                    nameTextBox.Text = reader.GetString("name");
                    surNameTextBox.Text = reader.GetString("surName");
                    }
                }
           }
       }

      private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var clientID = Convert.ToInt32(comboBox1.Text);
            LoadCustomerDetailsById(clientID);
        }
   }
}

Body:
Add this to your code.

The reason behind this is that when you launch your application, nothing is calling LoadCustomersId() function to populate the data on your comboBox. So use the Load event handler and populate your combobox from there:

private void editClient_Load(object sender, EventArgs e)
    {
       LoadCustomersId();
    }


问:
How to show image url in wordpress foreeach loop?
I need to display sub categories from a particular category

```<code><?php
$subcategories = get_categories('&child_of=22&hide_empty');

foreach ($subcategories as $subcategory) {

echo '<a href="' . get_category_link( $subcategory->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $subcategory->name ) . '" ' . '>' . $subcategory->name.'</a>';

 echo '<p>'.$subcategory->description.'</p>';

}

?>
</code>```

I tried this

```<code>echo '<img class='hline' src='bloginfo('template_url')/img/hline.png' alt=''>';
</code>```

its not working

答:
You need to look at the basics of strings and concatenation in PHP.

You open your string with single quotes so you can't then use single quotes for HTML attributes unless you escape them first (\'hline\'). Instead you should be using double quotes for those attributes.

Then you need to break out of your string in order to use your PHP function, bloginfo(). With that said it makes more sense to use get_template_directory_uri() instead (or stylesheet directory depending on your setup).

Complete example:

```<code>echo '<img class="hline" src="' . get_template_directory_uri() . '/img/hline.png" alt="" />';
</code>```

Documentation: http://php.net/manual/en/language.types.string.php

Body:
I need to display sub categories from a particular category

<?php
$subcategories = get_categories('&child_of=22&hide_empty');

foreach ($subcategories as $subcategory) {

echo 'term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $subcategory->name ) . '" ' . '>' . $subcategory->name.'';

 echo '
'.$subcategory->description.'
';

}

?>

I tried this

echo '';

its not working

Body:
You need to look at the basics of strings and concatenation in PHP.

You open your string with single quotes so you can't then use single quotes for HTML attributes unless you escape them first (\'hline\'). Instead you should be using double quotes for those attributes.

Then you need to break out of your string in order to use your PHP function, bloginfo(). With that said it makes more sense to use get_template_directory_uri() instead (or stylesheet directory depending on your setup).

Complete example:

echo '<img class="hline" src="' . get_template_directory_uri() . '/img/hline.png" alt="" />';

Documentation: http://php.net/manual/en/language.types.string.php


问:
Python Sum of Linked List
These are my code

```<code>class Node():
'''A node in a linked list'''
    def __init__(self, data, next_node=None):
        self.data = data
        self.next_node = next_node

def sum(LL):

    head = LL

    # If Linked list is empty, return 0
    if (head.data is None or head.data == []):
        result = 0

    # If Linked List contain only 1 node then return it
    elif (head.next_node is None):
        result = head.data

    else:
        curr = head
        result = curr.data
        # If next is not None then add up to result
        while (curr.next_node is not None):
            curr = curr.next_node
            result += curr.data

    return result
</code>```

Problem is at the end of the code

```<code>while (curr.next_node is not None):
    curr = curr.next_node
    result += curr.data
</code>```

If i try this

```<code>LL = Node(1, Node(2, 3))
sum(LL)
</code>```

I don't understand why it said

builtins.AttributeError: 'int' object has no attribute 'data'

The while loop works until it reach the last node

result should be 6

答: You are pointing to a node at the end which does not exist. The second nested node points to a next node 3, but that node does not exist sow hen it goes to look for its data, it is nowhere to be found.</p>

Title: Python Sum of Linked List

Body:
These are my code

class Node():
'''A node in a linked list'''
    def __init__(self, data, next_node=None):
        self.data = data
        self.next_node = next_node

def sum(LL):

    head = LL

    # If Linked list is empty, return 0
    if (head.data is None or head.data == []):
        result = 0

    # If Linked List contain only 1 node then return it
    elif (head.next_node is None):
        result = head.data

    else:
        curr = head
        result = curr.data
        # If next is not None then add up to result
        while (curr.next_node is not None):
            curr = curr.next_node
            result += curr.data

    return result

Problem is at the end of the code

while (curr.next_node is not None):
    curr = curr.next_node
    result += curr.data

If i try this

LL = Node(1, Node(2, 3))
sum(LL)

I don't understand why it said

builtins.AttributeError: 'int' object has no attribute 'data'

The while loop works until it reach the last node

result should be 6


问:
Conditionally Applying class with ternary operator
I've got a Button component that I'd like to assign an active class to if the state is 'true'. </p>

```<code><Button
    onClick={this.preferenceHandler.bind(this, "straight")}
    className={"col-sm-12 text-center " + (this.state.straight ? "active") }
    viewStyle=  "primary"
>
    <h4>Straight</h4>
    <i className="icon icon-ok-6"></i>
</Button>
</code>```

答:
Similar with @rossipedia, but with ES6 template string

className={`col-sm-12 text-center ${this.state.straight ? 'active' : ''}`}```

Body:
I've got a Button component that I'd like to assign an active class to if the state is 'true'.

<Button
    onClick={this.preferenceHandler.bind(this, "straight")}
    className={"col-sm-12 text-center " + (this.state.straight ? "active") }
    viewStyle=  "primary"
>

Straight

</Button>


问:
Jquery multiselect deselect all options except the newly-selected one automatic
I'm using jquery bootstrap multiselect using  this documentation. My scripts looks like this:

```<code>  <script id="example">
     $(document).ready(function() {
     $('#demo').multiselect({
      enableClickableOptGroups: true,
      enableCollapsibleOptGroups: true,
     });
  });
  </script>
</code>```

I had inserted  optgroups, in each one there is 4 option.

```<code> <select id="demo" multiple="multiple" >
<optgroup label="Group 1">
  <option value="1-1">Option 1.1</option>
  <option value="2-1">Option 2.1</option>
  <option value="2-2">Option 2.2</option>
  <option value="2-3">Option 2.3</option>
</optgroup>
<optgroup label="Group 111">
  <option value="1-1">Option 1</option>
  <option value="2-1">Option 2</option>
  <option value="2-2">Option 3</option>
  <option value="2-3">Option 4</option>
</optgroup>
<optgroup label="Group 12">
  <option value="1-1">Option 5</option>
  <option value="2-1">Option 6</option>
  <option value="2-2">Option 7</option>
  <option value="2-3">Option 8</option>
</optgroup>
<optgroup label="Group 63">
  <option value="1-1">Option 63.4</option>
  <option value="2-1">Option 63.1</option>
  <option value="2-2">Option 63.2</option>
  <option value="2-3">Option 63.3</option>
</optgroup>
</code>```

Here is the fiddle : https://jsfiddle.net/etzacv5k/2/

The problem is when i check "Group 1", it is checked, then, when i select "Group 111", the previous one is deselected, and the new one is selected, same for the last group, when i check the last one, all previous ones are deselected. I want it to persist selected when because its multiple choice.

Can someone help me ?

答:
Actually, i solved the issue by changing the bootstrap-multiselect.js version , i used the one from davidstutz.

http://davidstutz.github.io/bootstrap-multiselect/dist/js/bootstrap-multiselect.js

Body:
I'm using jquery bootstrap multiselect using  this documentation. My scripts looks like this:

I had inserted  optgroups, in each one there is 4 option.

 <select id="demo" multiple="multiple" >
<optgroup label="Group 1">
  <option value="1-1">Option 1.1</option>
  <option value="2-1">Option 2.1</option>
  <option value="2-2">Option 2.2</option>
  <option value="2-3">Option 2.3</option>
</optgroup>
<optgroup label="Group 111">
  <option value="1-1">Option 1</option>
  <option value="2-1">Option 2</option>
  <option value="2-2">Option 3</option>
  <option value="2-3">Option 4</option>
</optgroup>
<optgroup label="Group 12">
  <option value="1-1">Option 5</option>
  <option value="2-1">Option 6</option>
  <option value="2-2">Option 7</option>
  <option value="2-3">Option 8</option>
</optgroup>
<optgroup label="Group 63">
  <option value="1-1">Option 63.4</option>
  <option value="2-1">Option 63.1</option>
  <option value="2-2">Option 63.2</option>
  <option value="2-3">Option 63.3</option>
</optgroup>

Here is the fiddle : https://jsfiddle.net/etzacv5k/2/

The problem is when i check "Group 1", it is checked, then, when i select "Group 111", the previous one is deselected, and the new one is selected, same for the last group, when i check the last one, all previous ones are deselected. I want it to persist selected when because its multiple choice.

Can someone help me ?


问:
Difference between public and private variables
```<code>namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}
</code>```

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?

答:
Public variables are accessible from out side classes but private one just accessible for current class and inner classes:</p>

```<code>public class VarClass
{
    public int publicID = 10;
    private int privateID = 100;
    public VarClass()
    {
        Console.WriteLine(publicID);
        Console.WriteLine(privateID);
    }

    public class InnerClass
    {
        public InnerClass()
        {
            VarClass c = new VarClass();
            Console.WriteLine(c.privateID);
            Console.WriteLine(c.publicID);
        }
    }
}

public class OuterClass
{
    public OuterClass()
    {
        VarClass c = new VarClass();
        Console.WriteLine(c.privateID); // Compile Error
        Console.WriteLine(c.publicID);
    }
}
</code>```

Body:
namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?

Body:
Public variables are accessible from out side classes but private one just accessible for current class and inner classes:

public class VarClass
{
    public int publicID = 10;
    private int privateID = 100;
    public VarClass()
    {
        Console.WriteLine(publicID);
        Console.WriteLine(privateID);
    }

    public class InnerClass
    {
        public InnerClass()
        {
            VarClass c = new VarClass();
            Console.WriteLine(c.privateID);
            Console.WriteLine(c.publicID);
        }
    }
}

public class OuterClass
{
    public OuterClass()
    {
        VarClass c = new VarClass();
        Console.WriteLine(c.privateID); // Compile Error
        Console.WriteLine(c.publicID);
    }
}


问:
dyld: Library not loaded: AdjustSdk.framework
I have get build error after adding Adjust SDK framework to my project.

Error like below:

dyld: Library not loaded: .framework/AdjustSdk
Referenced from: /var/containers/Bundle/Application/ADB9806B-4B6F-4EEE-88CC-BC66DA8207D3/LCWaikiki.app/LCWaikiki
Reason: image not found

答:
For solution i followed the steps below:

Add the AdjustSDK.framework to the "Embedded Binaries" section of the "General" tab of the Xcode project settings.

Close Xcode

Delete derived data : Open Terminal and enter below command: rm -rf ~/Library/Developer/Xcode/DerivedData

Clean project

Rebuild


问:
ui-disable-choice with function
I am trying to disable options in a ui-select using a function in the ui-disable-choice. Calling a function doesn't seem to work. Any ideas on what I am doing wrong?

UI-Select

```<code><ui-select
            id="affSel--{{seat.sli_no}}"
            class="affSel"
            perf-no ="{{seat.perf_no}}"
            sli-no="{{seat.sli_no}}"
            ng-required="true"
            theme="bootstrap"
            on-select="changedAffiliate(mySeat.seat.sli_no, cartPerf.perf_no, seat.sli_no,seat)">

    <ui-select-match placeholder="-- Select person --">{{$select.selected.fname + ' ' + $select.selected.lname}}</ui-select-match>
    <ui-select-choices repeat="affiliate in affiliates | seatAffTypeFilter:seat.seatAff"
                        ui-disable-choice="checkDisable(affiliate.customer_no,cartPerf.perf_no, seat.sli_no)">
        <div ng-bind-html="affiliate.fname + ' ' + affiliate.lname"></div>
        <small ng-show="affiliate.disabled">{{AffSelected}}</small>
        <small ng-show="affiliate.validation_pass_age == 'N'">{{invalidAffLbl}}</small>
    </ui-select-choices>
</ui-select>
</code>```

Function

```<code>$scope.checkDisable = function (customer_no, cur_perf_no, cur_sli_no) {
    $.each($scope.selectedAff, function (i) {
        if (this.customer_no == customer_no && this.perfNo == cur_perf_no && this.sli_no != cur_sli_no) {
            return true;
        } else {
            return false;
        }
    })
}
</code>```

答:
try

```<code>$scope.checkDisable = function (customer_no, cur_perf_no, cur_sli_no) {
    return false; //true;
}
</code>```

if this does not work it would mean that function types are not supported, but if it works, then you have code issue...

mostly you are not capturing result of $.each function, from the context it seems you need _.find rather than $.each

Title: ui-disable-choice with function

Body:
I am trying to disable options in a ui-select using a function in the ui-disable-choice. Calling a function doesn't seem to work. Any ideas on what I am doing wrong?

UI-Select

<ui-select
            id="affSel--{{seat.sli_no}}"
            class="affSel"
            perf-no ="{{seat.perf_no}}"
            sli-no="{{seat.sli_no}}"
            ng-required="true"
            theme="bootstrap"
            on-select="changedAffiliate(mySeat.seat.sli_no, cartPerf.perf_no, seat.sli_no,seat)">

    <ui-select-match placeholder="-- Select person --">{{$select.selected.fname + ' ' + $select.selected.lname}}</ui-select-match>
    <ui-select-choices repeat="affiliate in affiliates | seatAffTypeFilter:seat.seatAff"
                        ui-disable-choice="checkDisable(affiliate.customer_no,cartPerf.perf_no, seat.sli_no)">

        {{AffSelected}}
        {{invalidAffLbl}}
    </ui-select-choices>
</ui-select>

Function

$scope.checkDisable = function (customer_no, cur_perf_no, cur_sli_no) {
    $.each($scope.selectedAff, function (i) {
        if (this.customer_no == customer_no && this.perfNo == cur_perf_no && this.sli_no != cur_sli_no) {
            return true;
        } else {
            return false;
        }
    })
}

Body:
try

$scope.checkDisable = function (customer_no, cur_perf_no, cur_sli_no) {
    return false; //true;
}

if this does not work it would mean that function types are not supported, but if it works, then you have code issue...

mostly you are not capturing result of $.each function, from the context it seems you need _.find rather than $.each


问:
Recompile Linux Kernel not to use specific CPU register
I'm doing an experiment that write the index of loop into a CPU register R11, then building it with gcc -ffixed-r11 try to let compiler know do not use that reg, and finally using perf to measure it.

But when I check the report (using perf script), the R11 value of most record entry is not what I expected, it supposed to be the number sequence like 1..2..3 or 1..4..7, etc. But actually it just a few fixed value. (possibly affected by system call overwriting?)

How can I let perf records the value I set to the register in my program? Or I must to recompile the whole kernel with -ffixed-r11 to achieve?

Thanks everyone.

答:
You should not try to recompile kernel when you just want to sample some register with perf. As I understand, kernel has its own set of registers and will not overwrite user R11. syscall interface uses some fixed registers which can't be changed (can you try different reg?) and there are often glibc gateways to syscall which may use some additional registers (they are not in kernel, they are user-space code; often generated or written in assembler). You may try using gdb to monitor the register to change to find who did it. It can do this (hmm, one more link to the same user on SO): gdb: breakpoint when register will have value 0xffaa like gdb ./program then gdb commands start; watch $r11; continue; where.

Two weeks age there was question perf-report show value of CPU register about register value sampling with perf:

I follow this document and using perf record with --intr-regs=ax,bx,r15, trying to log additional CPU register information with PEBS record.

While there was x86 & PEBS, ARM may have  --intr-regs implemented too. Check output of perf record --intr-regs=\? (man perf-record: "To list the available registers use --intr-regs=\?") to find support status and register names.

To print registers, use perf script -F ip,sym,iregs command. There was example in some linux commits:

```<code>  # perf record --intr-regs=AX,SP usleep 1
  [ perf record: Woken up 1 times to write data ]
  [ perf record: Captured and wrote 0.016 MB perf.data (8 samples) ]
  # perf script -F ip,sym,iregs | tail -5
   ffffffff8105f42a native_write_msr_safe   AX:0xf    SP:0xffff8802629c3c00
   ffffffff8105f42a native_write_msr_safe   AX:0xf    SP:0xffff8802629c3c00
   ffffffff81761ac0 _raw_spin_lock   AX:0xffff8801bfcf8020    SP:0xffff8802629c3ce8
   ffffffff81202bf8 __vma_adjust_trans_huge   AX:0x7ffc75200000    SP:0xffff8802629c3b30
   ffffffff8122b089 dput   AX:0x101    SP:0xffff8802629c3c78
  #
</code>```

Body:
You should not try to recompile kernel when you just want to sample some register with perf. As I understand, kernel has its own set of registers and will not overwrite user R11. syscall interface uses some fixed registers which can't be changed (can you try different reg?) and there are often glibc gateways to syscall which may use some additional registers (they are not in kernel, they are user-space code; often generated or written in assembler). You may try using gdb to monitor the register to change to find who did it. It can do this (hmm, one more link to the same user on SO): gdb: breakpoint when register will have value 0xffaa like gdb ./program then gdb commands start; watch $r11; continue; where.

Two weeks age there was question perf-report show value of CPU register about register value sampling with perf:

I follow this document and using perf record with --intr-regs=ax,bx,r15, trying to log additional CPU register information with PEBS record.

While there was x86 & PEBS, ARM may have  --intr-regs implemented too. Check output of perf record --intr-regs=\? (man perf-record: "To list the available registers use --intr-regs=\?") to find support status and register names.

To print registers, use perf script -F ip,sym,iregs command. There was example in some linux commits:

  # perf record --intr-regs=AX,SP usleep 1
  [ perf record: Woken up 1 times to write data ]
  [ perf record: Captured and wrote 0.016 MB perf.data (8 samples) ]
  # perf script -F ip,sym,iregs | tail -5
   ffffffff8105f42a native_write_msr_safe   AX:0xf    SP:0xffff8802629c3c00
   ffffffff8105f42a native_write_msr_safe   AX:0xf    SP:0xffff8802629c3c00
   ffffffff81761ac0 _raw_spin_lock   AX:0xffff8801bfcf8020    SP:0xffff8802629c3ce8
   ffffffff81202bf8 __vma_adjust_trans_huge   AX:0x7ffc75200000    SP:0xffff8802629c3b30
   ffffffff8122b089 dput   AX:0x101    SP:0xffff8802629c3c78
  #


问:
How do I send emails outside my domain with Exchange 2007 and c#
I am able to send emails using the typical C# SMTP code across Exchange 2007 as long as both the from and to addresses are within my domain.

As soon as I try to send emails outside the domain I get:

Exception Details: System.Net.Mail.SmtpFailedRecipientException: Mailbox unavailable. The server response was: 5.7.1 Unable to relay

How can I get exchange to accept my email and send it out to the internet?

答: Have you set up the exchange server to allow relays from your web server? I had the same problem when switching to Exchange 2007.</p>

OwnerDisplayName: jmcd

OwnerDisplayName: David Thomas Garcia


问:
Twilio using access token to send SMS
I keep reading in the doc that the access token can be used for services like Voice/Chat/Video, but I don't see anywhere mention sending SMS. Does Twilio exclude this functionality on purpose? i.e. my mobile app can acquire an access_token to send SMS</p>

答:
You can send the message via twilio module with relevant information

See the example below

```<code>// Twilio Credentials
var accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var authToken = 'your_auth_token';

//require the Twilio module and create a REST client
var client = require('twilio')(accountSid, authToken);

client.messages.create({
    to: "+15558675309",
    from: "+15017250604",
    body: "This is the ship that made the Kessel Run in fourteen parsecs?",
    mediaUrl: "https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg",
}, function(err, message) {
    console.log(message.sid);
});
</code>```

You can refer the sending-messages docs here

Title: Twilio using access token to send SMS

Body:
You can send the message via twilio module with relevant information

See the example below

// Twilio Credentials
var accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var authToken = 'your_auth_token';

//require the Twilio module and create a REST client
var client = require('twilio')(accountSid, authToken);

client.messages.create({
    to: "+15558675309",
    from: "+15017250604",
    body: "This is the ship that made the Kessel Run in fourteen parsecs?",
    mediaUrl: "https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg",
}, function(err, message) {
    console.log(message.sid);
});

You can refer the sending-messages docs here


问:
Python open() requires full path
I am writing a script to read a csv file. The csv file and script lies in the same directory. But when I tried to open the file it gives me FileNotFoundError: [Errno 2] No such file or directory: 'zipcodes.csv'. The code I used to read the file is

```<code>with open('zipcodes.csv', 'r') as zipcode_file:
    reader = csv.DictReader(zipcode_file)
</code>```

If I give the full path to the file, it will work. Why open() requires full path of the file ?

答:
I don't think Python knows which dir to use... to start with the current path of the current python .py file, try:</p>

```<code>mypath = os.path.dirname(os.path.abspath(__file__))
with open(mypath+'/zipcodes.csv', 'r') as zipcode_file:
    reader = csv.DictReader(zipcode_file)
</code>```

Title: Python open() requires full path

Body:
I am writing a script to read a csv file. The csv file and script lies in the same directory. But when I tried to open the file it gives me FileNotFoundError: [Errno 2] No such file or directory: 'zipcodes.csv'. The code I used to read the file is

with open('zipcodes.csv', 'r') as zipcode_file:
    reader = csv.DictReader(zipcode_file)

If I give the full path to the file, it will work. Why open() requires full path of the file ?

Body:
I don't think Python knows which dir to use... to start with the current path of the current python .py file, try:

mypath = os.path.dirname(os.path.abspath(__file__))
with open(mypath+'/zipcodes.csv', 'r') as zipcode_file:
    reader = csv.DictReader(zipcode_file)


问:
Splitting or Chunking NSData on specific value(s) in swift
I'm trying to figure out how to "chunk" a NSData on a specific value.

Input Data

7E 55 33 22 7E 7E 22 AE BC 7E 7E AA AA 00 20 00 22 53 25 A3 4E 7E

Output Data

Returns an array of 3 elements of type [NSData] where the elements are:

55 33 22

22 AE BC

AA AA 00 20 00 22 53 25 A3 4E

Where I'm at

I know I can do something like:

```<code>var ptr = UnsafePointer<UInt8>(data.bytes)
var bytes = UnsafeBufferPointer<UInt8>(start: ptr, count: data.length)
</code>```

And I guess iterate through doing a comparison similar to:

```<code>bytes[1] == UInt8(0x7E)
</code>```

And I guess build up "ranges" but I was wondering if there is a better way to go about this?

Code Stub

```<code>private fund chunkMessage(data: NSData) -> [NSData] {
  var ptr = UnsafePointer<UInt8>(data.bytes)
  var bytes = UnsafeBufferPointer<UInt8>(start: ptr, count: data.length)
  var ret = []

 // DO SOME STUFF

  return ret as! [NSData];

}
</code>```

答:
Swift 3 this would work, with an extension to Data

```<code>//: Playground - noun: a place where people can play

import Cocoa
import Foundation

var str = "Hello, playground"

let d : Data = Data(bytes: [0x7E, 0x55, 0x33, 0x22, 0x7E, 0x7E, 0x22, 0xAE, 0xBC, 0x7E, 0x7E, 0xAA, 0xAA, 0x00, 0x20, 0x00, 0x22, 0x53, 0x25, 0xA3, 0x4E, 0x7E])

let f = d.separateData(bySeparator: 0x7E)
print(f) // [[0x55, 0x33, 0x22],[0x22, 0xAE, 0xBC],[0xAA, 0xAA, 0x00, 0x20, 0x00, 0x22, 0x53, 0x25, 0xA3, 0x4E]
//
//  Data+Separate.swift
//  Created by Julian Bleecker on 6/7/17.
//

public extension Data {

    /// Separate data into an array of an array of Int8
    func separateData(bySeparator : UInt8) -> [[UInt8]] {
        let bytes = [UInt8](self)

        let split = bytes.split(separator: bySeparator)

        let bunks = split.enumerated().map( { $0.1 } )

        let chunks = bunks.enumerated().map( {
            Data.init($0.element).toArray(type: UInt8.self)
        })

        return chunks
    }
    /// Bonus. Convert to an array of Strings which would be separated by nulls
    func separateDataToStrings(encoding: String.Encoding)  -> [String] {
        let strunks: [String] = self.separateData(bySeparator: 0x00).enumerated().map( {
            let d: Data = Data.init(bytes: $0.element)
            return String(data: d, encoding: .utf8)!
        })
        return strunks
    }

    func toArray<T>(type: T.Type) -> [T] {
        return self.withUnsafeBytes {
            [T](UnsafeBufferPointer(start: $0, count: self.count/MemoryLayout<T>.stride))
        }
    }
}
</code>```

Body:
I'm trying to figure out how to "chunk" a NSData on a specific value.

Input Data

7E 55 33 22 7E 7E 22 AE BC 7E 7E AA AA 00 20 00 22 53 25 A3 4E 7E

Output Data

Returns an array of 3 elements of type [NSData] where the elements are:

55 33 22

22 AE BC

AA AA 00 20 00 22 53 25 A3 4E

Where I'm at

I know I can do something like:

var ptr = UnsafePointer<UInt8>(data.bytes)
var bytes = UnsafeBufferPointer<UInt8>(start: ptr, count: data.length)

And I guess iterate through doing a comparison similar to:

bytes[1] == UInt8(0x7E)

And I guess build up "ranges" but I was wondering if there is a better way to go about this?

Code Stub

private fund chunkMessage(data: NSData) -> [NSData] {
  var ptr = UnsafePointer<UInt8>(data.bytes)
  var bytes = UnsafeBufferPointer<UInt8>(start: ptr, count: data.length)
  var ret = []

 // DO SOME STUFF

  return ret as! [NSData];

}

Body:
Swift 3 this would work, with an extension to Data

//: Playground - noun: a place where people can play

import Cocoa
import Foundation

var str = "Hello, playground"

let d : Data = Data(bytes: [0x7E, 0x55, 0x33, 0x22, 0x7E, 0x7E, 0x22, 0xAE, 0xBC, 0x7E, 0x7E, 0xAA, 0xAA, 0x00, 0x20, 0x00, 0x22, 0x53, 0x25, 0xA3, 0x4E, 0x7E])

let f = d.separateData(bySeparator: 0x7E)
print(f) // [[0x55, 0x33, 0x22],[0x22, 0xAE, 0xBC],[0xAA, 0xAA, 0x00, 0x20, 0x00, 0x22, 0x53, 0x25, 0xA3, 0x4E]
//
//  Data+Separate.swift
//  Created by Julian Bleecker on 6/7/17.
//

public extension Data {

    /// Separate data into an array of an array of Int8
    func separateData(bySeparator : UInt8) -> [[UInt8]] {
        let bytes = [UInt8](self)

        let split = bytes.split(separator: bySeparator)

        let bunks = split.enumerated().map( { $0.1 } )

        let chunks = bunks.enumerated().map( {
            Data.init($0.element).toArray(type: UInt8.self)
        })

        return chunks
    }
    /// Bonus. Convert to an array of Strings which would be separated by nulls
    func separateDataToStrings(encoding: String.Encoding)  -> [String] {
        let strunks: [String] = self.separateData(bySeparator: 0x00).enumerated().map( {
            let d: Data = Data.init(bytes: $0.element)
            return String(data: d, encoding: .utf8)!
        })
        return strunks
    }

    func toArray<T>(type: T.Type) -> [T] {
        return self.withUnsafeBytes {
            [T](UnsafeBufferPointer(start: $0, count: self.count/MemoryLayout<T>.stride))
        }
    }
}