问:
Create API endpoint for fetching dynamic data based on time
I have a scraper which periodically scrapes articles from news sites and stores them in a database [MYSQL].
The way the scraping works is that the oldest articles are scraped first and then i move onto much more recent articles.

For example an article that was written on the 1st of Jan would be scraped first and given an ID 1  and an article that was scraped on the 2nd of Jan would have an ID 2.

So the recent articles would have a higher id as compared to older articles.

There are multiple scrapers running at the same time.

Now i need an endpoint which i can query based on timestamp of the articles and i also have a limit of 10 articles on each fetch.

The problem arises for example when there are 20 articles which were posted with a timestamp of 1499241705 and when i query the endpoint with a timestamp of 1499241705 a check is made to give me all articles that is >=1499241705 in which case i would always get the same 10 articles each time,changing the condition to a > would mean i skip out on the articles from 11-20. Adding another where clause to check on id is unsuccessful because articles may not always be inserted in the correct date order as the scraper is running concurrently.

Is there a way i can query this end point so i can always get consistent data from it with the latest articles coming first and then the older articles.

EDIT:

```<code>   +-----------------------+
   |   id | unix_timestamp |
   +-----------------------+
   |    1 |   1000         |
   |    2 |   1001         |
   |    3 |   1002         |
   |    4 |   1003         |
   |   11 |   1000         |
   |   12 |   1001         |
   |   13 |   1002         |
   |   14 |   1003         |
   +-----------------------+
</code>```

The last timestamp and ID is being sent through the WHERE clause.

E.g.
    $this->db->where('unix_timestamp <=', $timestamp);
                $this->db->where('id <', $offset);
$this->db->order_by('unix_timestamp ', 'DESC');
        $this->db->order_by('id', 'DESC');

On querying with a timestamp of 1003, ids 14 and 4 are fetched. But then during the next call, id 4 would be the offset thereby not fetching id 13 and only fetching id 3 the next time around.So data would be missing .

答:
Two parts: timestamp and id.

```<code>WHERE   timestamp <= $ts_leftoff
  AND ( timestamp <  $ts_leftoff
            OR id <= $id_leftoff )
ORDER BY (timestamp DESC, id DESC)
</code>```

So, assuming id is unique, it won't matter if lots of rows have the same timestamp, the order is fully deterministic.

There is a syntax for this, but unfortunately it is not well optimized:

```<code>WHERE (timestamp, id) <= ($ts_leftoff, $id_leftoff)
</code>```

So, I advise against using it.

More on the concept of "left off":  http://mysql.rjweb.org/doc.php/pagination

Body:
I have a scraper which periodically scrapes articles from news sites and stores them in a database [MYSQL].
The way the scraping works is that the oldest articles are scraped first and then i move onto much more recent articles.

For example an article that was written on the 1st of Jan would be scraped first and given an ID 1  and an article that was scraped on the 2nd of Jan would have an ID 2.

So the recent articles would have a higher id as compared to older articles.

There are multiple scrapers running at the same time.

Now i need an endpoint which i can query based on timestamp of the articles and i also have a limit of 10 articles on each fetch.

The problem arises for example when there are 20 articles which were posted with a timestamp of 1499241705 and when i query the endpoint with a timestamp of 1499241705 a check is made to give me all articles that is >=1499241705 in which case i would always get the same 10 articles each time,changing the condition to a > would mean i skip out on the articles from 11-20. Adding another where clause to check on id is unsuccessful because articles may not always be inserted in the correct date order as the scraper is running concurrently.

Is there a way i can query this end point so i can always get consistent data from it with the latest articles coming first and then the older articles.

EDIT:

   +-----------------------+
   |   id | unix_timestamp |
   +-----------------------+
   |    1 |   1000         |
   |    2 |   1001         |
   |    3 |   1002         |
   |    4 |   1003         |
   |   11 |   1000         |
   |   12 |   1001         |
   |   13 |   1002         |
   |   14 |   1003         |
   +-----------------------+

The last timestamp and ID is being sent through the WHERE clause.

E.g.
    $this->db->where('unix_timestamp <=', $timestamp);
                $this->db->where('id <', $offset);
$this->db->order_by('unix_timestamp ', 'DESC');
        $this->db->order_by('id', 'DESC');

On querying with a timestamp of 1003, ids 14 and 4 are fetched. But then during the next call, id 4 would be the offset thereby not fetching id 13 and only fetching id 3 the next time around.So data would be missing .

Body:
Two parts: timestamp and id.

WHERE   timestamp <= $ts_leftoff
  AND ( timestamp <  $ts_leftoff
            OR id <= $id_leftoff )
ORDER BY (timestamp DESC, id DESC)

So, assuming id is unique, it won't matter if lots of rows have the same timestamp, the order is fully deterministic.

There is a syntax for this, but unfortunately it is not well optimized:

WHERE (timestamp, id) <= ($ts_leftoff, $id_leftoff)

So, I advise against using it.

More on the concept of "left off":  http://mysql.rjweb.org/doc.php/pagination


来源: stackexchange

问:
ToIntArray - Replacement function
According to http://crsouza.blogspot.com.br/2012/01/decision-trees-in-c.html I use

```<code>DataTable symbols = codebook.Apply(data);
int[][] inputs  = symbols.ToIntArray("Outlook", "Temperature", "Humidity", "Wind");
int[]   outputs = symbols.ToIntArray("PlayTennis").GetColumn(0);
</code>```

But in .net 4.0 and in mono there is no ToIntArray, also I could not find any replacement function for it.

How does ToIntArray convert symbols or, what does ToIntArray look like?

答: As of the current version, you can use ToInt32(), as well as ToDouble(), ToSingle(), ToBoolean() and others to perform type conversions of arrays.</p>

ContentLicense: CC BY-SA 3.0

Title: ToIntArray - Replacement function

Body:
According to http://crsouza.blogspot.com.br/2012/01/decision-trees-in-c.html I use

DataTable symbols = codebook.Apply(data);
int[][] inputs  = symbols.ToIntArray("Outlook", "Temperature", "Humidity", "Wind");
int[]   outputs = symbols.ToIntArray("PlayTennis").GetColumn(0);

But in .net 4.0 and in mono there is no ToIntArray, also I could not find any replacement function for it.

How does ToIntArray convert symbols or, what does ToIntArray look like?


问:
Converting CGPoints between UIKit and SpriteKit woes: UIViews next to SKNodes
There are many posts on this but for whatever reason I can't seem to get the correct sequence of conversions correct. I'm trying to get the UISliders to go directly below the SKLabels.

As you can see in the pictures, one of the sliders doesn't show at all, and the other one is in the completely wrong place (the volume slider is near the seek label):

Here is my current attempt at getting this right, though I've tried a few other configurations that got me nowhere:

