问:
What does Tokens do and why they need to be created in C++ programming?
I am reading a book (Programming Principles and Practice by Bjarne Stroustrup).

In which he introduce Tokens:

“A token is a sequence of characters that represents something we consider a unit, such as a number or an operator. That’s the way a C++ compiler deals with its source. Actually, “tokenizing” in some form or another is the way most analysis of text starts.”

```<code>class Token {
public:
    char kind;
    double value;
};
</code>```

I do get what they are but he never explains this in detail and its quite confusing to me.

答:
Tokenizing is important to the process of figuring out what a program does. What Bjarne is referring to in relation to C++ source deals with how a programs meaning is affected by the tokenization rules. In particular, we must know what the tokens are, and how they are determined. Specifically, how can we identify a single token when it appears next to other characters, and how should we delimit tokens if there is ambiguity.

For instance, consider the prefix operators ++ and +. Let's assume we only had one token + to work with. What is the meaning of the following snippet?

```<code>int i = 1;
++i;
</code>```

With + only, is the above going to just apply unary + on i twice? Or is it going to increment it once? It's ambiguous, naturally. We need an additional token, and therefore introduce ++ as it's own "word" in the language.

But now there is another (albeit smaller) problem. What if the programmer wants to just apply unary + twice, and not increment? Token processing rules are needed. So if we determine that a white space is always a separator for tokens, our programmer may write:

```<code>int i = 1;
+ +i;
</code>```

Roughly speaking, a C++ implementation starts with a file full of characters, transforms them initially to a sequence of tokens ("words" with meaning in the C++ language), and then checks if the tokens appear in a "sentence" that has some valid meaning.

Body:
I am reading a book (Programming Principles and Practice by Bjarne Stroustrup).

In which he introduce Tokens:

“A token is a sequence of characters that represents something we consider a unit, such as a number or an operator. That’s the way a C++ compiler deals with its source. Actually, “tokenizing” in some form or another is the way most analysis of text starts.”

class Token {
public:
    char kind;
    double value;
};

I do get what they are but he never explains this in detail and its quite confusing to me.

Body:
Tokenizing is important to the process of figuring out what a program does. What Bjarne is referring to in relation to C++ source deals with how a programs meaning is affected by the tokenization rules. In particular, we must know what the tokens are, and how they are determined. Specifically, how can we identify a single token when it appears next to other characters, and how should we delimit tokens if there is ambiguity.

For instance, consider the prefix operators ++ and +. Let's assume we only had one token + to work with. What is the meaning of the following snippet?

int i = 1;
++i;

With + only, is the above going to just apply unary + on i twice? Or is it going to increment it once? It's ambiguous, naturally. We need an additional token, and therefore introduce ++ as it's own "word" in the language.

But now there is another (albeit smaller) problem. What if the programmer wants to just apply unary + twice, and not increment? Token processing rules are needed. So if we determine that a white space is always a separator for tokens, our programmer may write:

int i = 1;
+ +i;

Roughly speaking, a C++ implementation starts with a file full of characters, transforms them initially to a sequence of tokens ("words" with meaning in the C++ language), and then checks if the tokens appear in a "sentence" that has some valid meaning.


来源: stackexchange

问:
Linux kernel: How to get dev_t of whole disk from partitioned disk?
I want to retrieve the dev_t structure for a whole disk, given that of a partition on the disk.  This is for for a blkext driver,  like nvme.

Something like:

```<code>dev_t part_disk;
dev_t whole_disk = get_whole_disk_dev_t(part_disk);
</code>```

I would like my the interface of get_whole_disk_dev_t() to be:

Argument: dev_t: part_disk

Return: dev_t: whole_disk

My proposed algorithm:

Get path of partitioned disk from dev_t i.e "/dev/nvme1n1p3".  I couldn't find any API to get path from dev_t.

Do some string manipulation to remove "p3", giving the path for whole disk

Pass the path_name of whole disk to blk_lookup_devt to get the dev_t of whole disk.

i.e whole_disk=blk_lookup_devt(path_name,0)

Is this the right approach or is there a better approach? If the former, then how can I get path from dev_t?

P.S: I need to implement this in a device driver (i.e in kernel context). In user space I know I can use the udev API.

答:
It's not a problem: you can read /proc/partitions file, obtain needed sd[a|b|c]
drive id. Suppose, that id:
char devId[] = "sdb"
after that invoking devno = blk_lookup_devt(devId, 0);</p>

ContentLicense: CC BY-SA 3.0

Body:
I want to retrieve the dev_t structure for a whole disk, given that of a partition on the disk.  This is for for a blkext driver,  like nvme.

Something like:

dev_t part_disk;
dev_t whole_disk = get_whole_disk_dev_t(part_disk);

I would like my the interface of get_whole_disk_dev_t() to be:

Argument: dev_t: part_disk

Return: dev_t: whole_disk

My proposed algorithm:

Get path of partitioned disk from dev_t i.e "/dev/nvme1n1p3".  I couldn't find any API to get path from dev_t.

Do some string manipulation to remove "p3", giving the path for whole disk

Pass the path_name of whole disk to blk_lookup_devt to get the dev_t of whole disk.

i.e whole_disk=blk_lookup_devt(path_name,0)

Is this the right approach or is there a better approach? If the former, then how can I get path from dev_t?

P.S: I need to implement this in a device driver (i.e in kernel context). In user space I know I can use the udev API.


问:
How to enable php intl
I'm on Ubuntu 17.10
PHP Version: 7.1

I already tried this:

```<code>sudo apt-get install php7.1-intl
sudo service apache2 restart
</code>```

But when I var_dump extension_loaded('intl') it returns false. How can I enable this mod?

答:
First you check the php.ini file location. For that use a php file and write:

```<code>phpinfo();
</code>```

Then load this file in browser. You can see which config file php is using.

In the php.ini find this line:

```<code>;extension=php_intl.dll
</code>```

and change to

```<code>extension=php_intl.dll
</code>```

Restart your apache

sudo service apache2 restart

Title: How to enable php intl

Body:
I'm on Ubuntu 17.10
PHP Version: 7.1

I already tried this:

sudo apt-get install php7.1-intl
sudo service apache2 restart

But when I var_dump extension_loaded('intl') it returns false. How can I enable this mod?

Body:
First you check the php.ini file location. For that use a php file and write:

phpinfo();

Then load this file in browser. You can see which config file php is using.

In the php.ini find this line:

;extension=php_intl.dll

and change to

extension=php_intl.dll

Restart your apache

sudo service apache2 restart

ContentLicense: CC BY-SA 4.0


问:
Brackets in python rgex
Here's a strip of my code:

```<code>import re

prog2 = re.compile(r'\[\w\]')
activity = "[CS150]"
if prog2.match(activity):
    print 'matched'
else:
    print 'unmatched'
</code>```

I don't know why it prints unmatched, because I stated the pattern well I think and gave a right input.

答:
This below gives the expected result </p>

```<code>import re
prog2 = re.compile(r'\[\w+\]')
activity = "[CS150]"
if prog2.match(activity):
    print ('matched')
else:
    print ('unmatched')

>>matched
</code>```

<p>Hope that was helpful ! </p>

Title: Brackets in python rgex

Body:
Here's a strip of my code:

import re

prog2 = re.compile(r'\[\w\]')
activity = "[CS150]"
if prog2.match(activity):
    print 'matched'
else:
    print 'unmatched'

I don't know why it prints unmatched, because I stated the pattern well I think and gave a right input.

Body:
This below gives the expected result

import re
prog2 = re.compile(r'\[\w+\]')
activity = "[CS150]"
if prog2.match(activity):
    print ('matched')
else:
    print ('unmatched')

>>matched

Hope that was helpful !


问:
I want to make a firewall rule to allow smooch.io on my server
I am trying to configure webhook connection to my server but smooch is not able to connect( firewall policies). I need to allow smooch IP but the ping test returns different IP address all the times.

Is there any set of IP(s) which I can allow in the firewall directly?

答:
Smooch does not currently have a static set of IPs from which it sends webhooks, but the team is actively working on supporting this.

If you absolutely need static IPs in the meantime to bypass your firewall, you would need to host your own server outside the firewall that relays Smooch webhooks from a static IP that you've configured yourself. Then, configure Smooch to send webhooks to your proxy server instead of your real server.


答:
He's refering to the lexical analysis - the necessary piece of every compiler. It is a tool for the compiler to treat a text (as in: a sequence of bytes) in a meaningful way. For example consider the following line in C++

```<code>double x  = (15*3.0);  // my variable
</code>```

when the compiler looks at the text it first splits the line into a sequence of tokens which may look like this:

```<code>Token {"identifier", "double"}
Token {"space", " "}
Token {"identifier", "x"}
Token {"space", "  "}
Token {"operator", "="}
Token {"space", " "}
Token {"separator", "("}
Token {"literal_integer", "15"}
Token {"operator", "*"}
Token {"literal_float", "3.0"}
Token {"separator", ")"}
Token {"separator", ";"}
Token {"space", "  "}
Token {"comment", "// my variable"}
Token {"end_of_line"}
</code>```

It doesn't have to be interpreted like above (note that in my case both kind and value are strings), its just an example how it can be done. You usually do this via some regular expressions.

Anyway tokens are easier to understand for the machine then a raw text. Next step for the compiler is to create so called abstract syntax tree based on the tokenization and finally add meaning to everything.

Also note that unless you are writing a parser it is unlikely you will ever use the concept.

Title: What does Tokens do and why they need to be created in C++ programming?

Body:
He's refering to the lexical analysis - the necessary piece of every compiler. It is a tool for the compiler to treat a text (as in: a sequence of bytes) in a meaningful way. For example consider the following line in C++

double x  = (15*3.0);  // my variable

when the compiler looks at the text it first splits the line into a sequence of tokens which may look like this:

Token {"identifier", "double"}
Token {"space", " "}
Token {"identifier", "x"}
Token {"space", "  "}
Token {"operator", "="}
Token {"space", " "}
Token {"separator", "("}
Token {"literal_integer", "15"}
Token {"operator", "*"}
Token {"literal_float", "3.0"}
Token {"separator", ")"}
Token {"separator", ";"}
Token {"space", "  "}
Token {"comment", "// my variable"}
Token {"end_of_line"}

It doesn't have to be interpreted like above (note that in my case both kind and value are strings), its just an example how it can be done. You usually do this via some regular expressions.