```<code>class GameScene: SKScene {

  let seekSlider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))
  let volSlider  = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))

  override func didMove(to view: SKView) {
    removeAllChildren() // Delete this in your actual project.

    // Add some labels:
    let seekLabel = SKLabelNode(text: "Seek")
    seekLabel.setScale(3)
    seekLabel.verticalAlignmentMode = .center
    seekLabel.position = CGPoint(x: frame.minX + seekLabel.frame.width/2,
                                 y: frame.maxY - seekLabel.frame.height)

    let volLabel  = SKLabelNode(text: "Volume")
    volLabel.setScale(3)
    volLabel.verticalAlignmentMode = .center
    volLabel.position = CGPoint(x: frame.minX + volLabel.frame.width/2,
                                y: frame.minY + volLabel.frame.height + volSlider.frame.height)

    /*  CONVERSION WOES BELOW: */

    // Configure sliders:
    let seekOrigin = convertPoint(toView: convert(seekLabel.position, from: self))
    seekSlider.frame = CGRect(origin: seekOrigin, size: CGSize(width: 200, height: 15))
    seekSlider.value = 1

    let volOrigin = convertPoint(fromView: CGPoint(x: volLabel.frame.minX, y: volLabel.frame.minY))
    seekSlider.frame = CGRect(origin: volOrigin, size: CGSize(width: 200, height: 15))
    seekSlider.value = 0

    // Scene stuff:
    view.addSubview(seekSlider)
    view.addSubview(volSlider)
    addChild(seekLabel)
    addChild(volLabel)
  }
}
</code>```

答:
You're very close! There are two minor issues in your code:

Issue #1

You modify the seekSlider's frame twice instead of modifying the seekSlider then the volSlider.

```<code>let volOrigin = convertPoint(fromView: CGPoint(x: volLabel.frame.minX, y: volLabel.frame.minY))
seekSlider.frame = CGRect(origin: volOrigin, size: CGSize(width: 200, height: 15))
seekSlider.value = 0
</code>```

should be

```<code>let volOrigin = convertPoint(fromView: CGPoint(x: volLabel.frame.minX, y: volLabel.frame.minY))
volSlider.frame = CGRect(origin: volOrigin, size: CGSize(width: 200, height: 15))
volSlider.value = 0
</code>```

Issue #2

The conversion code is not correct.

Using the convertPoint(toView method with the node's position should do the trick:

```<code>let seekOrigin = convertPoint(toView: seekLabel.position)
</code>```

Final Code:

```<code>class GameScene: SKScene {

    let seekSlider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))
    let volSlider  = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))

    override func didMove(to view: SKView) {
        removeAllChildren() // Delete this in your actual project.

        // Add some labels:
        let seekLabel = SKLabelNode(text: "Seek")
        seekLabel.setScale(3)
        seekLabel.verticalAlignmentMode = .center
        seekLabel.position = CGPoint(x: frame.minX + seekLabel.frame.width/2,
                                     y: frame.maxY - seekLabel.frame.height)

        let volLabel  = SKLabelNode(text: "Volume")
        volLabel.setScale(3)
        volLabel.verticalAlignmentMode = .center
        volLabel.position = CGPoint(x: frame.minX + volLabel.frame.width/2,
                                    y: frame.minY + volLabel.frame.height + volSlider.frame.height)

        // Configure sliders:
        let seekOrigin = convertPoint(toView: seekLabel.position)
        let offsetSeekOrigin = CGPoint(x: seekOrigin.x, y: seekOrigin.y + 50)
        seekSlider.frame = CGRect(origin: offsetSeekOrigin, size: CGSize(width: 200, height: 15))
        seekSlider.value = 1

        let volOrigin = convertPoint(toView: volLabel.position)
        let offsetVolOrigin = CGPoint(x: volOrigin.x, y: volOrigin.y - 50)
        volSlider.frame = CGRect(origin: offsetVolOrigin, size: CGSize(width: 200, height: 15))
        volSlider.value = 0

        // Scene stuff:
        view.addSubview(seekSlider)
        view.addSubview(volSlider)
        addChild(seekLabel)
        addChild(volLabel)
    }
}
</code>```

Final Result:

Body:
There are many posts on this but for whatever reason I can't seem to get the correct sequence of conversions correct. I'm trying to get the UISliders to go directly below the SKLabels.

As you can see in the pictures, one of the sliders doesn't show at all, and the other one is in the completely wrong place (the volume slider is near the seek label):

Here is my current attempt at getting this right, though I've tried a few other configurations that got me nowhere:

class GameScene: SKScene {

  let seekSlider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))
  let volSlider  = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))

  override func didMove(to view: SKView) {
    removeAllChildren() // Delete this in your actual project.

    // Add some labels:
    let seekLabel = SKLabelNode(text: "Seek")
    seekLabel.setScale(3)
    seekLabel.verticalAlignmentMode = .center
    seekLabel.position = CGPoint(x: frame.minX + seekLabel.frame.width/2,
                                 y: frame.maxY - seekLabel.frame.height)

    let volLabel  = SKLabelNode(text: "Volume")
    volLabel.setScale(3)
    volLabel.verticalAlignmentMode = .center
    volLabel.position = CGPoint(x: frame.minX + volLabel.frame.width/2,
                                y: frame.minY + volLabel.frame.height + volSlider.frame.height)

    /*  CONVERSION WOES BELOW: */

    // Configure sliders:
    let seekOrigin = convertPoint(toView: convert(seekLabel.position, from: self))
    seekSlider.frame = CGRect(origin: seekOrigin, size: CGSize(width: 200, height: 15))
    seekSlider.value = 1

    let volOrigin = convertPoint(fromView: CGPoint(x: volLabel.frame.minX, y: volLabel.frame.minY))
    seekSlider.frame = CGRect(origin: volOrigin, size: CGSize(width: 200, height: 15))
    seekSlider.value = 0

    // Scene stuff:
    view.addSubview(seekSlider)
    view.addSubview(volSlider)
    addChild(seekLabel)
    addChild(volLabel)
  }
}

Body:
You're very close! There are two minor issues in your code:

Issue #1

You modify the seekSlider's frame twice instead of modifying the seekSlider then the volSlider.

let volOrigin = convertPoint(fromView: CGPoint(x: volLabel.frame.minX, y: volLabel.frame.minY))
seekSlider.frame = CGRect(origin: volOrigin, size: CGSize(width: 200, height: 15))
seekSlider.value = 0

should be

let volOrigin = convertPoint(fromView: CGPoint(x: volLabel.frame.minX, y: volLabel.frame.minY))
volSlider.frame = CGRect(origin: volOrigin, size: CGSize(width: 200, height: 15))
volSlider.value = 0

Issue #2

The conversion code is not correct.

Using the convertPoint(toView method with the node's position should do the trick:

let seekOrigin = convertPoint(toView: seekLabel.position)

Final Code:

class GameScene: SKScene {

    let seekSlider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))
    let volSlider  = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))

    override func didMove(to view: SKView) {
        removeAllChildren() // Delete this in your actual project.

        // Add some labels:
        let seekLabel = SKLabelNode(text: "Seek")
        seekLabel.setScale(3)
        seekLabel.verticalAlignmentMode = .center
        seekLabel.position = CGPoint(x: frame.minX + seekLabel.frame.width/2,
                                     y: frame.maxY - seekLabel.frame.height)

        let volLabel  = SKLabelNode(text: "Volume")
        volLabel.setScale(3)
        volLabel.verticalAlignmentMode = .center
        volLabel.position = CGPoint(x: frame.minX + volLabel.frame.width/2,
                                    y: frame.minY + volLabel.frame.height + volSlider.frame.height)

        // Configure sliders:
        let seekOrigin = convertPoint(toView: seekLabel.position)
        let offsetSeekOrigin = CGPoint(x: seekOrigin.x, y: seekOrigin.y + 50)
        seekSlider.frame = CGRect(origin: offsetSeekOrigin, size: CGSize(width: 200, height: 15))
        seekSlider.value = 1

        let volOrigin = convertPoint(toView: volLabel.position)
        let offsetVolOrigin = CGPoint(x: volOrigin.x, y: volOrigin.y - 50)
        volSlider.frame = CGRect(origin: offsetVolOrigin, size: CGSize(width: 200, height: 15))
        volSlider.value = 0

        // Scene stuff:
        view.addSubview(seekSlider)
        view.addSubview(volSlider)
        addChild(seekLabel)
        addChild(volLabel)
    }
}

Final Result:


问:
open another view controllers view from right side of the screen
I want to open a viewcontroller from right side of the screen.

That is on doing

[self presentModalViewController:pvc animated:YES];

I want the another viewcontroller's view to appear as if its sliding from the right of the screen instead of appearing as if it is coming from the bottom of the screen :)

How can I achieve that. Please help :)

答:
What you are looking for is a UINavigationController.

In your app delegate you will have a line that looks like this in applicationDidFinishLoading:

```<code>[window addSubview:viewController.view];
</code>```

Change that line to these:

```<code>UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
[window addSubview:navController.view];
</code>```

Now instead of [self presentModalViewController:pcv animated:YES]; you can do:

```<code>[self.navigationController pushViewController:pcv animated:YES];
</code>```

This is the control which gives the "slide in from the right" animation. Plus allows you to better control a view stack and navigation within an app. Its the best way to control navigation in your app.

ps: that navController will leak now - its just like this in my example so you can see what I'm doing. You'll want to make the navController an iVar in the .h of your app delegate so you can release it in dealloc. If you release it like it is now then you won't be able to send messages to it.

ContentLicense: CC BY-SA 2.5

Body:
What you are looking for is a UINavigationController.

In your app delegate you will have a line that looks like this in applicationDidFinishLoading:

[window addSubview:viewController.view];

Change that line to these:

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
[window addSubview:navController.view];

Now instead of [self presentModalViewController:pcv animated:YES]; you can do:

[self.navigationController pushViewController:pcv animated:YES];

This is the control which gives the "slide in from the right" animation. Plus allows you to better control a view stack and navigation within an app. Its the best way to control navigation in your app.

ps: that navController will leak now - its just like this in my example so you can see what I'm doing. You'll want to make the navController an iVar in the .h of your app delegate so you can release it in dealloc. If you release it like it is now then you won't be able to send messages to it.


问:
How do I reduce the space below my element/text using padding/margin?
my website learning

Hi everybody.

Im martin.

So im learning to use html and CSS but i'm running through some trouble.
if you are able to see my website (practice) that im trying to create, i wish to reduce the space under the word 'I am ______| learner' and under 'contact'.
I have tried to using padding-bottom but i must be doing something wrong, and i have been playing around for way way too long to understand padding,margins and borders but my head is so confused right now!

Thank you everyone!

```<code>/****************************
CSS
*****************************/

#wrapper {
  margin:15% auto;
  padding:5px;
  max-width:1024px;
}
body {
  color:#988;
  background:white;
  font-family: 'oswald', monospace;
}

/****************************
LOGO/HEADING
****************************/
header {
  background:#a0a0a0;
}

#logo {
  text-decoration:none;

}

h1 {
  font-family:'oswald', monospace;
  font-size:2em;
  color:#fff;
  text-align:center;
  margin:1px;
  padding:7px;
  line-height:0.8em;

}
nav {
  font-size:1em;
  background:#d0d0d0;
  text-align:center;
  padding-top:0px;
  margin-bottom:5px;
  line-height: 1.1em;
  padding-bottom:1px;
}

/****************************
nav a links
*****************************/

nav a, nav a:visited {
  color:#FFF;
}

nav a.selected, nav a:hover {
  color:#131c1f;
}
</code>```

答:
Please do not sweat up where there is a will there's a way we are here to help you in all way.

All i came to know from your question is that you have an element suppose
I am
 having border and you to reduce spacing between text "I am" and border correct?

well here is the suggestion. You just need to play using property "Padding-bottom".

in case it still not working and you want more space to be decreased you can also try line-height property. You can giver line-height property in px, em, or %.

I hope this suggestions works well for your problems.

Adios. Cheeers....

Body:
my website learning

Hi everybody.

Im martin.

So im learning to use html and CSS but i'm running through some trouble.
if you are able to see my website (practice) that im trying to create, i wish to reduce the space under the word 'I am ______| learner' and under 'contact'.
I have tried to using padding-bottom but i must be doing something wrong, and i have been playing around for way way too long to understand padding,margins and borders but my head is so confused right now!

Thank you everyone!

/****************************
CSS
*****************************/

#wrapper {
  margin:15% auto;
  padding:5px;
  max-width:1024px;
}
body {
  color:#988;
  background:white;
  font-family: 'oswald', monospace;
}

/****************************
LOGO/HEADING
****************************/
header {
  background:#a0a0a0;
}

#logo {
  text-decoration:none;

}

h1 {
  font-family:'oswald', monospace;
  font-size:2em;
  color:#fff;
  text-align:center;
  margin:1px;
  padding:7px;
  line-height:0.8em;

}
nav {
  font-size:1em;
  background:#d0d0d0;
  text-align:center;
  padding-top:0px;
  margin-bottom:5px;
  line-height: 1.1em;
  padding-bottom:1px;
}

/****************************
nav a links
*****************************/

nav a, nav a:visited {
  color:#FFF;
}

nav a.selected, nav a:hover {
  color:#131c1f;
}


问:
Javascript code doesn't work. Why?
The values of the buttons should change when you click on them

```<code><html>
<head>

</head>

<body>

<input type = "button" value ="1" onclick="click(this);">
<input type = "button" value ="0" onclick="click(this);">
<input type = "button" value ="1" onclick="click(this);">

<script>

function click(objekt) {

if(objekt.value == 1)
    objekt.value = 0;
    else
        objekt.value = 1;

}

</script>

</body>
</html>
</code>```

Please explain how to get the value on onclick event?

答:
Name of your function is the culprit here. you can not name your function name "click", it's restricted . Change your function name, it will work.