Anyway tokens are easier to understand for the machine then a raw text. Next step for the compiler is to create so called abstract syntax tree based on the tokenization and finally add meaning to everything.

Also note that unless you are writing a parser it is unlikely you will ever use the concept.


问:
UICollectionView - Scrolling to first cell
I'm making use of UICollectionView and I need to scroll to first cell after click in a button.

The button is located in a (big) header section in my collection view... when clicking int it, I need scroll to my first cell located bellow of this button.

I created a action of this button, but I don't know how to scroll to first UICollectionViewCell.

Can someone help me?

答:
```<code>if let indexPath = self.collectionView?.indexPathForItem(at: CGPoint(x: 0, y: 0)) {
            self.collectionView?.scrollToItem(at: indexPath, at: .top, animated: false)
}
</code>```


问:
How to obtain updated list of browsers in browser_changed event handler of Karma API?
I want to use the karma API to automatically close the karma server after I manually closed the browser window.

```<code> ...
 var karmaServer = new karma.Server(karmaOptions, done);
 karmaServer.on('browsers_change', stopServerIfAllBrowsersAreClosed); //for a full list of events see http://karma-runner.github.io/1.0/dev/public-api.html
 karmaServer.start();

function stopServerIfAllBrowsersAreClosed(browsers) {
  if (browsers.length === 0) {

    //double check since browser might only be closed temporarily due to connection issues
    setTimeout(function () {
      if (browsers.length === 0) {
         karma.stopper.stop();
      }
    }, 2000);
 }
}
</code>```

Will that code work as expected, because the (observable?) browsers argument will always be updated when the number of browser changes?

Or will the length of browsers always be zero if the browser_change event has been emitted during a connection issue?

The karma doc does not state whether the collection is observable or not:

https://karma-runner.github.io/0.13/dev/public-api.html

If this does not work, do you know an alternative strategy to only stop the server after manually closing the last browser window and not for network connection issues?

答:
It turned out that the browsers array is not updated and that the "double check" does not work. I did not find a way to get the updated number of browsers.

What helped was to increase the browserDisconnectTimeout in karma.conf.js to avoid the unwanted closing issue.

Body:
I want to use the karma API to automatically close the karma server after I manually closed the browser window.

 ...
 var karmaServer = new karma.Server(karmaOptions, done);
 karmaServer.on('browsers_change', stopServerIfAllBrowsersAreClosed); //for a full list of events see http://karma-runner.github.io/1.0/dev/public-api.html
 karmaServer.start();

function stopServerIfAllBrowsersAreClosed(browsers) {
  if (browsers.length === 0) {

    //double check since browser might only be closed temporarily due to connection issues
    setTimeout(function () {
      if (browsers.length === 0) {
         karma.stopper.stop();
      }
    }, 2000);
 }
}

Will that code work as expected, because the (observable?) browsers argument will always be updated when the number of browser changes?

Or will the length of browsers always be zero if the browser_change event has been emitted during a connection issue?

The karma doc does not state whether the collection is observable or not:

https://karma-runner.github.io/0.13/dev/public-api.html

If this does not work, do you know an alternative strategy to only stop the server after manually closing the last browser window and not for network connection issues?


问:
onblur event is not firing
I need to fire onblur event when I click outside "aside panel", in order to make the panel close if user clicks outside navigation panel.

Though I'm using React JS - but for simplicity I've written example in pure JavaScript.
Lately I've written something similar and everything works fine, but in this case it's not working, may be because of position fixed.

var d = document.getElementById("fname");

d.addEventListener("blur", myFunction);

function myFunction() {
  alert("Input field lost focus.");
}
var state = true;