function click123(objekt) {
  if (objekt.value == 1)
    objekt.value = 0;
  else
    objekt.value = 1;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" value="1" onclick="click123(this);">
<input type="button" value="0" onclick="click123(this);">
<input type="button" value="1" onclick="click123(this);"></code>```

Title: Javascript code doesn't work. Why?

Body:
The values of the buttons should change when you click on them

<input type = "button" value ="1" onclick="click(this);">
<input type = "button" value ="0" onclick="click(this);">
<input type = "button" value ="1" onclick="click(this);">

Please explain how to get the value on onclick event?

Body:
Name of your function is the culprit here. you can not name your function name "click", it's restricted . Change your function name, it will work.

function click123(objekt) {
  if (objekt.value == 1)
    objekt.value = 0;
  else
    objekt.value = 1;

}

<input type="button" value="1" onclick="click123(this);">
<input type="button" value="0" onclick="click123(this);">
<input type="button" value="1" onclick="click123(this);">


问:
deleting repetitive columns in unix
I would like to delete multiple repetitive columns from a huge file (about 1 million).
The columns that I want to delete has the same column names: A and others has different unique name. Say:

A B2 A B3

1.1 AA 1.2 AA

2.1 AB 4.3 CT

2.2 AC 6.4 GT

so column headers are A, B2, A, B3,... .
How could I delete the columns named as A's from the data.

答:
```<code>cut -d' ' -f $(head -1 filename|tr ' ' '\n'|awk '{if(!seen[$0]++) print NR}'|paste -s -d ',') filename
</code>```

<p>this will work like a charm. </p>

Title: deleting repetitive columns in unix

Body:
cut -d' ' -f $(head -1 filename|tr ' ' '\n'|awk '{if(!seen[$0]++) print NR}'|paste -s -d ',') filename

this will work like a charm.


问:
Unable to pass temporary object to a move constructor
I'm trying to come to terms with rvalue in C++11, and I encounter this oddity. As I understand, calling foo myfoo(foo()) would create a temporary foo, which is then moved to myfoo.

However, Visual Studio 2015 tells me that myfoo does not exist when I try to compile. Is this a bug?

```<code>#include<iostream>
using namespace std;

class foo
{
    static int n;
    int id;
public:
    foo() :id(n) { ++n; cout << "Created: " << id << endl; }
    foo(foo &o) :id(o.id) { cout << "Copy: " << id << endl; }
    foo(foo &&o) :id(o.id) { cout << "Move: " << id << endl; }
    ~foo() { cout << "Destroy: " << id << endl; }
    void bar (){cout << "I am: " << id << endl; }
};
int foo::n = 0;

int main()
{
    foo myfoo (foo());
    myfoo.bar();
    return 0;
}
</code>```

答:
It's an instance of most vexing parse. C++ interprets myfoo construction as an function returning foo with foo argument.

To fix this, you need to put additional parenthesis around temporary foo()

```<code>foo myfoo ((foo()));
</code>```

Or use initialization list:

```<code>foo myfoo { foo() };
</code>```

Body:
I'm trying to come to terms with rvalue in C++11, and I encounter this oddity. As I understand, calling foo myfoo(foo()) would create a temporary foo, which is then moved to myfoo.

However, Visual Studio 2015 tells me that myfoo does not exist when I try to compile. Is this a bug?

#include<iostream>
using namespace std;

class foo
{
    static int n;
    int id;
public:
    foo() :id(n) { ++n; cout << "Created: " << id << endl; }
    foo(foo &o) :id(o.id) { cout << "Copy: " << id << endl; }
    foo(foo &&o) :id(o.id) { cout << "Move: " << id << endl; }
    ~foo() { cout << "Destroy: " << id << endl; }
    void bar (){cout << "I am: " << id << endl; }
};
int foo::n = 0;

int main()
{
    foo myfoo (foo());
    myfoo.bar();
    return 0;
}

Body:
It's an instance of most vexing parse. C++ interprets myfoo construction as an function returning foo with foo argument.

To fix this, you need to put additional parenthesis around temporary foo()

foo myfoo ((foo()));

Or use initialization list:

foo myfoo { foo() };


答:
try this just a simple loop with try except , this is base on your example output, try to modify it base on your data

```<code>n=5 #your example
df['boolean']=df['X(%)']>1
A=[]
for i in range(len(df)):
     try :
         A.append(sum(df.boolean[i+1:i+n+1])/len(df.boolean[i+1:i+n+1]))
     except:
         A.append(0)

df['Y(%)']=A

df

     ticker       date  adj_open  ad_close   X(%) boolean Y(%)
   0    ABC  10/6/2017     12.10     13.11   8.0   True  0.80
   1    ABC  12/5/2017     11.11     11.87   5.0   True  0.75
   2    ABC  12/4/2017     12.08     11.40  -7.0  False  1.00
   3    ABC  12/3/2017     12.01     13.03  10.1   True  1.00
   4    ABC   7/4/2017      9.01      9.59   8.0   True  1.00
   5    ABC   7/3/2017      7.89      8.19   4.0   True  0.00
</code>```

Title: Computing the column value based on previous rows

Body:
I would like to add a new column Y to each row which will tell me percentage number of times the X column val was greater > 1 for last 10 previous records

stock price history

   ticker       date    adj_open   ad_close       X(%)
0    ABC     2017-10-06   12.10      13.11        8.0
1    ABC     2017-12-05   11.11      11.87        5.0
2    ABC     2017-12-04   12.08      11.40       -7.0
3    ABC     2017-12-03   12.01      13.03       10.1
4    ABC     2017-07-04   9.01        9.59        8.0
5    ABC     2017-07-03   7.89        8.19        4.0

Resultant transformed data set

    ticker       date    adj_open ad_close    X(%)     Y(%)
0    ABC     2017-10-06   12.10    13.11      8.0        80
1    ABC     2017-12-05   11.11    11.87      5.0        75
2    ABC     2017-12-04   12.08    11.40     -7.0       100
3    ABC     2017-12-03   12.01    13.03     10.1       100
4    ABC     2017-07-04   9.01     9.59       8.0       100
5    ABC     2017-07-03   7.89     8.19       4.0        0

Body:
try this just a simple loop with try except , this is base on your example output, try to modify it base on your data

n=5 #your example
df['boolean']=df['X(%)']>1
A=[]
for i in range(len(df)):
     try :
         A.append(sum(df.boolean[i+1:i+n+1])/len(df.boolean[i+1:i+n+1]))
     except:
         A.append(0)

df['Y(%)']=A

df

     ticker       date  adj_open  ad_close   X(%) boolean Y(%)
   0    ABC  10/6/2017     12.10     13.11   8.0   True  0.80
   1    ABC  12/5/2017     11.11     11.87   5.0   True  0.75
   2    ABC  12/4/2017     12.08     11.40  -7.0  False  1.00
   3    ABC  12/3/2017     12.01     13.03  10.1   True  1.00
   4    ABC   7/4/2017      9.01      9.59   8.0   True  1.00
   5    ABC   7/3/2017      7.89      8.19   4.0   True  0.00


问:
Xcode 8.3.2 Clang Error
I am trying to update one of my project, when I opened it I performed validated settings, but when I try to build it I just face with this error :

Apple Mach-O Linker Error Group : clang: error: linker command failed
  with exit code 1 (use -v to see invocation)

with no more infos and I am not using cocoapods or any external frameworks. I just searched everywhere and did any possible solution such as :

Clean and run

Searched for duplicate files

Check imported header files

Delete xxxTest

Checked Build Active architecture

Validated Settings

Checked missing frameworks

Restart mac

Changed iOS deployment target

Disabled bitcode

and etc...

Is there anything to solve this issue ?!

答:
-Try this
1.Xcode -> Preferences -> Location -> click on derived data path and clear all derived data.
2."Build Phases" -> "Compile Sources" and look for duplicate of classes.
3.Or check if you have "*.m" files in your #import</p>

Title: Xcode 8.3.2 Clang Error


答:
you can use margin-top or margin-bottom

/****************************
CSS
*****************************/

#wrapper {
  margin:15% auto;
  padding:5px;
  max-width:1024px;
}
body {
  color:#988;
  background:white;
  font-family: 'oswald', monospace;
}

/****************************
LOGO/HEADING
****************************/
header {
  background:#a0a0a0;
}

#logo {
  text-decoration:none;

}

h1 {
  font-family:'oswald', monospace;
  font-size:2em;
  color:#fff;
  text-align:center;
  margin-top:20px;
 margin-bottom:20px;
  padding:7px;
  line-height:0.8em;

}
nav {
  font-size:1em;
  background:#d0d0d0;
  text-align:center;
  padding-top:0px;
  margin-bottom:5px;
  line-height: 1.1em;
  padding-bottom:1px;
}

/****************************
nav a links
*****************************/

nav a, nav a:visited {
  color:#FFF;
}

nav a.selected, nav a:hover {
  color:#131c1f;
}

    ```

Title: How do I reduce the space below my element/text using padding/margin?


问:
Share variables between elements in polymer
I have a component <my-comp> which has a property with double binding which I pass to a different component <my-sec-comp show-drawer="{{showDrawer}}">.
When I change the property showDrawer in the parent element it is also noticed in the child element. But not the other way around. How can I achieve this?

declaration in  child element is:

```<code> showDrawer : {
                type: Boolean,
                notify: true
            }
</code>```

declaration in parent element is:

```<code>showDrawer : {
                type: Boolean,
                notify: true,
                observer: '_drawerChanged'
            },
</code>```

答: You can use redux for this it allows you to share information between any components. They don´t even need to be siblings. Have a look at this</p>

Body:
I have a component <my-comp> which has a property with double binding which I pass to a different component <my-sec-comp show-drawer="{{showDrawer}}">.
When I change the property showDrawer in the parent element it is also noticed in the child element. But not the other way around. How can I achieve this?

declaration in  child element is:

 showDrawer : {
                type: Boolean,
                notify: true
            }

declaration in parent element is:

showDrawer : {
                type: Boolean,
                notify: true,
                observer: '_drawerChanged'
            },


问:
Getting the following code to work in both Chrome and Safari
Can't seem to figure out why this works in Safari but not in chrome. Any help would be much appreciated.

```<code>//Create or use existing DB
var db = openDatabase('myTest', '1.0', 'mySpecialDatabase', 200000);

if (db) {
  //New Transaction
  db.transaction(function (tx) {
  tx.executeSql('DROP TABLE IF EXISTS foo');
  tx.executeSql('CREATE TABLE IF NOT EXISTS foo (id unique, text)');
  //Insert test data
  tx.executeSql('INSERT INTO foo (id, text) VALUES (1, "myTest")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (2, "another")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (3, "andYetAnother")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (4, "ohAndAgain")');
    });
    alert("DB success");
 }
else {
    alert("Oooops");
}

db.transaction(function (tx) {
    // Loop rows of DB, print values
    tx.executeSql('SELECT * FROM foo',[], function (tx, results) {
        var rows = results.rows;
        alert(rows.length);
        for (var index = 0; index < rows.length; index++) {
            var x = rows.item(index);
            alert(x.text);
        }
    });
});
</code>```

Throw it in JSFiddle in either browser, works as intended in latest release of Safari but no such luck in chrome.

EDIT

I managed to get it working in the end - code can be seen below.

```<code>var db = openDatabase('CBDB', '1.0', 'mySpecialDatabaseThatWontWork',10*1024*1024);

db.transaction(function (tx){
 tx.executeSql('DROP TABLE IF EXISTS cb');
 alert("dropped table");
 createDB();
 queryDB();
},
function (tx, error) {
    // error
    alert('0.Something went wrong: '+ error.message);
});

function createDB(){
    db.transaction(function (tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS cb (id unique, text)');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (1, "myTest")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (2, "another")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (3, "andYetAnother")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (4, "ohAndAgain")');
        alert("DB success");
        },
        function (tx, error) {
            // error
            alert('1.Something went wrong: '+ error.message);
        });
}

function queryDB(){
    db.transaction(function (tx) {
        tx.executeSql('SELECT * FROM cb',[], function (tx, results) {
            var rows = results.rows;
            alert(rows.length);
            for (var index = 0; index < rows.length; index++) {
                var x = rows.item(index);
                alert(x.text);
            }
        },
        function (tx, error) {
        // error
        alert('2.Something went wrong: '+ error.message);
        });
    });
}
</code>```

答:
The problem is that rather like an AJAX request, Chrome performs its database transactions (as coded) asynchronously. i.e. the data doesn't exist yet when it starts executing the query. This code should work:

```<code>//Create or use existing DB
var db = openDatabase('myTest', '1.0', 'mySpecialDatabase', 200000);

if (db) {
  //New Transaction
  db.transaction(function (tx) {
  tx.executeSql('DROP TABLE IF EXISTS foo');
  tx.executeSql('CREATE TABLE IF NOT EXISTS foo (id unique, text)');
  //Insert test data
  tx.executeSql('INSERT INTO foo (id, text) VALUES (1, "myTest")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (2, "another")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (3, "andYetAnother")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (4, "ohAndAgain")');
    });
    alert("DB success");
    doQuery(); // call query only after database load is complete

 }
else {
    alert("Oooops");
}

function doQuery(){
  db.transaction(function (tx) {
      // Loop rows of DB, print values
      tx.executeSql('SELECT * FROM foo',[], function (tx, results) {
          var rows = results.rows;
          alert(rows.length);
          for (var index = 0; index < rows.length; index++) {
              var x = rows.item(index);
              alert(x.text);
          }
      });
  });
}
</code>```

It is possible to have synchronous database access (c.f. HTML5 Database API : Synchronous request) but this is also not straightforward.

Body:
Can't seem to figure out why this works in Safari but not in chrome. Any help would be much appreciated.

//Create or use existing DB
var db = openDatabase('myTest', '1.0', 'mySpecialDatabase', 200000);

if (db) {
  //New Transaction
  db.transaction(function (tx) {
  tx.executeSql('DROP TABLE IF EXISTS foo');
  tx.executeSql('CREATE TABLE IF NOT EXISTS foo (id unique, text)');
  //Insert test data
  tx.executeSql('INSERT INTO foo (id, text) VALUES (1, "myTest")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (2, "another")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (3, "andYetAnother")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (4, "ohAndAgain")');
    });
    alert("DB success");
 }
else {
    alert("Oooops");
}

db.transaction(function (tx) {
    // Loop rows of DB, print values
    tx.executeSql('SELECT * FROM foo',[], function (tx, results) {
        var rows = results.rows;
        alert(rows.length);
        for (var index = 0; index < rows.length; index++) {
            var x = rows.item(index);
            alert(x.text);
        }
    });
});

Throw it in JSFiddle in either browser, works as intended in latest release of Safari but no such luck in chrome.

EDIT

I managed to get it working in the end - code can be seen below.

var db = openDatabase('CBDB', '1.0', 'mySpecialDatabaseThatWontWork',10*1024*1024);

db.transaction(function (tx){
 tx.executeSql('DROP TABLE IF EXISTS cb');
 alert("dropped table");
 createDB();
 queryDB();
},
function (tx, error) {
    // error
    alert('0.Something went wrong: '+ error.message);
});

function createDB(){
    db.transaction(function (tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS cb (id unique, text)');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (1, "myTest")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (2, "another")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (3, "andYetAnother")');
        tx.executeSql('INSERT INTO cb (id, text) VALUES (4, "ohAndAgain")');
        alert("DB success");
        },
        function (tx, error) {
            // error
            alert('1.Something went wrong: '+ error.message);
        });
}

function queryDB(){
    db.transaction(function (tx) {
        tx.executeSql('SELECT * FROM cb',[], function (tx, results) {
            var rows = results.rows;
            alert(rows.length);
            for (var index = 0; index < rows.length; index++) {
                var x = rows.item(index);
                alert(x.text);
            }
        },
        function (tx, error) {
        // error
        alert('2.Something went wrong: '+ error.message);
        });
    });
}

Body:
The problem is that rather like an AJAX request, Chrome performs its database transactions (as coded) asynchronously. i.e. the data doesn't exist yet when it starts executing the query. This code should work:

//Create or use existing DB
var db = openDatabase('myTest', '1.0', 'mySpecialDatabase', 200000);

if (db) {
  //New Transaction
  db.transaction(function (tx) {
  tx.executeSql('DROP TABLE IF EXISTS foo');
  tx.executeSql('CREATE TABLE IF NOT EXISTS foo (id unique, text)');
  //Insert test data
  tx.executeSql('INSERT INTO foo (id, text) VALUES (1, "myTest")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (2, "another")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (3, "andYetAnother")');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (4, "ohAndAgain")');
    });
    alert("DB success");
    doQuery(); // call query only after database load is complete

 }
else {
    alert("Oooops");
}

function doQuery(){
  db.transaction(function (tx) {
      // Loop rows of DB, print values
      tx.executeSql('SELECT * FROM foo',[], function (tx, results) {
          var rows = results.rows;
          alert(rows.length);
          for (var index = 0; index < rows.length; index++) {
              var x = rows.item(index);
              alert(x.text);
          }
      });
  });
}