function myFunction2() {
  state = !state;
  if (state) {
    d.className = "header__aside";
  } else {
    d.className += " header__aside--open";
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main {
  background-color: violet;
  padding: 50px;
}

.header__aside {
  background-color: #cfcfcf;
  box-shadow: 0 19px 38px rgba(0, 0, 0, 0.3), 0 15px 12px rgba(0, 0, 0, 0.22);
  font-size: 1.2rem;
  height: 100%;
  opacity: 0.9;
  position: fixed;
  right: -30%;
  top: 0;
  transition: right 0.5s ease-out;
  width: 30%;
  z-index: 10;
}

.header__aside--open {
  right: 0;
}</code>```

This example

<button type="button" onClick="myFunction2()">
☰
</button>

      <button type="button" class="aside-nav__header-button" onClick="myFunction2()">x</button>

      Main

```

答:
You will have to set a tabindex on the div and manually focus it to get the blur handler invoked

var d = document.getElementById("fname");

d.addEventListener("blur", myFunction);

function myFunction() {
  alert("Input field lost focus.");
}
var state = true;

function myFunction2() {
  state = !state;
  d.focus();
  if (state) {
    d.className = "header__aside";
  } else {
    d.className += " header__aside--open";
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main {
  background-color: violet;
  padding: 50px;
}

.header__aside {
  background-color: #cfcfcf;
  box-shadow: 0 19px 38px rgba(0, 0, 0, 0.3), 0 15px 12px rgba(0, 0, 0, 0.22);
  font-size: 1.2rem;
  height: 100%;
  opacity: 0.9;
  position: fixed;
  right: -30%;
  top: 0;
  transition: right 0.5s ease-out;
  width: 30%;
  z-index: 10;
}

.header__aside--open {
  right: 0;
}</code>```

This example

<button type="button" onClick="myFunction2()">
☰
</button>

      <button type="button" class="aside-nav__header-button" onClick="myFunction2()">x</button>

      Main

```

Title: onblur event is not firing

Body:
I need to fire onblur event when I click outside "aside panel", in order to make the panel close if user clicks outside navigation panel.

Though I'm using React JS - but for simplicity I've written example in pure JavaScript.
Lately I've written something similar and everything works fine, but in this case it's not working, may be because of position fixed.

var d = document.getElementById("fname");

d.addEventListener("blur", myFunction);

function myFunction() {
  alert("Input field lost focus.");
}
var state = true;

function myFunction2() {
  state = !state;
  if (state) {
    d.className = "header__aside";
  } else {
    d.className += " header__aside--open";
  }

}

.main {
  background-color: violet;
  padding: 50px;
}

.header__aside {
  background-color: #cfcfcf;
  box-shadow: 0 19px 38px rgba(0, 0, 0, 0.3), 0 15px 12px rgba(0, 0, 0, 0.22);
  font-size: 1.2rem;
  height: 100%;
  opacity: 0.9;
  position: fixed;
  right: -30%;
  top: 0;
  transition: right 0.5s ease-out;
  width: 30%;
  z-index: 10;
}

.header__aside--open {
  right: 0;
}

This example

<button type="button" onClick="myFunction2()">
☰
</button>

      <button type="button" class="aside-nav__header-button" onClick="myFunction2()">x</button>

      Main

Body:
You will have to set a tabindex on the div and manually focus it to get the blur handler invoked

var d = document.getElementById("fname");

d.addEventListener("blur", myFunction);

function myFunction() {
  alert("Input field lost focus.");
}
var state = true;

function myFunction2() {
  state = !state;
  d.focus();
  if (state) {
    d.className = "header__aside";
  } else {
    d.className += " header__aside--open";
  }

}

.main {
  background-color: violet;
  padding: 50px;
}

.header__aside {
  background-color: #cfcfcf;
  box-shadow: 0 19px 38px rgba(0, 0, 0, 0.3), 0 15px 12px rgba(0, 0, 0, 0.22);
  font-size: 1.2rem;
  height: 100%;
  opacity: 0.9;
  position: fixed;
  right: -30%;
  top: 0;
  transition: right 0.5s ease-out;
  width: 30%;
  z-index: 10;
}

.header__aside--open {
  right: 0;
}

<p class='main'>This example</p>
<button type="button" onClick="myFunction2()">
&#9776;
</button>
<div class="header__aside" id="fname" tabindex="0">
  <div class="aside-nav">
    <div class="aside-nav__header">
      <button type="button" class="aside-nav__header-button" onClick="myFunction2()">x</button>
    </div>
    <nav class="nav nav__aside">
      <a class="nav__aside-link active" aria-current="true" href="/">Main</a>
    </nav>
  </div>
</div>


问:
Strange behaviour of simple pycuda kernel
I'm quite new to cuda and pycuda.
I need a kernel that creates a matrix (of dimension n x d) out of an array (1 x d), by simply "repeating" the same array n times:
for example, suppose we have n = 4 and d = 3, then if the array is [1 2 3]
the result of my kernel should be:

```<code>[1 2 3
 1 2 3
 1 2 3
 1 2 3]
</code>```

(a matrix 4x3).

Basically, it's the same as doing numpy.tile(array, (n, 1))

I've written the code below:

```<code>kernel_code_template = """
__global__ void TileKernel(float *in, float *out)
{
    // Each thread computes one element of out
    int y = blockIdx.y * blockDim.y + threadIdx.y;
    int x = blockIdx.x * blockDim.x + threadIdx.x;

    if (y > %(n)s || x > %(d)s) return;

    out[y * %(d)s + x] = in[x];
}
"""

d = 64
n = 512

blockSizex = 16
blockSizey = 16
gridSizex = (d + blockSizex - 1) / blockSizex
gridSizey = (n + blockSizey - 1) / blockSizey

# get the kernel code from the template
kernel_code = kernel_code_template % {
    'd': d,
    'n': n
    }
mod = SourceModule(kernel_code)
TileKernel = mod.get_function("TileKernel")

vec_cpu = np.arange(d).astype(np.float32) # just as an example
vec_gpu = gpuarray.to_gpu(vec_cpu)
out_gpu = gpuarray.empty((n, d), np.float32)

TileKernel.prepare("PP")
TileKernel.prepared_call((gridSizex, gridSizey), (blockSizex, blockSizey, 1), vec_gpu.gpudata,  out_gpu.gpudata)

out_cpu = out_gpu.get()
</code>```

Now, if I run this code with d equals a power of 2 >= 16 I get the right result (just like numpy.tile(vec_cpu, (n, 1)) );
but if I set d equals to anything else (let's say for example 88) I get that every element of the output matrix has the
correct value, except the first column: some entries are right but others have another value, apparently random, same for every wrong element, but different every run,
and also the entries of the first column that have the wrong value are different every run.
Example:

```<code>[0  1  2
 0  1  2
 6  1  2
 0  1  2
 6  1  2
 ...]
</code>```

I really can't figure out what is causing this problem, but maybe it's just something simple that I'm missing...

Any help will be appreciated, thanks in advance!

答:
The bounds checking within your kernel code is incorrect. This

```<code>if (y > n ||  x > d) return;
out[y * d + x] = in[x];
</code>```

should be:

```<code>if (y >= n ||  x >= d) return;
out[y * d + x] = in[x];
</code>```

or better still:

```<code>if ((y < n) && (x < d))
    out[y * d + x] = in[x];
</code>```

All array valid indexing in the array lies on 0 < x < d and 0 < y < n. By allowing x=d you have undefined behaviour, allowing the first entry in the next row of the output array to be overwritten with an unknown value. This explains why sometimes the results were correct and other times not.

Body:
I'm quite new to cuda and pycuda.
I need a kernel that creates a matrix (of dimension n x d) out of an array (1 x d), by simply "repeating" the same array n times:
for example, suppose we have n = 4 and d = 3, then if the array is [1 2 3]
the result of my kernel should be:

[1 2 3
 1 2 3
 1 2 3
 1 2 3]

(a matrix 4x3).

Basically, it's the same as doing numpy.tile(array, (n, 1))

I've written the code below:

kernel_code_template = """
__global__ void TileKernel(float *in, float *out)
{
    // Each thread computes one element of out
    int y = blockIdx.y * blockDim.y + threadIdx.y;
    int x = blockIdx.x * blockDim.x + threadIdx.x;

    if (y > %(n)s || x > %(d)s) return;

    out[y * %(d)s + x] = in[x];
}
"""

d = 64
n = 512

blockSizex = 16
blockSizey = 16
gridSizex = (d + blockSizex - 1) / blockSizex
gridSizey = (n + blockSizey - 1) / blockSizey

# get the kernel code from the template
kernel_code = kernel_code_template % {
    'd': d,
    'n': n
    }
mod = SourceModule(kernel_code)
TileKernel = mod.get_function("TileKernel")

vec_cpu = np.arange(d).astype(np.float32) # just as an example
vec_gpu = gpuarray.to_gpu(vec_cpu)
out_gpu = gpuarray.empty((n, d), np.float32)

TileKernel.prepare("PP")
TileKernel.prepared_call((gridSizex, gridSizey), (blockSizex, blockSizey, 1), vec_gpu.gpudata,  out_gpu.gpudata)

out_cpu = out_gpu.get()

Now, if I run this code with d equals a power of 2 >= 16 I get the right result (just like numpy.tile(vec_cpu, (n, 1)) );
but if I set d equals to anything else (let's say for example 88) I get that every element of the output matrix has the
correct value, except the first column: some entries are right but others have another value, apparently random, same for every wrong element, but different every run,
and also the entries of the first column that have the wrong value are different every run.
Example:

[0  1  2
 0  1  2
 6  1  2
 0  1  2
 6  1  2
 ...]

I really can't figure out what is causing this problem, but maybe it's just something simple that I'm missing...

Any help will be appreciated, thanks in advance!

Body:
The bounds checking within your kernel code is incorrect. This

if (y > n ||  x > d) return;
out[y * d + x] = in[x];

should be:

if (y >= n ||  x >= d) return;
out[y * d + x] = in[x];

or better still:

if ((y < n) && (x < d))
    out[y * d + x] = in[x];

All array valid indexing in the array lies on 0 < x < d and 0 < y < n. By allowing x=d you have undefined behaviour, allowing the first entry in the next row of the output array to be overwritten with an unknown value. This explains why sometimes the results were correct and other times not.


问:
UICollectionView spacing margins
I have a UICollectionView which shows photos. I have created the collectionview using UICollectionViewFlowLayout. It works good but I would like to have spacing on margins. Is it possible to do that using UICollectionViewFlowLayout or must I implement my own UICollectionViewLayout?

答:
Modern Swift, Automatic Layout Calculation

While this thread already contains a bunch of useful answers, I want to add a modern Swift version, based on William Hu's answer. It also improves two things:

The spacing between different lines will now always match the spacing between items in the same line.

By setting a minimum width, the
code automatically calculates the number of items in a row and
applies that style to the flow layout.

Here's the code:

```<code>// Create flow layout
let flow = UICollectionViewFlowLayout()

// Define layout constants
let itemSpacing: CGFloat = 1
let minimumCellWidth: CGFloat = 120
let collectionViewWidth = collectionView!.bounds.size.width

// Calculate other required constants
let itemsInOneLine = CGFloat(Int((collectionViewWidth - CGFloat(Int(collectionViewWidth / minimumCellWidth) - 1) * itemSpacing) / minimumCellWidth))
let width = collectionViewWidth - itemSpacing * (itemsInOneLine - 1)
let cellWidth = floor(width / itemsInOneLine)
let realItemSpacing = itemSpacing + (width / itemsInOneLine - cellWidth) * itemsInOneLine / max(1, itemsInOneLine - 1)

// Apply values
flow.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
flow.itemSize = CGSize(width: cellWidth, height: cellWidth)
flow.minimumInteritemSpacing = realItemSpacing
flow.minimumLineSpacing = realItemSpacing

// Apply flow layout
collectionView?.setCollectionViewLayout(flow, animated: false)
</code>```

Title: UICollectionView spacing margins

Body:
Modern Swift, Automatic Layout Calculation

While this thread already contains a bunch of useful answers, I want to add a modern Swift version, based on William Hu's answer. It also improves two things:

The spacing between different lines will now always match the spacing between items in the same line.

By setting a minimum width, the
code automatically calculates the number of items in a row and
applies that style to the flow layout.

Here's the code:

// Create flow layout
let flow = UICollectionViewFlowLayout()

// Define layout constants
let itemSpacing: CGFloat = 1
let minimumCellWidth: CGFloat = 120
let collectionViewWidth = collectionView!.bounds.size.width

// Calculate other required constants
let itemsInOneLine = CGFloat(Int((collectionViewWidth - CGFloat(Int(collectionViewWidth / minimumCellWidth) - 1) * itemSpacing) / minimumCellWidth))
let width = collectionViewWidth - itemSpacing * (itemsInOneLine - 1)
let cellWidth = floor(width / itemsInOneLine)
let realItemSpacing = itemSpacing + (width / itemsInOneLine - cellWidth) * itemsInOneLine / max(1, itemsInOneLine - 1)

// Apply values
flow.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
flow.itemSize = CGSize(width: cellWidth, height: cellWidth)
flow.minimumInteritemSpacing = realItemSpacing
flow.minimumLineSpacing = realItemSpacing

// Apply flow layout
collectionView?.setCollectionViewLayout(flow, animated: false)


问:
Drop down button is not responding with selenium in java
I want to click on drop down button and select one among one and click on it.I tried by many ways but it is not working. Attached image of html code, Anyone help me regarding this.
Below is my code which i tried

```<code>driver.findElement(By.id("homepages_dropdown")).click();

    /*List<WebElement> allElements = driver.findElements(By.xpath("//*[@id=\"homepages_item_AccountManagerDashboard\"]"));

    for (WebElement element: allElements)
    {
          System.out.println(element.getText());
    }*/
</code>```

答:
This isn't the sharpest way to do it, but if you can't get developers to make it a specific select element via HTML it may have to do. I have stuff like this in my solution where there are custom dropdowns.

You can start by creating a dropdown element and then click a single record in it if that's what you're trying to do, in your case it looks like it is the span within the highlighted button element, so you can do something like the following:

```<code>driver.findElement(By.id("homepages_dropdown")).click();
driver.findElement(By.xpath("//li//a[@id='homepages_item_AccountManagerDashboard']").click();
</code>```

The above statements will click the dropdown then click the element with the id of homepages_item_AccountManagerDashboard.

You can also create a function that clicks any li of based off of a parameter you pass into a method you create, consider this if you may select many options in your dropdown.

```<code>public void SelectItem(string itemText)
{
    var dropdownElement = driver.findElement(By.id("homepages_dropdown"));
    var selectionItem = driver.findElement(By.xpath("//li[text()='" + itemText + "']");
    dropdownElement.Click();
    selectionItem.Click();
}
</code>```

This is only really a valid option if you are working through the Page Object Model, but it's the best way to make things work consistently long term.

Body:
I want to click on drop down button and select one among one and click on it.I tried by many ways but it is not working. Attached image of html code, Anyone help me regarding this.
Below is my code which i tried

driver.findElement(By.id("homepages_dropdown")).click();

    /*List<WebElement> allElements = driver.findElements(By.xpath("//*[@id=\"homepages_item_AccountManagerDashboard\"]"));

    for (WebElement element: allElements)
    {
          System.out.println(element.getText());
    }*/

Body:
This isn't the sharpest way to do it, but if you can't get developers to make it a specific select element via HTML it may have to do. I have stuff like this in my solution where there are custom dropdowns.

You can start by creating a dropdown element and then click a single record in it if that's what you're trying to do, in your case it looks like it is the span within the highlighted button element, so you can do something like the following:

driver.findElement(By.id("homepages_dropdown")).click();
driver.findElement(By.xpath("//li//a[@id='homepages_item_AccountManagerDashboard']").click();

The above statements will click the dropdown then click the element with the id of homepages_item_AccountManagerDashboard.

You can also create a function that clicks any li of based off of a parameter you pass into a method you create, consider this if you may select many options in your dropdown.

public void SelectItem(string itemText)
{
    var dropdownElement = driver.findElement(By.id("homepages_dropdown"));
    var selectionItem = driver.findElement(By.xpath("//li[text()='" + itemText + "']");
    dropdownElement.Click();
    selectionItem.Click();
}

This is only really a valid option if you are working through the Page Object Model, but it's the best way to make things work consistently long term.


问:
Q:How to if contidion from json on React in one component?
I want to make the type of product to add and hide things, can I use only one component because I do it right now with two. I have an if that renders ProductNew and ProductOld. Is it possible to make the differences in one compartment or not?

This is the json:

```<code>{
"products": {
    "product": {
        "type": "new",
        "new": {
            "text": "Some text..."
        },
        "attr": {
            "price": "20"
        }
    },
    "product2": {
        "type": "old",
        "attr": {
            "price": "10"
        }
    }
}
</code>```

}

答:
It is possible, yes. Just pass the type as a property into your single component and then move the if statements into that.

So the calling code would look like

```<code><YourComponent type="{this.props.type}" />
</code>```

and the component would have, for example

```<code><div>
{this.props.type == "New" ?
    <span>New Stuff</span> :
    <span>Old Stuff</span>
}
</div>
</code>```

if you don't want anything in the old then just use

```<code><div>
{this.props.type == "New" ?
    <span>New Stuff</span> :
    null
}
</div>
</code>```

Body:
I want to make the type of product to add and hide things, can I use only one component because I do it right now with two. I have an if that renders ProductNew and ProductOld. Is it possible to make the differences in one compartment or not?

This is the json:

{
"products": {
    "product": {
        "type": "new",
        "new": {
            "text": "Some text..."
        },
        "attr": {
            "price": "20"
        }
    },
    "product2": {
        "type": "old",
        "attr": {
            "price": "10"
        }
    }
}

}

Body:
It is possible, yes. Just pass the type as a property into your single component and then move the if statements into that.

So the calling code would look like

<YourComponent type="{this.props.type}" />

and the component would have, for example

<div>
{this.props.type == "New" ?
    <span>New Stuff</span> :
    <span>Old Stuff</span>
}
</div>

if you don't want anything in the old then just use

<div>
{this.props.type == "New" ?
    <span>New Stuff</span> :
    null
}
</div>


问:
pg.connect not a function?
There appears to be a lot of documentation (e.g. https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js, but also elsewhere including this site) indicating that the proper method of connecting with the pg.js Node package is using pg.connect.  However, I attempted (after previous problems with my actual code) to test by using the exact code shown on the aforementioned Heroku documentation:

```<code>var pg = require('pg');

pg.defaults.ssl = true;
pg.connect(process.env.DATABASE_URL, function(err, client) {
  if (err) throw err;
  console.log('Connected to postgres! Getting schemas...');

  client
    .query('SELECT table_schema,table_name FROM information_schema.tables;')
    .on('row', function(row) {
      console.log(JSON.stringify(row));
    });
});
</code>```

And I got the error message "pg.connect is not a function".  What is going on, and how do I fix it?

答:
pg: postgresql => (https://www.npmjs.com/package/pg)

⚠ pg.connect is deprecated since version 6.3 ❌

BE CAREFUL : Instead there is another method called pool

Here is how you can set up node-postgres easily with express.

```<code>const pg        = require('pg');
const express   = require('express');
const app       = express();

const config = {
    user: 'postgres',
    database: 'YOURDBNAME',
    password: 'YOURPASSWORD',
    port: 5432                  //Default port, change it if needed
};

// pool takes the object above -config- as parameter
const pool = new pg.Pool(config);

app.get('/', (req, res, next) => {
   pool.connect(function (err, client, done) {
       if (err) {
           console.log("Can not connect to the DB" + err);
       }
       client.query('SELECT * FROM GetAllStudent()', function (err, result) {
            done();
            if (err) {
                console.log(err);
                res.status(400).send(err);
            }
            res.status(200).send(result.rows);
       })
   })
});

app.listen(4000, function () {
    console.log('Server is running on port 4000');
});
</code>```

Title: pg.connect not a function?

Body:
There appears to be a lot of documentation (e.g. https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js, but also elsewhere including this site) indicating that the proper method of connecting with the pg.js Node package is using pg.connect.  However, I attempted (after previous problems with my actual code) to test by using the exact code shown on the aforementioned Heroku documentation:

var pg = require('pg');

pg.defaults.ssl = true;
pg.connect(process.env.DATABASE_URL, function(err, client) {
  if (err) throw err;
  console.log('Connected to postgres! Getting schemas...');

  client
    .query('SELECT table_schema,table_name FROM information_schema.tables;')
    .on('row', function(row) {
      console.log(JSON.stringify(row));
    });
});

And I got the error message "pg.connect is not a function".  What is going on, and how do I fix it?

Body:
pg: postgresql => (https://www.npmjs.com/package/pg)

⚠ pg.connect is deprecated since version 6.3 ❌

BE CAREFUL : Instead there is another method called pool

Here is how you can set up node-postgres easily with express.

const pg        = require('pg');
const express   = require('express');
const app       = express();

const config = {
    user: 'postgres',
    database: 'YOURDBNAME',
    password: 'YOURPASSWORD',
    port: 5432                  //Default port, change it if needed
};

// pool takes the object above -config- as parameter
const pool = new pg.Pool(config);

app.get('/', (req, res, next) => {
   pool.connect(function (err, client, done) {
       if (err) {
           console.log("Can not connect to the DB" + err);
       }
       client.query('SELECT * FROM GetAllStudent()', function (err, result) {
            done();
            if (err) {
                console.log(err);
                res.status(400).send(err);
            }
            res.status(200).send(result.rows);
       })
   })
});

app.listen(4000, function () {
    console.log('Server is running on port 4000');
});


问:
Is it possible to repeat a match in a grep regexp?
I am using this:

```<code>grep '\s[A-Z]+\s[A-Z]+\s' file.txt -Po
</code>```

Which will match

```<code> ABC DE
 AB AB
 DEF GHIFOO
</code>```

etc

What I want to do is something like

```<code>grep '\s([A-Z]+)\s%1\s' file.txt -Po
</code>```

to only match

```<code> AB AB
 BC BC
 DDD DDD
</code>```

etc.

I can't work out if it's even possible, let alone how.  Is it?

Thanks

答:
The first captured group should be specified as \1 not as %1:

Sample file.txt:

```<code>AA AB
AB AB
BC BC
DDD DDD
NN WN
</code>```

Consider the updated regex patten:

```<code>grep -Po '\b([A-Z]+)\s\1\s*' file.txt
</code>```

The output:

```<code>AB AB
BC BC
DDD DDD
</code>```

Bonus approach for opposite action:

```<code>grep -Po '\b([A-Z]+)\s(?!\1)[A-Z]+\s*' file.txt
</code>```

The output:

```<code>AA AB
NN WN
</code>```

Body:
I am using this:

grep '\s[A-Z]+\s[A-Z]+\s' file.txt -Po

Which will match

 ABC DE
 AB AB
 DEF GHIFOO

etc

What I want to do is something like

grep '\s([A-Z]+)\s%1\s' file.txt -Po

to only match

 AB AB
 BC BC
 DDD DDD

etc.

I can't work out if it's even possible, let alone how.  Is it?

Thanks

Body:
The first captured group should be specified as \1 not as %1:

Sample file.txt:

AA AB
AB AB
BC BC
DDD DDD
NN WN

Consider the updated regex patten:

grep -Po '\b([A-Z]+)\s\1\s*' file.txt

The output:

AB AB
BC BC
DDD DDD

Bonus approach for opposite action:

grep -Po '\b([A-Z]+)\s(?!\1)[A-Z]+\s*' file.txt

The output:

AA AB
NN WN


问:
Python - Search multiple columns for string to set categorical variable value
I am very new to Python and Pandas, and am trying to use it for a statistical analysis of a very large dataset (10 million cases) because the other options (SPSS and R) are unable to handle the dataset on the authorized hardware.

In this analysis, I need to search a range of columns (30 to be exact) row-wise to extract individual strings (about 200 are possible, not sure how many will actually be present in the dataset) and then create a categorical variable for each string.

The data looks like this

```<code>  Dx1     Dx2     Dx3   etc...
  001     234     456
  231     001     444
  245     777     001
</code>```

What is needed is

```<code>Dx1     Dx2     Dx3  Var001   Var234  Var456  Var231   etc..
001     234     456  True     True    True    False
231     001     444  True     False   False   True
245     777     001  True     False   False   False
</code>```

Any thoughts on how to do this?

df.dtypes shows

```<code>AGE                      int64
DISPUNIFORM              int64
DRG                      int64
DRGVER                   int64
Readmit_30D              int64
DXCCS1                   int64
DXCCS2                   int64
DXCCS3                   int64
DXCCS4                   int64
...on to DXCCS30
</code>```

答:
Use get_dummies with max, convert to bool and last join to original:

```<code>df = (df.join(pd.get_dummies(df, prefix_sep='', prefix='')
                .max(level=0, axis=1)
                .astype(bool)
                .add_prefix('Var')))
print (df)

   Dx1  Dx2  Dx3  Var001  Var231  Var245  Var234  Var777  Var444  Var456
0  001  234  456    True   False   False    True   False   False    True
1  231  001  444    True    True   False   False   False    True   False
2  245  777  001    True   False    True   False    True   False   False
</code>```

Body:
I am very new to Python and Pandas, and am trying to use it for a statistical analysis of a very large dataset (10 million cases) because the other options (SPSS and R) are unable to handle the dataset on the authorized hardware.

In this analysis, I need to search a range of columns (30 to be exact) row-wise to extract individual strings (about 200 are possible, not sure how many will actually be present in the dataset) and then create a categorical variable for each string.

The data looks like this

  Dx1     Dx2     Dx3   etc...
  001     234     456
  231     001     444
  245     777     001

What is needed is

Dx1     Dx2     Dx3  Var001   Var234  Var456  Var231   etc..
001     234     456  True     True    True    False
231     001     444  True     False   False   True
245     777     001  True     False   False   False

Any thoughts on how to do this?

df.dtypes shows

AGE                      int64
DISPUNIFORM              int64
DRG                      int64
DRGVER                   int64
Readmit_30D              int64
DXCCS1                   int64
DXCCS2                   int64
DXCCS3                   int64
DXCCS4                   int64
...on to DXCCS30

Body:
Use get_dummies with max, convert to bool and last join to original:

df = (df.join(pd.get_dummies(df, prefix_sep='', prefix='')
                .max(level=0, axis=1)
                .astype(bool)
                .add_prefix('Var')))
print (df)

   Dx1  Dx2  Dx3  Var001  Var231  Var245  Var234  Var777  Var444  Var456
0  001  234  456    True   False   False    True   False   False    True
1  231  001  444    True    True   False   False   False    True   False
2  245  777  001    True   False    True   False    True   False   False


问:
Change input text value in before submitting form
I'm trying to change the value of my input text field before submitting the form using jQuery like this:

```<code><form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
    var value = $("#autocompleteform").val();
    value = value.substr(0, value.indexOf(' '));
    if (!isNan(value) && !empty(value)) {
        $("#autocompleteform").val(value);
        alert($("#autocompleteform").val());
        return true;
    } else {
        alert("Invalid Postcode");
        return false;
    }
});
</script>
</code>```

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

```<code> old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";
</code>```

答:
You submit the form before you change the value. You have to submit the form using jQuery, after you change the value.

Change the submit button to link to jquery function, change all you have to change and then submit form using:

```<code>$("#formId").submit();
</code>```

Body:
I'm trying to change the value of my input text field before submitting the form using jQuery like this:

<form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

 old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";

Body:
You submit the form before you change the value. You have to submit the form using jQuery, after you change the value.

Change the submit button to link to jquery function, change all you have to change and then submit form using:

$("#formId").submit();


问:
How to release pst file after creating it using Redemption API?
I am simply converting a list of message files to a combined pst. Below is my code:

```<code>RDOSession pstSession = new RDOSession();
RDOPstStore store = null;
var pstPath = "D:\\test\\combined.pst";
store = pstSession.LogonPstStore(pstPath, 1, "combinedPST");
RDOMail rdo_Mail =
   pstSession.GetMessageFromMsgFile(dr["FullPathOfMessageFile"].ToString());
rdo_Mail.CopyTo(store.IPMRootFolder);
rdo_Mail.Save();
store.Save();
pstSession.Logoff();
</code>```

This is a windows form application. Running above code creates a file combined.pst in the test folder. When I try to open this pst in outlook, outlook prompts that this pst is currently being used by another process. After I close my win from application, pst can be loaded.
I think redemption API is locking the created PST. What am I missing? What other object do I need to dispose?

答:
PST provider keeps a PST file referenced and loaded for 30 minutes for the performance reasons. Or until the PST provider dll itself gets unloaded (e.g. when the host process terminates).
You might want to play with the registry key mentioned in http://support.microsoft.com/Default.aspx?kbid=222328 </p>

Body:
I am simply converting a list of message files to a combined pst. Below is my code:

RDOSession pstSession = new RDOSession();
RDOPstStore store = null;
var pstPath = "D:\\test\\combined.pst";
store = pstSession.LogonPstStore(pstPath, 1, "combinedPST");
RDOMail rdo_Mail =
   pstSession.GetMessageFromMsgFile(dr["FullPathOfMessageFile"].ToString());
rdo_Mail.CopyTo(store.IPMRootFolder);
rdo_Mail.Save();
store.Save();
pstSession.Logoff();

This is a windows form application. Running above code creates a file combined.pst in the test folder. When I try to open this pst in outlook, outlook prompts that this pst is currently being used by another process. After I close my win from application, pst can be loaded.
I think redemption API is locking the created PST. What am I missing? What other object do I need to dispose?


问:
Eureka : cannot convert value of type 'BaseRow?' to specified type 'CustomPushRow?'
I have use Eureka for my form but i am facing an issues. I setup the form using these code

```<code>form +++ Section("Add Event")
        <<< TextRow("Event"){ row in
            row.title = "Event"
            row.placeholder = "Enter Event Name Here"
        }
        <<< DateRow("Date"){
            $0.title = "Date"
            $0.value = selectedDate

        }
        <<< TimeRow("Time"){
            $0.title = "Time"
            $0.value = selectedDate

    }
    let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "eventLocation") as! EventLocationViewController

    form +++ Section("Location")
        <<< CustomPushRow<EventLocationViewController>(){
            $0.title = "Location"
            $0.presentationMode = .segueName(segueName: "eventLocation" ,controllerProvider: locationSearchTable, onDismiss: nil)

    }
</code>```

here the custom push row class

```<code>public final class CustomPushRow<T: Equatable>: SelectorRow<PushSelectorCell<T>, SelectorViewController<T>>, RowType {

public required init(tag: String?) {
    super.init(tag: tag)
    presentationMode = .show(controllerProvider: ControllerProvider.callback {
        return SelectorViewController<T>(){ _ in }
        }, onDismiss: { vc in
            print("On Dimiss")
            _ = vc.navigationController?.popViewController(animated: true)
    })
}

}
</code>```

and when i wanna change the value of the form i use this method to change

```<code>    let eventName : TextRow? = form.rowBy(tag:"Event")
    eventName?.value = "asdasadsds"
</code>```

but when i wanna change the custom push row i am having this issues cannot convert value of type 'BaseRow?' to specified type 'CustomPushRow?' when i do this

```<code>   let row : CustomPushRow? = form.rowBy(tag: "Location")
</code>```

How can i change the value of the CustomPushRow

答:
Try taking your info a different way (a tip I got from Swift: How to get form values using Eureka form builder? helped me with another "cannot convert value of...." issue)

To READ the value on a row that gives you the error message:

Be sure to set tags on all your elements ($0.tag = "whatever")

instead of

let row : CustomPushRow? = form.rowBy(tag: "Location")

use

```<code>let dict = self.form.values(includeHidden: true)
</code>```

Then you can see the value with something like

```<code>print(dict["whatever"])
</code>```

Now, the other part of your question asked about SETTING the value, which is a different thing in Eureka.

From the docs (https://github.com/xmartlabs/Eureka#how-to-set-the-form-values-using-a-dictionary):

How to set the form values using a dictionary

Invoking setValues(values: [String: Any?]) which is exposed by Form class.

For example:

```<code>form.setValues(["IntRowTag": 8, "TextRowTag": "Hello world!", "PushRowTag": Company(name:"Xmartlabs")])
</code>```

Where "IntRowTag", "TextRowTag", "PushRowTag" are row tags (each one uniquely identifies a row) and 8, "Hello world!", Company(name:"Xmartlabs") are the corresponding row value to assign.

Body:
I have use Eureka for my form but i am facing an issues. I setup the form using these code

form +++ Section("Add Event")
        <<< TextRow("Event"){ row in
            row.title = "Event"
            row.placeholder = "Enter Event Name Here"
        }
        <<< DateRow("Date"){
            $0.title = "Date"
            $0.value = selectedDate

        }
        <<< TimeRow("Time"){
            $0.title = "Time"
            $0.value = selectedDate

    }
    let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "eventLocation") as! EventLocationViewController

    form +++ Section("Location")
        <<< CustomPushRow<EventLocationViewController>(){
            $0.title = "Location"
            $0.presentationMode = .segueName(segueName: "eventLocation" ,controllerProvider: locationSearchTable, onDismiss: nil)

    }

here the custom push row class

public final class CustomPushRow<T: Equatable>: SelectorRow<PushSelectorCell<T>, SelectorViewController<T>>, RowType {

public required init(tag: String?) {
    super.init(tag: tag)
    presentationMode = .show(controllerProvider: ControllerProvider.callback {
        return SelectorViewController<T>(){ _ in }
        }, onDismiss: { vc in
            print("On Dimiss")
            _ = vc.navigationController?.popViewController(animated: true)
    })
}

}

and when i wanna change the value of the form i use this method to change

    let eventName : TextRow? = form.rowBy(tag:"Event")
    eventName?.value = "asdasadsds"

but when i wanna change the custom push row i am having this issues cannot convert value of type 'BaseRow?' to specified type 'CustomPushRow?' when i do this

   let row : CustomPushRow? = form.rowBy(tag: "Location")

How can i change the value of the CustomPushRow

Body:
Try taking your info a different way (a tip I got from Swift: How to get form values using Eureka form builder? helped me with another "cannot convert value of...." issue)

To READ the value on a row that gives you the error message:

Be sure to set tags on all your elements ($0.tag = "whatever")

instead of

let row : CustomPushRow? = form.rowBy(tag: "Location")

use

let dict = self.form.values(includeHidden: true)

Then you can see the value with something like

print(dict["whatever"])

Now, the other part of your question asked about SETTING the value, which is a different thing in Eureka.

From the docs (https://github.com/xmartlabs/Eureka#how-to-set-the-form-values-using-a-dictionary):

How to set the form values using a dictionary

Invoking setValues(values: [String: Any?]) which is exposed by Form class.

For example:

form.setValues(["IntRowTag": 8, "TextRowTag": "Hello world!", "PushRowTag": Company(name:"Xmartlabs")])

Where "IntRowTag", "TextRowTag", "PushRowTag" are row tags (each one uniquely identifies a row) and 8, "Hello world!", Company(name:"Xmartlabs") are the corresponding row value to assign.


问:
JQuery, show an element based on 2 attribute conditions
I was wondering if anyone knew of a way of selecting a DIV based on 2 of its attributes meeting a certain criteria using JQuery?  Say for example I have a variable called 'time', now if data-in and data-out (below) are 'seconds', how would you show the relevant DIV based on the 'time' variable.  Assume all the DIVs below are hidden by CSS to start with.

For example if 'time'=15 it would show slide1 because it's between data-in (10) and data-out (20), and if 'time'=73 it would show slide4 (between data-in 70 and data-out 80).

Here is the code (very basic),

```<code><div id="slide1" data-in="10" data-out="20" name="slide1"></div>
<div id="slide2" data-in="30" data-out="40" name="slide2"></div>
<div id="slide3" data-in="50" data-out="60" name="slide3"></div>
<div id="slide4" data-in="70" data-out="80" name="slide4"></div>
<div id="slide5" data-in="90" data-out="100" name="slide5"></div>
</code>```

Thanks in advance.

答:
You could do it like this using filter()(docs) :

Example: http://jsfiddle.net/3vDcb/4/

```<code>var time = 35;

$('div[name^=slide]').filter(function() {
    var data_in = $(this).attr('data-in');
    var data_out = $(this).attr('data-out');

    return time >= data_in && time <= data_out;
}).show();
</code>```

EDIT: Fixed an error due to gaps in ranges.

ContentLicense: CC BY-SA 2.5

Body:
I was wondering if anyone knew of a way of selecting a DIV based on 2 of its attributes meeting a certain criteria using JQuery?  Say for example I have a variable called 'time', now if data-in and data-out (below) are 'seconds', how would you show the relevant DIV based on the 'time' variable.  Assume all the DIVs below are hidden by CSS to start with.

For example if 'time'=15 it would show slide1 because it's between data-in (10) and data-out (20), and if 'time'=73 it would show slide4 (between data-in 70 and data-out 80).

Here is the code (very basic),

Thanks in advance.

Body:
You could do it like this using filter()(docs) :

Example: http://jsfiddle.net/3vDcb/4/

var time = 35;

$('div[name^=slide]').filter(function() {
    var data_in = $(this).attr('data-in');
    var data_out = $(this).attr('data-out');

    return time >= data_in && time <= data_out;
}).show();

EDIT: Fixed an error due to gaps in ranges.


问:
Keras multiclass classificator error with validation data and validation labels: Input arrays should have the same number of samples as target arrays
I am trying to build a multi-class classificator for 24 classes with Keras using VGG16 bottleneck features and a small fully connected model on top.

At first I was trying to follow this tutorial: https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html adapting it to multiclass, then I got the error and tried to use this other tutorial's code: http://www.codesofinterest.com/2017/08/bottleneck-features-multi-class-classification-keras.html and got the exact same error. I cannot figure out what the problem is!

The error I get is : " ValueError: Input arrays should have the same number of samples as target arrays. Found 12768 input samples and 12782 target samples. "

Basically I have two folders, train and validation. The train folder has 52992 png images, the validation folder as 12782 png images. My batch size is 16.

Here is the code in save_bottleneck_features() where I save the validation data (this function is called before the train_top_model() function):

```<code>generator = datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical',
    shuffle=False)

nb_validation_samples = len(generator.filenames)

predict_size_validation = int(
    math.ceil(nb_validation_samples / batch_size))

bottleneck_features_validation = model.predict_generator(
    generator, predict_size_validation)

np.save('bottleneck_features_validation.npy',
        bottleneck_features_validation)
</code>```

And here is the code in train_top_model() where I calculate the validation labels:

```<code>generator_top = datagen_top.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode= 'categorical',
    shuffle=False)

nb_validation_samples = len(generator_top.filenames)

validation_data = np.load('bottleneck_features_validation.npy')

validation_labels = generator_top.classes
validation_labels = np.array(
     [0] * (nb_validation_samples / 2) + [1] * (nb_validation_samples / 2))
validation_labels = to_categorical(
   validation_labels, num_classes=num_classes)
</code>```

print predict_size_validation prints 798

print nb_validation_samples prints 12782

print len(validation_data) prints 12768

print len(validation_labels) prints 12782

Train data and train labels are calculated in the same way but they are OK.

I think that maybe the problem is with predict_size_validation, and that 12782 is not divisible by 16.

Thank you!!!

答:
In python 2, which I assume you are using given the comments, the division of two integers gives the integer division by default. This means that 12782 / 16 == 798 (in python 3, this is equivalent to 12782 // 16) instead of 12782 / 16 == 798.875 as is the case in python 3.

In order to resolve this issue, you should make sure that one of the numbers in the division is a float in order to get the correct behaviour, e.g.

```<code>import math

predict_size_validation = int(math.ceil(nb_validation_samples / float(batch_size)))
</code>```

Alternatively, you can use the __future__ module to get python 3 behaviour, i.e.

```<code>import math
from __future__ import division

predict_size_validation = int(math.ceil(nb_validation_samples / batch_size))
</code>```

Yet another solution is to rely on the integer division to do the computation (instead of relying on math.ceil):

```<code>predict_size_validation = nb_validation_samples // batch_size
if nb_validation_samples % batch_size != 0:
    predict_size_validation += 1
</code>```

For more information on the python 2 floating point division, see this answer

Body:
I am trying to build a multi-class classificator for 24 classes with Keras using VGG16 bottleneck features and a small fully connected model on top.

At first I was trying to follow this tutorial: https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html adapting it to multiclass, then I got the error and tried to use this other tutorial's code: http://www.codesofinterest.com/2017/08/bottleneck-features-multi-class-classification-keras.html and got the exact same error. I cannot figure out what the problem is!

The error I get is : " ValueError: Input arrays should have the same number of samples as target arrays. Found 12768 input samples and 12782 target samples. "

Basically I have two folders, train and validation. The train folder has 52992 png images, the validation folder as 12782 png images. My batch size is 16.

Here is the code in save_bottleneck_features() where I save the validation data (this function is called before the train_top_model() function):

generator = datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical',
    shuffle=False)

nb_validation_samples = len(generator.filenames)

predict_size_validation = int(
    math.ceil(nb_validation_samples / batch_size))

bottleneck_features_validation = model.predict_generator(
    generator, predict_size_validation)

np.save('bottleneck_features_validation.npy',
        bottleneck_features_validation)

And here is the code in train_top_model() where I calculate the validation labels:

generator_top = datagen_top.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode= 'categorical',
    shuffle=False)

nb_validation_samples = len(generator_top.filenames)

validation_data = np.load('bottleneck_features_validation.npy')

validation_labels = generator_top.classes
validation_labels = np.array(
     [0] * (nb_validation_samples / 2) + [1] * (nb_validation_samples / 2))
validation_labels = to_categorical(
   validation_labels, num_classes=num_classes)

print predict_size_validation prints 798

print nb_validation_samples prints 12782

print len(validation_data) prints 12768

print len(validation_labels) prints 12782

Train data and train labels are calculated in the same way but they are OK.

I think that maybe the problem is with predict_size_validation, and that 12782 is not divisible by 16.

Thank you!!!

Body:
In python 2, which I assume you are using given the comments, the division of two integers gives the integer division by default. This means that 12782 / 16 == 798 (in python 3, this is equivalent to 12782 // 16) instead of 12782 / 16 == 798.875 as is the case in python 3.

In order to resolve this issue, you should make sure that one of the numbers in the division is a float in order to get the correct behaviour, e.g.

import math

predict_size_validation = int(math.ceil(nb_validation_samples / float(batch_size)))

Alternatively, you can use the __future__ module to get python 3 behaviour, i.e.

import math
from __future__ import division

predict_size_validation = int(math.ceil(nb_validation_samples / batch_size))

Yet another solution is to rely on the integer division to do the computation (instead of relying on math.ceil):

predict_size_validation = nb_validation_samples // batch_size
if nb_validation_samples % batch_size != 0:
    predict_size_validation += 1

For more information on the python 2 floating point division, see this answer


问:
JSTL not recognized in JSP after adding jar
I added jstl-1.2.jar to my lib folder, then I included:

```<code><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
</code>```

on top of my JSP file and still It says `Unknown tag (c:forEach).

welcome.jsp

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <c:forEach>
 </c:forEach>
</body>
</html>
</code>```

Project construction HERE

答:
1.Use only jstl-1.2.jar

2.Try to get some items to iterate, for example:

```<code><c:forEach items="${requestScope.list}" var="item">
</c:forEach>
</code>```

Body:
I added jstl-1.2.jar to my lib folder, then I included:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

on top of my JSP file and still It says `Unknown tag (c:forEach).

welcome.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

 <c:forEach>
 </c:forEach>

Project construction HERE

Body:
1.Use only jstl-1.2.jar

2.Try to get some items to iterate, for example:

<c:forEach items="${requestScope.list}" var="item">
</c:forEach>


问:
How to choose starting screen of react-native app based on redux state?
There are several screens in my react-native app that user should go through sequentially: first they should login, then set pin code for the app, then select a city and only then can they use main functionality. On the next start user should go straight to the Main screen.

I'm managing state with redux and keep data in async storage on device. When the app starts data is loaded from storage and based on it user should be sent to some screen or other.

The question is: how can I do this, when and where in the app lifecycle?

Let's look at this example: https://github.com/react-community/react-navigation/tree/master/examples/ReduxExample.

It generates initial navigation state, but does so statically:

```<code>// Start with two routes: The Main screen, with the Login screen on top.
const firstAction = AppNavigator.router.getActionForPathAndParams('Main');
const tempNavState = AppNavigator.router.getStateForAction(firstAction);
const secondAction = AppNavigator.router.getActionForPathAndParams('Login');
const initialNavState = AppNavigator.router.getStateForAction(
  secondAction,
  tempNavState
);
</code>```

What should I change in that example if I want to load isLoggedIn flag from device storage and navigate user accordingly?

答:
I had the same issue some time ago, I will tell you how I solved it:
In my first screen called App.js I put redux configuration:

```<code>const App = () => (
  <Provider store={store}>
    <View style={{ flex: 1 }}>
        <Main />
    </View>
  </Provider>
)
</code>```

In Main.js:

```<code>class Main extends Component {
    constructor() {
        super();
        this.state = ({
            initial_data_fetched: false
        })
    }
    componentDidMount() {
        this.props.isUserAthenticated();
    }

    componentWillReceiveProps(next) {
        if (next.token !== '') {
            if (!this.state.initial_data_fetched) {
                this.props.loadUserData(next.token);
            }
            this.setState({ initial_data_fetched: true })
        }
    }

    render() {
        if (this.props.processing_auth) {
            return (<Spinner size="small" />)
        } else {
            return (<Router authenticated={this.props.authenticated}/>)
        }
    }
}

const mapStateToProps = ({ auth }) => {
    const { processing_auth, authenticated, token } = auth;
    return { processing_auth, authenticated, token };
};

export default connect(mapStateToProps, { isUserAthenticated})(Main);
</code>```

Finally, with react-native-router-flux I choose if show the login component, or the initial component. That is my Router.js file:

```<code>const RouterComponent = ({ authenticated }) => {

return (
    <Router>
        <Overlay>
            <Stack key="root" hideNavBar>
                <Stack key="authentication" >
                    <Scene key="login"
                        component={LoginForm}
                        hideNavBar
                        initial={!authenticated} />
                </Stack>

                <Stack
                    back={false}
                    key="main"
                    initial={authenticated}
                    type={ActionConst.RESET}>

                    <Lightbox key="mainScreen">
                        <Scene
                            hideNavBar
                            key="mainScreen"
                            component={Parking}
                            initial={authenticated}
                        />

                </Stack>
            </Stack>
        </Overlay>
    </Router>
);
};

export default RouterComponent;
</code>```

Hope it helps you!!

Body:
There are several screens in my react-native app that user should go through sequentially: first they should login, then set pin code for the app, then select a city and only then can they use main functionality. On the next start user should go straight to the Main screen.

I'm managing state with redux and keep data in async storage on device. When the app starts data is loaded from storage and based on it user should be sent to some screen or other.

The question is: how can I do this, when and where in the app lifecycle?

Let's look at this example: https://github.com/react-community/react-navigation/tree/master/examples/ReduxExample.

It generates initial navigation state, but does so statically:

// Start with two routes: The Main screen, with the Login screen on top.
const firstAction = AppNavigator.router.getActionForPathAndParams('Main');
const tempNavState = AppNavigator.router.getStateForAction(firstAction);
const secondAction = AppNavigator.router.getActionForPathAndParams('Login');
const initialNavState = AppNavigator.router.getStateForAction(
  secondAction,
  tempNavState
);

What should I change in that example if I want to load isLoggedIn flag from device storage and navigate user accordingly?

Body:
I had the same issue some time ago, I will tell you how I solved it:
In my first screen called App.js I put redux configuration:

const App = () => (
  <Provider store={store}>
    <View style={{ flex: 1 }}>
        <Main />
    </View>
  </Provider>
)

In Main.js:

class Main extends Component {
    constructor() {
        super();
        this.state = ({
            initial_data_fetched: false
        })
    }
    componentDidMount() {
        this.props.isUserAthenticated();
    }

    componentWillReceiveProps(next) {
        if (next.token !== '') {
            if (!this.state.initial_data_fetched) {
                this.props.loadUserData(next.token);
            }
            this.setState({ initial_data_fetched: true })
        }
    }

    render() {
        if (this.props.processing_auth) {
            return (<Spinner size="small" />)
        } else {
            return (<Router authenticated={this.props.authenticated}/>)
        }
    }
}

const mapStateToProps = ({ auth }) => {
    const { processing_auth, authenticated, token } = auth;
    return { processing_auth, authenticated, token };
};

export default connect(mapStateToProps, { isUserAthenticated})(Main);

Finally, with react-native-router-flux I choose if show the login component, or the initial component. That is my Router.js file:

const RouterComponent = ({ authenticated }) => {

return (
    <Router>
        <Overlay>
            <Stack key="root" hideNavBar>
                <Stack key="authentication" >
                    <Scene key="login"
                        component={LoginForm}
                        hideNavBar
                        initial={!authenticated} />
                </Stack>

                <Stack
                    back={false}
                    key="main"
                    initial={authenticated}
                    type={ActionConst.RESET}>

                    <Lightbox key="mainScreen">
                        <Scene
                            hideNavBar
                            key="mainScreen"
                            component={Parking}
                            initial={authenticated}
                        />

                </Stack>
            </Stack>
        </Overlay>
    </Router>
);
};

export default RouterComponent;

Hope it helps you!!


问:
not read the file. htaccess
I would like to help me please if it is in their hands.

And in advance thank you who have read my problem.

The problem is this:

In my local server (localhost) I did not read the file. htaccess, I checked my httpd.conf and rewrite module is active, since it is not the pad

So this:

```<code>Rewrite_module LoadModule modules / mod_rewrite.so
</code>```

But still I do not read the apache server

I have also seen that the AllowOverride None deny nor do I read, I've tried putting # AllowOverride None but I do not read.

I have two files:

First file: index.php, this file I have two results

and second: ver.php

And when I click on index.php do I send it to:

```<code>ver.php? idmini = 1

http://pablodelriob.kodingen.com/mininoticias2/ver.php?idmini=1
</code>```

And I can not run the url friendly. htaccess

To leave my doubt also increased all the files on a server on the Internet, the address is at:

http://pablodelriob.kodingen.com/mininoticias2

The contents of my file. htaccess is:

```<code>Mod_rewrite.c> <IfModule
# Options + FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteRule ^ view (.*) \. html $ ver.php? idmini = $ 1
</ IfModule>
</code>```

Be possible to help me?

Thanks for reading

答:
If you put garbage in your htaccess file, and you don't get a 500 error, AllowOverride is set to none in your base apache configuration.  It needs to be set to at least FileInfo to use rewrite in htaccess.

You mention adding "AllowOverride None", but this is exactly the opposite of what you want.

Title: not read the file. htaccess

Body:
I would like to help me please if it is in their hands.

And in advance thank you who have read my problem.

The problem is this:

In my local server (localhost) I did not read the file. htaccess, I checked my httpd.conf and rewrite module is active, since it is not the pad

So this:

Rewrite_module LoadModule modules / mod_rewrite.so

But still I do not read the apache server

I have also seen that the AllowOverride None deny nor do I read, I've tried putting # AllowOverride None but I do not read.

I have two files:

First file: index.php, this file I have two results

and second: ver.php

And when I click on index.php do I send it to:

ver.php? idmini = 1

http://pablodelriob.kodingen.com/mininoticias2/ver.php?idmini=1

And I can not run the url friendly. htaccess

To leave my doubt also increased all the files on a server on the Internet, the address is at:

http://pablodelriob.kodingen.com/mininoticias2

The contents of my file. htaccess is:

Mod_rewrite.c> <IfModule
# Options + FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteRule ^ view (.*) \. html $ ver.php? idmini = $ 1
</ IfModule>

Be possible to help me?

Thanks for reading


问:
Facebook: Test users for an unpublished page
Lets establish the constants first;

App pages are 720px or fluid wide.

Timeline apps are 810px wide.

To view an app as a timeline app you need to add it to a page.

Whilst testing/developing you want the page to be unpublished.

So to see that page and the app as a part/tab of that page any testers need to be admin for the page.

My problem is;

Some testers may be external, we don't want them Admins to the page.

We want to be able to show the app as a tab/app of a page in the 810px layout for signoff.

Is there a way to set different permissions for an unpublished page, as there are for apps.  i.e. Admin, Developer, tester if only to give them view permissions if nothing else?

答: CLOSING QUESTION. NOW OUT OF DATE AND NO LONGER RELEVANT.</p>


问:
Apache Camel: File Component IO exceptions
While using the file component to process a large queue of messages I am getting many errors like "Too many open files" and

```<code>org.apache.http.nio.reactor.IOReactorException: Failure opening selector
</code>```

What is a good approach to limit the amount of messages that is being processed to prevent any IO exceptions?

答:
You can use a seda queue to limit the total number of exchanges in a route that are concurrently processed.

```<code>from("direct:input")
    .to("seda:fileProcessor")
    .to("direct:furtherProcessing);

from("seda:fileProcessor?concurrentConsumers=100")
    .process(fileProcessor);
</code>```

You could also look at the throttle component, however this just limits the number of exchanges passing through the throttle for a given amount of time, rather than limiting the total number of exchanges being processed concurrently.

Note that it is also possible to increase the number of file descriptors open at any one time.  To do that on a linux system, check out this answer

Body:
While using the file component to process a large queue of messages I am getting many errors like "Too many open files" and

org.apache.http.nio.reactor.IOReactorException: Failure opening selector

What is a good approach to limit the amount of messages that is being processed to prevent any IO exceptions?

Body:
You can use a seda queue to limit the total number of exchanges in a route that are concurrently processed.

from("direct:input")
    .to("seda:fileProcessor")
    .to("direct:furtherProcessing);

from("seda:fileProcessor?concurrentConsumers=100")
    .process(fileProcessor);

You could also look at the throttle component, however this just limits the number of exchanges passing through the throttle for a given amount of time, rather than limiting the total number of exchanges being processed concurrently.

Note that it is also possible to increase the number of file descriptors open at any one time.  To do that on a linux system, check out this answer


问:
October CMS backend form field get backend username
How can I get the backend user's name and output it on the backend form field using a partial.

Thanks

答:
// Returns the signed in user
$user = BackendAuth::getUser();

// Returns the signed in user from a controller
$user = $this->user;


问:
get src value from multiple images and split to single variables
I am trying to get src value of some images but i will get it only from first one image.. is here way to get value from all images?</p>

```<code><div class="cube-box--cube active">
    <img class="cube-box--cube__img" src="
    {$basePath}/assets/img/animation/scenery2.jpg" alt="scenery2">

    <div class="white-cover"></div>
    <p class="cube-box--cube__text">
      <span class="fix-size">Electrostatics</span>
    Neutral
    </p>
</div>

<div class="cube-box--cube active">
    <img class="cube-box--cube__img" src="
    {$basePath}/assets/img/animation/scenery3.jpg" alt="scenery3">

    <div class="white-cover"></div>
    <p class="cube-box--cube__text">
      <span class="fix-size">Electrostatics</span>
    Neutral
    </p>
</div>

var imgSrc = $('.cube-box--cube').filter('.active').find("img").attr("src");
console.log(imgSrc);
</code>```

答:
There are probably better ways to do it

```<code>var srcs = [ ];

$.each($('.cube-box--cube').filter('.active').find("img"), function() {
    srcs.push($(this).attr("src"));
});
</code>```

If you want to use map, you may need to:

```<code>...find("img").get().map(...
</code>```

Body:
I am trying to get src value of some images but i will get it only from first one image.. is here way to get value from all images?

      Electrostatics
    Neutral

      Electrostatics
    Neutral

var imgSrc = $('.cube-box--cube').filter('.active').find("img").attr("src");
console.log(imgSrc);

Body:
There are probably better ways to do it

var srcs = [ ];

$.each($('.cube-box--cube').filter('.active').find("img"), function() {
    srcs.push($(this).attr("src"));
});

If you want to use map, you may need to:

...find("img").get().map(...


答:
To accomplish that you need to:

Prevent form submission

Change input value

submit form with jquery $('#form').submit()

Prevent form submission with e.preventDefault() right inside your callback handler

Title: Change input text value in before submitting form

Body:
I'm trying to change the value of my input text field before submitting the form using jQuery like this:

<form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

 old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";


问:
What does Tokens do and why they need to be created in C++ programming?
I am reading a book (Programming Principles and Practice by Bjarne Stroustrup).

In which he introduce Tokens:

“A token is a sequence of characters that represents something we consider a unit, such as a number or an operator. That’s the way a C++ compiler deals with its source. Actually, “tokenizing” in some form or another is the way most analysis of text starts.”

```<code>class Token {
public:
    char kind;
    double value;
};
</code>```

I do get what they are but he never explains this in detail and its quite confusing to me.

答:
Broadly speaking, a compiler will run multiple operations on a given source code, before converting it into a binary format. One of the first stages is running a tokenizer, where the contents of a source file are converted to Tokens, which are units understood by the compiler. For example, if you write a statementint a, the tokenizer might create a structure to store this information.

```<code>Type: integer
Identifier: A
Reserved Word: No
Line number: 10
</code>```

This would be then referred to as a token, and most of the code in a source file will be broken down into similar structures.

Body:
I am reading a book (Programming Principles and Practice by Bjarne Stroustrup).

In which he introduce Tokens:

“A token is a sequence of characters that represents something we consider a unit, such as a number or an operator. That’s the way a C++ compiler deals with its source. Actually, “tokenizing” in some form or another is the way most analysis of text starts.”

class Token {
public:
    char kind;
    double value;
};

I do get what they are but he never explains this in detail and its quite confusing to me.

Body:
Broadly speaking, a compiler will run multiple operations on a given source code, before converting it into a binary format. One of the first stages is running a tokenizer, where the contents of a source file are converted to Tokens, which are units understood by the compiler. For example, if you write a statementint a, the tokenizer might create a structure to store this information.

Type: integer
Identifier: A
Reserved Word: No
Line number: 10

This would be then referred to as a token, and most of the code in a source file will be broken down into similar structures.


问:
Resuming a thread by using notifyAll
Take the Pausing a Thread example. If I use notifyAll instead of notify, is there any side effect, and is it necessary?

答: Using notifyAll as opposed to notify is important if you can have multiple parties waiting on the object. If only one thread ever waits, then there is no difference between calling notify vs notifyAll.</p>

Title: Resuming a thread by using notifyAll


问:
Jenkins pipeline not failing based on batch exit code
I am having trouble with a Jenkins pipeline that is not failing when a called batch file fails. I have checked the batch file, it returns a non-zero status code, but somehow this seems to be not considered. Does anyone of you have a hint for me?

desired pipeline

```<code>node {
  stage('1'){
    dir('_src') {
      bat 'call test.bat'
    }
  }
}
</code>```

Calling the batch in cmd window results in the following

```<code>>call test.bat
INFO: Started ...
ERROR
Press any key to continue . . .
>echo %ERRORLEVEL%
2
</code>```

I also used the following pipeline for testing

```<code>node {
  stage('1'){
    dir('_src') {
      bat '''call test.bat
      echo %ERRORLEVEL%'''
    }
  }
}
</code>```

... with this output

```<code>C:\_src>call test.bat
INFO: Started ...
ERROR
Press any key to continue . . .
2
</code>```

Still, the pipeline is not failing. Any ideas?

答: You only write an echo, not actually doing a return/ exit. Try to add a concrete Exit 0 or in your case Exit 2 in your script.

Body:
I am having trouble with a Jenkins pipeline that is not failing when a called batch file fails. I have checked the batch file, it returns a non-zero status code, but somehow this seems to be not considered. Does anyone of you have a hint for me?

desired pipeline

node {
  stage('1'){
    dir('_src') {
      bat 'call test.bat'
    }
  }
}

Calling the batch in cmd window results in the following

>call test.bat
INFO: Started ...
ERROR
Press any key to continue . . .
>echo %ERRORLEVEL%
2

I also used the following pipeline for testing

node {
  stage('1'){
    dir('_src') {
      bat '''call test.bat
      echo %ERRORLEVEL%'''
    }
  }
}

... with this output

C:\_src>call test.bat
INFO: Started ...
ERROR
Press any key to continue . . .
2

Still, the pipeline is not failing. Any ideas?


问:
custom value in custom attribute jquery select option
i have this select option html with custom attribute

```<code><select id='voucher_dealer' name='voucher_dealer' class='form-control'><option value=''>اختر موزع</option>
        @foreach($dealers as $dealer)
            <option dealername='awad' value='{{$dealer->id}}'>{{$dealer->dealer_name}}</option>
        @endforeach
</select>
</code>```

now i want to get the value of dealername i did this

```<code> $("#voucher_dealer").change(function(){
    var dealer = $(this).val();
    var dealername = $(this).attr("dealername");
    alert(dealername);
});
</code>```

i get undefined how i can get the value of the attribute dealername

答:
The issue is because the dealername attribute is on the selected option, not the select itself. Try this:

```<code>$("#voucher_dealer").change(function(){
  var dealer = $(this).val();
  var dealername = $(this).find('option:selected').attr("dealername");
  console.log(dealername);
});
</code>```

Note the use of find() here, and also console.log() over alert() for debugging purposes.

Body:
i have this select option html with custom attribute

<select id='voucher_dealer' name='voucher_dealer' class='form-control'><option value=''>اختر موزع</option>
        @foreach($dealers as $dealer)
            <option dealername='awad' value='{{$dealer->id}}'>{{$dealer->dealer_name}}</option>
        @endforeach
</select>

now i want to get the value of dealername i did this

 $("#voucher_dealer").change(function(){
    var dealer = $(this).val();
    var dealername = $(this).attr("dealername");
    alert(dealername);
});

i get undefined how i can get the value of the attribute dealername

Body:
The issue is because the dealername attribute is on the selected option, not the select itself. Try this:

$("#voucher_dealer").change(function(){
  var dealer = $(this).val();
  var dealername = $(this).find('option:selected').attr("dealername");
  console.log(dealername);
});

Note the use of find() here, and also console.log() over alert() for debugging purposes.


问:
Read entire database with sqlalchemy and dump as JSON
Django has the convenience manage.py command dumpdata which can be configured to dump an entire database as JSON.

At present I am confined to using sqlalchemy and I'd like to do the same thing:

Take as input a connection string like 'mysql+pymysql://user:pwd@localhost:3306/' and get the contents of the database as JSON (I don't require all the meta info that Django provides, but I won't mind).

I found this question elaborating how to dump SQLAlchemy objects to JSON and this from the sqlalchemy documentation outlining how to get all tablenames from a database:

```<code>meta = MetaData()
input_db = f'sqlite:///tmpsqlite'
engine = create_engine(input_db)
meta.reflect(bind=engine)
print(meta.tables)
</code>```

How do I retrieve all of the content of these tables and then convert them to JSON? Is there a built-in command in sqlalchemy similar to django's dumpdata functionality?

答:
Leaving my solution here for posterity:</p>

```<code>import json

def dump_sqlalchemy(output_connection_string,output_schema):
    """ Returns the entire content of a database as lists of dicts"""
    engine = create_engine(f'{output_connection_string}{output_schema}')
    meta = MetaData()
    meta.reflect(bind=engine)  # http://docs.sqlalchemy.org/en/rel_0_9/core/reflection.html
    result = {}
    for table in meta.sorted_tables:
        result[table.name] = [dict(row) for row in engine.execute(table.select())]
    return json.dumps(result)
</code>```

Body:
Django has the convenience manage.py command dumpdata which can be configured to dump an entire database as JSON.

At present I am confined to using sqlalchemy and I'd like to do the same thing:

Take as input a connection string like 'mysql+pymysql://user:pwd@localhost:3306/' and get the contents of the database as JSON (I don't require all the meta info that Django provides, but I won't mind).

I found this question elaborating how to dump SQLAlchemy objects to JSON and this from the sqlalchemy documentation outlining how to get all tablenames from a database:

meta = MetaData()
input_db = f'sqlite:///tmpsqlite'
engine = create_engine(input_db)
meta.reflect(bind=engine)
print(meta.tables)

How do I retrieve all of the content of these tables and then convert them to JSON? Is there a built-in command in sqlalchemy similar to django's dumpdata functionality?

Body:
Leaving my solution here for posterity:

import json

def dump_sqlalchemy(output_connection_string,output_schema):
    """ Returns the entire content of a database as lists of dicts"""
    engine = create_engine(f'{output_connection_string}{output_schema}')
    meta = MetaData()
    meta.reflect(bind=engine)  # http://docs.sqlalchemy.org/en/rel_0_9/core/reflection.html
    result = {}
    for table in meta.sorted_tables:
        result[table.name] = [dict(row) for row in engine.execute(table.select())]
    return json.dumps(result)


问:
Query 'any' value with 'where' in Rails
I have the following method:

```<code>def self.fetch_by_subcat(subcat_id, state)
  where(state: state).joins(:subcategories).where("subcategory_id = ? AND published = ?", subcat_id, true)
end
</code>```

The problem is that if my state is blank, I get back an empty array. So I would like to set my state argument to a default, something like 'any', which will simply skip the where(state ...) query and go straight to joins. So something like

```<code>def self.fetch_by_subcat(subcat_id, state='any')
  where(state: state).joins...
end
</code>```

Is there a way? Trying to avoid if/else.

答:
There is another way of doing it:

```<code>def self.fetch_by_subcat(subcat_id, state = 'state')
  joins(:subcategories).where("subcategory_id = ? AND published = ? AND state = #{state}", subcat_id, true)
end
</code>```

How it works? If You pass state, then its simply inserted. If not the query will look like: WHERE table_name.state = table_name.state.
Which is always true.

the ONLY thing to add here is to secure this method from sql injection and pass only specific, allowed state values.

Title: Query 'any' value with 'where' in Rails

Body:
I have the following method:

def self.fetch_by_subcat(subcat_id, state)
  where(state: state).joins(:subcategories).where("subcategory_id = ? AND published = ?", subcat_id, true)
end

The problem is that if my state is blank, I get back an empty array. So I would like to set my state argument to a default, something like 'any', which will simply skip the where(state ...) query and go straight to joins. So something like

def self.fetch_by_subcat(subcat_id, state='any')
  where(state: state).joins...
end

Is there a way? Trying to avoid if/else.

Body:
There is another way of doing it:

def self.fetch_by_subcat(subcat_id, state = 'state')
  joins(:subcategories).where("subcategory_id = ? AND published = ? AND state = #{state}", subcat_id, true)
end

How it works? If You pass state, then its simply inserted. If not the query will look like: WHERE table_name.state = table_name.state.
Which is always true.

the ONLY thing to add here is to secure this method from sql injection and pass only specific, allowed state values.


问:
vuforia augmented reality with unity3d
error image form visual studio

i download Vuforia Core Samples

and download last version vurforia sdk

and i have Unity 2017.3.0b4 with vuforia

and i use visual studio enterprise 2017 to edit scripts

what the solution for these errors?

The type or namespace name 'ReconstructionBehaviour' could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name 'PropBehaviour' could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name 'SurfaceBehaviour' could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name 'ReconstructionBehaviour' could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name 'Prop' could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name 'Surface' could not be found (are you missing a using directive or an assembly reference?)

error image form visual studio

答:
Activate Vuforia in the XR Settings under Player Settings. Refer Link.</p>

```<code>Edited:

1. Be sure to install Vuforia AR Support from the Download Assistant or XR Settings
2. Activate Vuforia AR Support in XR Settings
3. Then import the samples
</code>```

Title: vuforia augmented reality with unity3d

Body:
Activate Vuforia in the XR Settings under Player Settings. Refer Link.

Edited:

1. Be sure to install Vuforia AR Support from the Download Assistant or XR Settings
2. Activate Vuforia AR Support in XR Settings
3. Then import the samples