It is possible to have synchronous database access (c.f. HTML5 Database API : Synchronous request) but this is also not straightforward.


问:
Python Multiprocessing: What's the difference between map and imap?
I'm trying to learn how to use Python's multiprocessing package, but I don't understand the difference between map and imap.

Is the difference that map returns, say, an actual array or set, while imap returns an iterator over an array or set? When would I use one over the other?

Also, I don't understand what the chunksize argument is. Is this the number of values that are passed to each process?

答:
imap is from itertools module which is used for fast and memory efficiency in python.Map will return the list where as imap returns the object which generates the values for each iterations(In python 2.7).The below code blocks will clear the difference.

Map returns the list can be printed directly

```<code> from itertools import *
    from math import *

    integers = [1,2,3,4,5]
    sqr_ints = map(sqrt, integers)
    print (sqr_ints)
</code>```

imap returns object which is converted to list and printed.

```<code>from itertools import *
from math import *

integers = [1,2,3,4,5]
sqr_ints = imap(sqrt, integers)
print list(sqr_ints)
</code>```

Chunksize will make the iterable to be split into pieces of specified size(approximate) and each piece is submitted as a separate task.

Body:
imap is from itertools module which is used for fast and memory efficiency in python.Map will return the list where as imap returns the object which generates the values for each iterations(In python 2.7).The below code blocks will clear the difference.

Map returns the list can be printed directly

 from itertools import *
    from math import *

    integers = [1,2,3,4,5]
    sqr_ints = map(sqrt, integers)
    print (sqr_ints)

imap returns object which is converted to list and printed.

from itertools import *
from math import *

integers = [1,2,3,4,5]
sqr_ints = imap(sqrt, integers)
print list(sqr_ints)

Chunksize will make the iterable to be split into pieces of specified size(approximate) and each piece is submitted as a separate task.


问:
How does a substitution cipher work in C?
I've been researching the topic of encryption and I'm currently experimenting with using C. Does such a cipher work well in this programming language</p>

答:
Yes: "C" is a good implementation language for encryption.

No: Basic substitution cipher are not good/secure. For data encryption use AES.

Essentially a substitution cipher replaces the message characters with other characters based on some schedule. Simple examples are the Caesar cipher, ROT13 and One-time pad—the first two are trivial, the last is completely secure if implemented properly.

To study there are many references on the web.

There is even a free PDF book: Handbook of Applied Cryptography by Alfred J. Menezes, Paul C. van Oorschot and Scott A. Vanstone, see free download. Chapter is a reasonable start for current ciphers.

Other books:

Cryptography Decrypted by H. X. Mel and Doris M. Baker (good starter I really like)

Applied Cryptography by Bruce Schneier

Cryptography Engineering by Niels Ferguson, Bruce Schneier, and Tadayoshi Kohno

There are also some good free courses in the web as Coursera and Udacity.


问:
Escaping a C++ string
What's the easiest way to convert a C++ std::string to another std::string, which has all the unprintable characters escaped?

For example, for the string of two characters [0x61,0x01], the result string might be "a\x01" or "a%01".

答:
Assuming that "easiest way" means short and yet easily understandable while not depending on any other resources (like libs) I would go this way:</p>

```<code>#include <cctype>
#include <sstream>

// s is our escaped output string
std::string s = "";
// loop through all characters
for(char c : your_string)
{
    // check if a given character is printable
    // the cast is necessary to avoid undefined behaviour
    if(isprint((unsigned char)c))
        s += c;
    else
    {
        std::stringstream stream;
        // if the character is not printable
        // we'll convert it to a hex string using a stringstream
        // note that since char is signed we have to cast it to unsigned first
        stream << std::hex << (unsigned int)(unsigned char)(c);
        std::string code = stream.str();
        s += std::string("\\x")+(code.size()<2?"0":"")+code;
        // alternatively for URL encodings:
        //s += std::string("%")+(code.size()<2?"0":"")+code;
    }
}
</code>```

Title: Escaping a C++ string

Body:
Assuming that "easiest way" means short and yet easily understandable while not depending on any other resources (like libs) I would go this way:

#include <cctype>
#include <sstream>

// s is our escaped output string
std::string s = "";
// loop through all characters
for(char c : your_string)
{
    // check if a given character is printable
    // the cast is necessary to avoid undefined behaviour
    if(isprint((unsigned char)c))
        s += c;
    else
    {
        std::stringstream stream;
        // if the character is not printable
        // we'll convert it to a hex string using a stringstream
        // note that since char is signed we have to cast it to unsigned first
        stream << std::hex << (unsigned int)(unsigned char)(c);
        std::string code = stream.str();
        s += std::string("\\x")+(code.size()<2?"0":"")+code;
        // alternatively for URL encodings:
        //s += std::string("%")+(code.size()<2?"0":"")+code;
    }
}

ContentLicense: CC BY-SA 4.0


问:
Julia: How to iterate with Channel
When I run the following code, I get a deprecation saying produce has been replace with channels.

```<code>function source(dir)
    filelist = readdir(dir)

    for filename in filelist
        name,ext = splitext(filename)
        if ext == ".jld"
            produce(filename)
        end
    end
end

path = "somepathdirectoryhere"

for fname in Task(source(path))
    println(fname)
end
</code>```

I cannot find an example on how to do this with channels.  I've tried creating a global channel and using put! instead of produce with no luck.

Any ideas?

答:
Here's one way. Modify your function to accept a channel argument, and put! data in it:

```<code>function source(dir, chnl)
  filelist = readdir(dir)
  for filename in filelist
    name, ext = splitext(filename)
    if ext == ".jld"
      put!(chnl, filename)  % this blocks until "take!" is used elsewhere
    end
  end
end
</code>```

Then create your task implicitly using the Channel constructor (which takes a function with a single argument only representing the channel, so we need to wrap the source function around an anonymous function):

```<code>my_channel = Channel( (channel_arg) -> source( pwd(), channel_arg) )
</code>```

Then, either check the channel is still open (i.e. task hasn't finished) and if so take an argument:

```<code>julia> while isopen( my_channel)
         take!( my_channel) |> println;
       end
no.jld
yes.jld
</code>```

or, use the channel itself as an iterator (iterating over Tasks is becoming deprecated, along with the produce / consume functionality)

```<code>julia> for i in my_channel
         i |> println
       end
no.jld
yes.jld
</code>```

Alternatively you can use @schedule with bind etc as per the documentation, but it seems like the above is the most straightforward way.

Title: Julia: How to iterate with Channel

Body:
When I run the following code, I get a deprecation saying produce has been replace with channels.

function source(dir)
    filelist = readdir(dir)

    for filename in filelist
        name,ext = splitext(filename)
        if ext == ".jld"
            produce(filename)
        end
    end
end

path = "somepathdirectoryhere"

for fname in Task(source(path))
    println(fname)
end

I cannot find an example on how to do this with channels.  I've tried creating a global channel and using put! instead of produce with no luck.

Any ideas?

Body:
Here's one way. Modify your function to accept a channel argument, and put! data in it:

function source(dir, chnl)
  filelist = readdir(dir)
  for filename in filelist
    name, ext = splitext(filename)
    if ext == ".jld"
      put!(chnl, filename)  % this blocks until "take!" is used elsewhere
    end
  end
end

Then create your task implicitly using the Channel constructor (which takes a function with a single argument only representing the channel, so we need to wrap the source function around an anonymous function):

my_channel = Channel( (channel_arg) -> source( pwd(), channel_arg) )

Then, either check the channel is still open (i.e. task hasn't finished) and if so take an argument:

julia> while isopen( my_channel)
         take!( my_channel) |> println;
       end
no.jld
yes.jld

or, use the channel itself as an iterator (iterating over Tasks is becoming deprecated, along with the produce / consume functionality)

julia> for i in my_channel
         i |> println
       end
no.jld
yes.jld

Alternatively you can use @schedule with bind etc as per the documentation, but it seems like the above is the most straightforward way.


问:
jquery datepicker and asp.net c# empty value
I'm getting really pissed off by this code :D I'm using jQuery datepicker in input field that's set to readonly and the datepicker should appear twice in the same page and it depends on the value of a dropdownlist.

The language i'm using is ASP.NET c#:

the following input textboxes are on my aspx page:

```<code><asp:TextBox ID="txt_check_chequeDate" runat="server" BorderStyle="Solid"
BorderWidth="2px" Font-Names="Calibri" Style="margin-left: 0px" ClientIDMode="Static" ReadOnly="true"></asp:TextBox>

<tr ID="tr_wire_TransactionDate" runat="server">
    <td>
        <asp:Label ID="lbl_wire_TransactionDate" runat="server" Font-Names="Calibri"
            Text="Transaction Date"></asp:Label>
    </td>
    <td>
        <asp:TextBox ID="txt_wire_chequeDate" runat="server" BorderStyle="Solid"
            BorderWidth="2px" ClientIDMode="Static" Font-Names="Calibri"
            Style="margin-left: 0px" ReadOnly="true"></asp:TextBox>
    </td>
</tr>
</code>```

and my jQuery script is as follows with references:

```<code><script type="text/javascript" src="../Scripts/jquery-1.4.1.min.js"></script>
<script src='../Scripts/jquery-1.4.1-vsdoc.js' type='text/javascript'></script>
<script src='../Scripts/jquery.ui.core.js' type='text/javascript'></script>
<script src='../Scripts/jquery.ui.widget.js' type='text/javascript'></script>

<link href='../Styles/jquery.ui.all.css' rel='stylesheet' type='text/css'/>

<link href='../Styles/jquery.ui.datepicker.css' rel='Stylesheet'
type='text/css' />
<script src='../Scripts/jquery.ui.datepicker.js' type='text/javascript'></script>
<script type='text/javascript'>
    $(function () {
        $('#txt_check_chequeDate').datepicker({ changeYear: true });

    });
    $(function () {
       $('#txt_wire_chequeDate').datepicker({ changeYear: true });
    });
</code>```

and when I click the submit button, I get empty value by executing the following:

```<code>Debug.WriteLine("on page click value is wire  =  " + this.txt_wire_chequeDate.Text.Trim());
        Debug.WriteLine("on page click value is cheque  =  " + this.txt_check_chequeDate.Text.Trim());
</code>```

Any idea why I'm getting empty date through datepicker, when i tried eariler i was getting the value correctly for one case only :(

答:
As stated in this post try this:

```<code>txt_wire_chequeDate.Attributes.Add("readonly", "true");
txt_check_chequeDate.Attributes.Add("readonly", "true");
</code>```

and remove Readonly = "true"

Body:
I'm getting really pissed off by this code :D I'm using jQuery datepicker in input field that's set to readonly and the datepicker should appear twice in the same page and it depends on the value of a dropdownlist.

The language i'm using is ASP.NET c#:

the following input textboxes are on my aspx page:

<asp:TextBox ID="txt_check_chequeDate" runat="server" BorderStyle="Solid"
BorderWidth="2px" Font-Names="Calibri" Style="margin-left: 0px" ClientIDMode="Static" ReadOnly="true"></asp:TextBox>

        <asp:Label ID="lbl_wire_TransactionDate" runat="server" Font-Names="Calibri"
            Text="Transaction Date"></asp:Label>

        <asp:TextBox ID="txt_wire_chequeDate" runat="server" BorderStyle="Solid"
            BorderWidth="2px" ClientIDMode="Static" Font-Names="Calibri"
            Style="margin-left: 0px" ReadOnly="true"></asp:TextBox>

and my jQuery script is as follows with references:

<link href='../Styles/jquery.ui.all.css' rel='stylesheet' type='text/css'/>

<link href='../Styles/jquery.ui.datepicker.css' rel='Stylesheet'
type='text/css' />

Body:
As stated in this post try this:

txt_wire_chequeDate.Attributes.Add("readonly", "true");
txt_check_chequeDate.Attributes.Add("readonly", "true");

and remove Readonly = "true"


问:
Making a valid password checker. Can not get my program to get through the if conditions to print a valid password
I have been assigned the following exercise as homework:

Some Web sites impose certain rules for passwords. Write a function that checks whether a string is a valid password. Suppose the password rules are as follows:

A password must have at least eight characters.

A password must consist of only letters and digits.

A password must contain at least two digits.
  Write a program that prompts the user to enter a password and displays valid password if the rules are followed or invalid password otherwise.

I know there's a more efficient and proper way of doing this but i'm just starting out so I don't necessarily need to be those right now. Just want to finish this question.

The counter/ accumulator works and I don't get any errors but I can not fulfill the if condition correctly so that this program prints "valid password"

```<code>password = str(input("Enter in a password to be checked: "))

def valid_password_checker(password):

    from string import ascii_lowercase as alphabet

    digits = '0123456789'  # creates a string of digits
    digit = 0  # acc for digits
    length = 0 # acc for length

    for char in password:  # calls on each character in string
        if char in alphabet:
            length += 1
        if char in digits:
            digit += 1
            if digit >= 2:
                flag = True
                if length >= 8 and digit is True:
                    print("valid password")
                else:
                    print("Password does not contain enough characters or digits.")
            else:
                print("Password does not contain enough digits.")

valid_password_checker(password)
</code>```

答:
you can write something like this:

```<code>password = str(input("What is the password that you want to validate: "))

def get_digits(password):
    return [i for i in password if i.isdigit()]

numbers = ''.join(get_digits(password))

if (len(password) < 8) or (len(numbers) < 2):
    print(password, "is an invalid password")
else:
    print(password, "is a valid password")
</code>```

nice and simple.

Body:
I have been assigned the following exercise as homework:

Some Web sites impose certain rules for passwords. Write a function that checks whether a string is a valid password. Suppose the password rules are as follows:

A password must have at least eight characters.

A password must consist of only letters and digits.

A password must contain at least two digits.
  Write a program that prompts the user to enter a password and displays valid password if the rules are followed or invalid password otherwise.

I know there's a more efficient and proper way of doing this but i'm just starting out so I don't necessarily need to be those right now. Just want to finish this question.

The counter/ accumulator works and I don't get any errors but I can not fulfill the if condition correctly so that this program prints "valid password"

password = str(input("Enter in a password to be checked: "))

def valid_password_checker(password):

    from string import ascii_lowercase as alphabet

    digits = '0123456789'  # creates a string of digits
    digit = 0  # acc for digits
    length = 0 # acc for length

    for char in password:  # calls on each character in string
        if char in alphabet:
            length += 1
        if char in digits:
            digit += 1
            if digit >= 2:
                flag = True
                if length >= 8 and digit is True:
                    print("valid password")
                else:
                    print("Password does not contain enough characters or digits.")
            else:
                print("Password does not contain enough digits.")

valid_password_checker(password)

Body:
you can write something like this:

password = str(input("What is the password that you want to validate: "))

def get_digits(password):
    return [i for i in password if i.isdigit()]

numbers = ''.join(get_digits(password))

if (len(password) < 8) or (len(numbers) < 2):
    print(password, "is an invalid password")
else:
    print(password, "is a valid password")

nice and simple.


问:
There is no error in the code , but also it is not getting executed?
```<code>enrollments=[{'name':'Kinjal','account_key':4149},
            {'name':'Amruta','account_key':4162}]

unique_engagement_students={'name':'Amruta','account_key':4162}

for enrollment in enrollments:
    student = enrollment['account_key']
    if student in unique_engagement_students:
        print (enrollment)
</code>```

答:
Why it didn't work:

it is getting executed. I added a print statement before the if statement and it did get printed.

nothing gets printed doesn't mean the program didn't get executed.In your case the expression inside of if statement never returned true so nothing gets printed. Learn how to use print() to debug or check in the future.

```<code>enrollments=[{'name':'Kinjal','account_key':4149},
            {'name':'Amruta','account_key':4162}]

unique_engagement_students={'name':'Amruta','account_key':4162}

for enrollment in enrollments:
  print("derp")
  student = enrollment['account_key']
  if student in unique_engagement_students:
      print (enrollment)
</code>```

result:

```<code>derp
derp
</code>```

Alternative/Fix:

```<code>enrollments=[{'name':'Kinjal','account_key':4149},
            {'name':'Amruta','account_key':4162}]

unique_engagement_students={'name':'Amruta','account_key':4162}

for enrollment in enrollments:
  student = enrollment['account_key']
  if student in unique_engagement_students.values():
      print (enrollment)
</code>```

the .values() is getting the value inside of unique_engagement_students for you. Before you were comparing student to the unique_engagement_students whole dictionary

see example below:

```<code>print(unique_engagement_students)
print(unique_engagement_students.values())
</code>```

result:

```<code>{'name': 'Amruta', 'account_key': 4162}
dict_values(['Amruta', 4162])
</code>```

I hope this helps and welcome to StackOverflow. If you find this answer or any other answer helpful and solves your problem please mark it as the solution. That way it will help the SO community and if fellow programmers run into the same problem in the future they can find the answer easier. Cheers!

Body:
Why it didn't work:

it is getting executed. I added a print statement before the if statement and it did get printed.

nothing gets printed doesn't mean the program didn't get executed.In your case the expression inside of if statement never returned true so nothing gets printed. Learn how to use print() to debug or check in the future.

enrollments=[{'name':'Kinjal','account_key':4149},
            {'name':'Amruta','account_key':4162}]

unique_engagement_students={'name':'Amruta','account_key':4162}

for enrollment in enrollments:
  print("derp")
  student = enrollment['account_key']
  if student in unique_engagement_students:
      print (enrollment)

result:

derp
derp

Alternative/Fix:

enrollments=[{'name':'Kinjal','account_key':4149},
            {'name':'Amruta','account_key':4162}]

unique_engagement_students={'name':'Amruta','account_key':4162}

for enrollment in enrollments:
  student = enrollment['account_key']
  if student in unique_engagement_students.values():
      print (enrollment)

the .values() is getting the value inside of unique_engagement_students for you. Before you were comparing student to the unique_engagement_students whole dictionary

see example below:

print(unique_engagement_students)
print(unique_engagement_students.values())

result:

{'name': 'Amruta', 'account_key': 4162}
dict_values(['Amruta', 4162])

I hope this helps and welcome to StackOverflow. If you find this answer or any other answer helpful and solves your problem please mark it as the solution. That way it will help the SO community and if fellow programmers run into the same problem in the future they can find the answer easier. Cheers!


问:
Searching the fields 2 level above of associations using Ransack
```<code>class UserGroup
 has_many :users
end
class User
 has_many :posts
end
class Post
end
</code>```

Can we search the fields in user_group in the position of post using ransack?

Thanks!

答:
you may try something like Post.ransack(user_user_group_type_eq: 'admin')

here I am assuming UserGroup class will have a column type and comparing it to value admin

Body:
class UserGroup
 has_many :users
end
class User
 has_many :posts
end
class Post
end

Can we search the fields in user_group in the position of post using ransack?

Thanks!


问:
How to download youtube videos for iphone - using objective-c programmatically

Possible Duplicate:

  Save Youtube video to iPhone in the app

I want to download and save a youtube video from a given youtube video link, programmatically. Can anyone point to some sample app. Help appreciated.

答:
Does the AVAssetWriter class help you at all?

http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAssetWriter_Class/Reference/Reference.html