问:
How can I apply styles online in React with Meteor?
How can I apply styles online in React with Meteor?

I want to use a local image for the background of a container but my code does not work when invoking the image saved in images/borealis.jpg in the public folder.

Try this render but it does not work, it could be wrong with the code

```<code>render() {
        const fondoBorealis = {backgroundImage: 'images/borealis.jpg'};
        return(
            <div className="container-logeo-vitae">
            <div style={{fondoBorealis}} className="logeo-vitae">
                <div className="header wrap">
                    <h1>borealis </h1>
                </div>
                    <div className="form">
                    <center>
                    {this.state.error ? <p>{this.state.error}</p> : undefined}
                        <form className="form-logeo-vitae" onSubmit={this.onSubmit.bind(this)}>
                            <input className="input-logeo" autoComplete="off" type="email" ref="email" placeholder="correo" />
                            <input className="input-logeo" autoComplete="off" type="password" ref="pass" placeholder="••••••••••" />
                            <button className="btn">login</button>
                        </form>
                    <Link to="/registro" className="link-to">crea una cuenta.</Link>
                    </center>
                    </div>
            </div>
            </div>
        );
    }
</code>```

答:
```<code>var co_img = "/images/borealis.jpg";
const sheshema = {
  backgroundImage: "url(" + co_img + ")"
}
<div style={sheshema}>
 </div>
</code>```

This should work. try it.

Body:
How can I apply styles online in React with Meteor?

I want to use a local image for the background of a container but my code does not work when invoking the image saved in images/borealis.jpg in the public folder.

Try this render but it does not work, it could be wrong with the code

render() {
        const fondoBorealis = {backgroundImage: 'images/borealis.jpg'};
        return(

borealis

                    {this.state.error ?
{this.state.error}
 : undefined}
                        <form className="form-logeo-vitae" onSubmit={this.onSubmit.bind(this)}>
                            <input className="input-logeo" autoComplete="off" type="email" ref="email" placeholder="correo" />
                            <input className="input-logeo" autoComplete="off" type="password" ref="pass" placeholder="••••••••••" />
                            <button className="btn">login</button>
                        </form>
                    <Link to="/registro" className="link-to">crea una cuenta.</Link>

        );
    }

Body:
var co_img = "/images/borealis.jpg";
const sheshema = {
  backgroundImage: "url(" + co_img + ")"
}
<div style={sheshema}>
 </div>

This should work. try it.


来源: stackexchange

问:
Batch looping an if statement on the same line
I want to loop the if exist line once so that the line will run continuously until a unused sequential number is found (it has to loop on the same line so it becomes part of the if statement). Is there a better way to achieve this ?

```<code>if exist "*%num%*" (set /a num+=jump)
</code>```

update

```<code>@echo off
set /p usrname=enter folder name
set /a num=100
set /a jump=10

if exist "*%num%*" (set /a num+=jump)

MD %num%_%usrname%
</code>```

答:
How about this?

```<code>@echo off
set /p usrname=enter folder name
set /a num=100
set /a jump=10
:test_exist
if not exist "*%num%*" goto found_one
set /a num+=jump
goto test_exist
:found_one
MD %num%_%usrname%
</code>```

There's technically a race condition in there, but that will only matter if other people/processes are working in the folder at the same time.

ContentLicense: CC BY-SA 3.0

Body:
I want to loop the if exist line once so that the line will run continuously until a unused sequential number is found (it has to loop on the same line so it becomes part of the if statement). Is there a better way to achieve this ?

if exist "*%num%*" (set /a num+=jump)

update

@echo off
set /p usrname=enter folder name
set /a num=100
set /a jump=10

if exist "*%num%*" (set /a num+=jump)

MD %num%_%usrname%

Body:
How about this?

@echo off
set /p usrname=enter folder name
set /a num=100
set /a jump=10
:test_exist
if not exist "*%num%*" goto found_one
set /a num+=jump
goto test_exist
:found_one
MD %num%_%usrname%

There's technically a race condition in there, but that will only matter if other people/processes are working in the folder at the same time.


问:
Error: Hostname/IP doesn't match certificate's altnames:
I am using axios as an HTTP client for node.js

I am using a proxy on localhost and port 8888 so I can sniff network traffic with Charles Proxy for debugging.

```<code> axios.get(`http://example.com',
           { proxy: { host: '127.0.0.1', port: 8888 })
    .then(result => { // })
    .catch(error => { console.log(error) })
</code>```

With this configuration, I often receive this error message:

Error: Hostname/IP doesn't match certificate's altnames:

I read here:
Node.js Hostname/IP doesn't match certificate's altnames
that  I have to configure node.js like this to disable security checks:

```<code>{ rejectUnauthorized : false }
</code>```

My question is how and where exactly do I make that configuration?

答:
I do not know if you solve that. I hope you did. If not, for a known server as it is not safe to do that:

```<code>process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
</code>```

You can put this code in the file that is calling that server.

Body:
I am using axios as an HTTP client for node.js

I am using a proxy on localhost and port 8888 so I can sniff network traffic with Charles Proxy for debugging.

 axios.get(`http://example.com',
           { proxy: { host: '127.0.0.1', port: 8888 })
    .then(result => { // })
    .catch(error => { console.log(error) })

With this configuration, I often receive this error message:

Error: Hostname/IP doesn't match certificate's altnames:

I read here:
Node.js Hostname/IP doesn't match certificate's altnames
that  I have to configure node.js like this to disable security checks:

{ rejectUnauthorized : false }

My question is how and where exactly do I make that configuration?

Body:
I do not know if you solve that. I hope you did. If not, for a known server as it is not safe to do that:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;

You can put this code in the file that is calling that server.


问:
output showing nil result in console when passing
I am new iOS development and still learning basics, my query is when i passed the data to other view controller from my main tableView controller so it is passing smoothly but the output result is showing nil in the console as shown below
here as you can see output in console is nil.This is my second view controller named as movieDetailViewController

below is my main tableView controller from where i am calling my second view controller.

```<code>   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "showDetails", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? movieDetailViewController
    {
        destination.film = movies[(tables.indexPathForSelectedRow?.row)!] as? Movie
    }
  }
}
</code>```

Here the structure Movie is a normal swift file containing attributes that i want to print shown as below:

```<code>import Foundation

struct Movie {

     var title: String
     var overview: String
     var poster_path: String

}
</code>```

Now as i describe that output when passed to another view controller is showing nil. I have been stuck in this problem from 1 week and also searched a lot but no solution helped me in this .

答:
Replace this code in the movieTable View Controller class

```<code> override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? movieDetailViewController
    {
        if let selectedIndex = tables.indexPathForSelectedRow?.row,
            let selectedTitle = movies[selectedIndex]["title"],
            let selectedOverView = movies[selectedIndex]["overview"],
            let selectedPosterPath : String = movies[selectedIndex]["poster_path"] as! String
            {
                destination.film = Movie.init(title: selectedTitle as! String, overView: selectedOverView as! String, posterPath:selectedPosterPath) as! Movie
            }
    }
}
</code>```

Add an initialiser to your struct

```<code>init(title t: String, overView: String, posterPath pp: String) {
    title = t
    overview = overView
    poster_path = pp
}
</code>```

Replace your viewDidLoad code in movieDetailsViewController to

```<code>override func viewDidLoad() {
        super.viewDidLoad()
        if let title = film?.title,
           let movieoverview = film?.overview,
            let urlString = film?.poster_path
        {
            movieTitle.text = title
            print(movieTitle.text)

            movieOverview.text = movieoverview

            print(movieOverview.text)

            let urlString = URL(string: ("http://image.tmdb.org/t/p/w185/") + urlString)
            moviePoster.downloadedFrom(url: urlString!)

        }

    }
</code>```

Hope this helps. Happy Coding.

Body:
I am new iOS development and still learning basics, my query is when i passed the data to other view controller from my main tableView controller so it is passing smoothly but the output result is showing nil in the console as shown below
here as you can see output in console is nil.This is my second view controller named as movieDetailViewController

below is my main tableView controller from where i am calling my second view controller.

   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "showDetails", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? movieDetailViewController
    {
        destination.film = movies[(tables.indexPathForSelectedRow?.row)!] as? Movie
    }
  }
}

Here the structure Movie is a normal swift file containing attributes that i want to print shown as below:

import Foundation

struct Movie {

     var title: String
     var overview: String
     var poster_path: String

}

Now as i describe that output when passed to another view controller is showing nil. I have been stuck in this problem from 1 week and also searched a lot but no solution helped me in this .

Body:
Replace this code in the movieTable View Controller class

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? movieDetailViewController
    {
        if let selectedIndex = tables.indexPathForSelectedRow?.row,
            let selectedTitle = movies[selectedIndex]["title"],
            let selectedOverView = movies[selectedIndex]["overview"],
            let selectedPosterPath : String = movies[selectedIndex]["poster_path"] as! String
            {
                destination.film = Movie.init(title: selectedTitle as! String, overView: selectedOverView as! String, posterPath:selectedPosterPath) as! Movie
            }
    }
}

Add an initialiser to your struct

init(title t: String, overView: String, posterPath pp: String) {
    title = t
    overview = overView
    poster_path = pp
}

Replace your viewDidLoad code in movieDetailsViewController to

override func viewDidLoad() {
        super.viewDidLoad()
        if let title = film?.title,
           let movieoverview = film?.overview,
            let urlString = film?.poster_path
        {
            movieTitle.text = title
            print(movieTitle.text)

            movieOverview.text = movieoverview

            print(movieOverview.text)

            let urlString = URL(string: ("http://image.tmdb.org/t/p/w185/") + urlString)
            moviePoster.downloadedFrom(url: urlString!)

        }

    }

Hope this helps. Happy Coding.


问:
PubSub framework + Core Data?
Is it possible to persist PubSub framework objects in a Core Data persistent store? Or is there a better way to do this...? I'm working on an RSS reader and looking for ways to cache RSS/Atom feeds retrieved by PubSub..

Thanks in advance

答:
It is possible to persist PubSub objects in the persistent store, however, I am not sure if it is needed as I believe those objects are persisted in an operating system database.

Regardless, to do this, all you have to is add a transformable property, i.e. feedObject. The docs have a good explanation of how to do this:DOCS

The only real trick is that you have to import the PubSub framework on the Entity header file.

Like I said though, the feeds and associated entries are all persisted (I believe) in the operating system as long as you subscribe to the feed. The only time it retrieves entries is (a) when you first subscribe to a feed and (b) when it decides that is time to refresh the feed.

If you don't subscribe to the feed and you are only taking the feeds manually then you might want to consider adding them to your persistent store.

ContentLicense: CC BY-SA 2.5

Title: PubSub framework + Core Data?


问:
regex expression in Notepad++
In the following code:

```<code> name="DCF3600" id="DCF3600" onclick="toggle3600dcf()" <?php if($row_getInfo3600["DCF"]==1){
</code>```

I am struggling to figure out how to change the two "DCF3600" to "Admin3600". Every line has a different number which I want to keep. The closet I got was

Find: DCF(\d)

Replace: Admin

But this deletes the 3 from 3600. How do I find DCF next to a digit but leave the digit?

答:
Code

See regex in use here

```<code>\b(?:id|name)="\K\D*
</code>```

Replacement: Admin

You can also use either of the following:

```<code>(?<=")[^\W\d_]+(?=\d+")
(?<=")[a-zA-Z]+(?=\d+")
</code>```

Explanation

\b Assert position as a word boundary

(?:id|name) Match either id or name literally

=" Match this literally

\K Resets the starting point of the reported match. Any previously consumed characters are no longer included in the final match

\D* Match any number of any character except digit

Title: regex expression in Notepad++

Body:
In the following code:

 name="DCF3600" id="DCF3600" onclick="toggle3600dcf()" <?php if($row_getInfo3600["DCF"]==1){

I am struggling to figure out how to change the two "DCF3600" to "Admin3600". Every line has a different number which I want to keep. The closet I got was

Find: DCF(\d)

Replace: Admin

But this deletes the 3 from 3600. How do I find DCF next to a digit but leave the digit?

Body:
Code

See regex in use here

\b(?:id|name)="\K\D*

Replacement: Admin

You can also use either of the following:

(?<=")[^\W\d_]+(?=\d+")
(?<=")[a-zA-Z]+(?=\d+")

Explanation

\b Assert position as a word boundary

(?:id|name) Match either id or name literally

=" Match this literally

\K Resets the starting point of the reported match. Any previously consumed characters are no longer included in the final match

\D* Match any number of any character except digit


问:
Opengl Lighting Artifact (calculating light before translation)
I am trying to create a scene in opengl and I am having trouble with my lighting. I believe it is something to do with translating my models from the origin of the world into their respective places.

I only have 1 light in my scene placed on the right in the centre of the world, however you can see the light on the wall at the front of the scene.

I have wrote my own shaders. I suspect that I'm calculating the lighting too early as it seems that it is being calculated before the models are being translated around the world, that or I am using local coordinates rather than world coordinates (I think thats right anyway...).

(please ignore the glass, they are using a global light and a different shader)

Does anyone know if this is indeed the case or where would be the best place to find a solution.

Below is how I call rendering my models.

```<code>glUseProgram(modelShader);

//center floor mat
if (floorMat)
{
    glUniformMatrix4fv(modelShader_modelMatrixLocation, 1, GL_FALSE, (GLfloat*)&(modelTransform.M));
    floorMat->setTextureForModel(carpetTexture);
    floorMat->renderTexturedModel();
}
</code>```

答:
https://www.youtube.com/watch?annotation_id=annotation_1430411783&feature=iv&index=86&list=PLRwVmtr-pp06qT6ckboaOhnm9FxmzHpbY&src_vid=NH68sIdF-48&v=P3DQXzyjswQ

Turns out I was not calculating the lighting in world space.

Rather than using the transposed modelworldposition I was just using the plain vertex position

Body:
I am trying to create a scene in opengl and I am having trouble with my lighting. I believe it is something to do with translating my models from the origin of the world into their respective places.

I only have 1 light in my scene placed on the right in the centre of the world, however you can see the light on the wall at the front of the scene.

I have wrote my own shaders. I suspect that I'm calculating the lighting too early as it seems that it is being calculated before the models are being translated around the world, that or I am using local coordinates rather than world coordinates (I think thats right anyway...).

(please ignore the glass, they are using a global light and a different shader)

Does anyone know if this is indeed the case or where would be the best place to find a solution.

Below is how I call rendering my models.

glUseProgram(modelShader);

//center floor mat
if (floorMat)
{
    glUniformMatrix4fv(modelShader_modelMatrixLocation, 1, GL_FALSE, (GLfloat*)&(modelTransform.M));
    floorMat->setTextureForModel(carpetTexture);
    floorMat->renderTexturedModel();
}


问:
Replace if/else statement with pattern
In the code below, I'm trying to determine what the business date should be depending on if the month to date (mtd) indicator is true or if the previous 2 business date (btd) indicator is true.

Currently, if I come up with another indicator then I'll have to include another else if statement.

I've read that the approach to make this code easier to maintain is to use the Factory Design pattern.  However, I'm not sure what steps to take in order to implement the pattern.

Here is the code:

```<code>    public static string GetBusDate(bool mtdIndicator, bool prev2BusDtInd)
    {
        string busDate = Helper.PreviousBusinessDate;

        if (mtdIndicator)
        {
            busDate = Helper.FOMBusDt;
        }
        else if (prev2BusDtInd)
        {
            busDate = Helper.Previous2BusinessDate;
        }

        return busDate;
    }
</code>```

答:
The Factory Pattern (Factory Method && Abstract Factory) is not going to work well for your use case, because this pattern will only force you to create a couple of classes for each if statement and the pattern usually returns an abstract object to your client code to consume (not your case because you're returning a simple string).

You also can't use a Simple Factory (which is not a design pattern) because will only move the conditional logic into a single class, so your code design will not improve.

You should not use a design pattern just increase the complexity of your code without the benefits of flexibility.

For your use case I would simply leave it as an if/else statement using a  single line of code.

```<code>return mtdIndicator ? Helper.FOMBusDt :
       prev2BusDtInd ? Helper.Previous2BusinessDate :
                       Helper.PreviousBusinessDate;
</code>```

If you want to replace conditionals with polymorphism you should try:

Chain-of-Responsibility Pattern

Strategy Pattern

Decorator Pattern

... or other patterns (depends on the overall architecture)

Also you can avoid ifs by following 'Tell DON'T Ask'.

You should send a request to your low level component to do task X

You should NOT ask a low level component about it's internal
context / state (you do that by avoiding functions like isStateXOk():Boolean)

TIP: Don't avoid a short if/else statement by creating from 3 to 10+ classes, avoid a switch by making classes for each case branch.

Title: Replace if/else statement with pattern

Body:
In the code below, I'm trying to determine what the business date should be depending on if the month to date (mtd) indicator is true or if the previous 2 business date (btd) indicator is true.

Currently, if I come up with another indicator then I'll have to include another else if statement.

I've read that the approach to make this code easier to maintain is to use the Factory Design pattern.  However, I'm not sure what steps to take in order to implement the pattern.

Here is the code:

    public static string GetBusDate(bool mtdIndicator, bool prev2BusDtInd)
    {
        string busDate = Helper.PreviousBusinessDate;

        if (mtdIndicator)
        {
            busDate = Helper.FOMBusDt;
        }
        else if (prev2BusDtInd)
        {
            busDate = Helper.Previous2BusinessDate;
        }

        return busDate;
    }

Body:
The Factory Pattern (Factory Method && Abstract Factory) is not going to work well for your use case, because this pattern will only force you to create a couple of classes for each if statement and the pattern usually returns an abstract object to your client code to consume (not your case because you're returning a simple string).

You also can't use a Simple Factory (which is not a design pattern) because will only move the conditional logic into a single class, so your code design will not improve.

You should not use a design pattern just increase the complexity of your code without the benefits of flexibility.

For your use case I would simply leave it as an if/else statement using a  single line of code.

return mtdIndicator ? Helper.FOMBusDt :
       prev2BusDtInd ? Helper.Previous2BusinessDate :
                       Helper.PreviousBusinessDate;

If you want to replace conditionals with polymorphism you should try:

Chain-of-Responsibility Pattern

Strategy Pattern

Decorator Pattern

... or other patterns (depends on the overall architecture)

Also you can avoid ifs by following 'Tell DON'T Ask'.

You should send a request to your low level component to do task X

You should NOT ask a low level component about it's internal
context / state (you do that by avoiding functions like isStateXOk():Boolean)

TIP: Don't avoid a short if/else statement by creating from 3 to 10+ classes, avoid a switch by making classes for each case branch.


问:
How do I extract the particular row from .csv file and write out in to another file
I have .csv file something like this:

```<code>x,   y,   z
1,  10,   45
2,   0,   34
4,  15,   34
5,  99,   38
6,  13,   23
5,  99,   38
6,  13,   23
.    .     .
1000, 234, 678
</code>```

now I would like to write out the rows of column x, which can be advisable by 5 form this .csv file.

Here is the more detail about the file:

```<code>x,                  y
0.0000123219872323, 1.213
.                     .
4.991414887967266,  8.123
4.996324047550014,  2.323
5.000581861276573,  6.234
5.006295444400881,  9.234
5.029657671211434,  1.219
5.034806828096650,  1.123
.                   .
9.997414351064347,  1.345
10.00211537343025,  1.232
10.00675672507283,  2.234
10.01201110041457,  1.003
.                   .
</code>```

Here is the real file that I want to process. I have to extract the rows from this .csv file. In particular, rows of the column values which can be dividable by 5.

My output should look like this:

```<code>5.000581861276573,  6.234
10.00211537343025,  1.232
</code>```

Not twice the values of 5, 10 and so on. Once one 5 value is extracted,
it should go to next divisible by 5, in this case it should be 10.

答:
```<code>archive_in = open('lines.txt', 'r')
archive_out = open('out.txt', 'w')
i = 0
for line in archive_in.readlines():
    i += 1
    if i == 2:
        archive_out.write(line)
        i = 3
    elif i == 7:
        archive_out.write(line)
        i = 2

archive_in.close()
archive_out.close()
</code>```

EDIT, now write lines with closest values to list inputs.

```<code>import pandas as pd

df = pd.read_csv('lines.txt', header=None)
archive_out = open('out.txt', 'w')
inputs = (1, 5, 10)

for input in inputs:

    archive_out.write(str(df.ix[(df[0] - input).abs().argsort()[:1]].values[0])[1:-1].strip() + '\n')

archive_out.close()
</code>```

Body:
I have .csv file something like this:

x,   y,   z
1,  10,   45
2,   0,   34
4,  15,   34
5,  99,   38
6,  13,   23
5,  99,   38
6,  13,   23
.    .     .
1000, 234, 678

now I would like to write out the rows of column x, which can be advisable by 5 form this .csv file.

Here is the more detail about the file:

x,                  y
0.0000123219872323, 1.213
.                     .
4.991414887967266,  8.123
4.996324047550014,  2.323
5.000581861276573,  6.234
5.006295444400881,  9.234
5.029657671211434,  1.219
5.034806828096650,  1.123
.                   .
9.997414351064347,  1.345
10.00211537343025,  1.232
10.00675672507283,  2.234
10.01201110041457,  1.003
.                   .

Here is the real file that I want to process. I have to extract the rows from this .csv file. In particular, rows of the column values which can be dividable by 5.

My output should look like this:

5.000581861276573,  6.234
10.00211537343025,  1.232

Not twice the values of 5, 10 and so on. Once one 5 value is extracted,
it should go to next divisible by 5, in this case it should be 10.

Body:
archive_in = open('lines.txt', 'r')
archive_out = open('out.txt', 'w')
i = 0
for line in archive_in.readlines():
    i += 1
    if i == 2:
        archive_out.write(line)
        i = 3
    elif i == 7:
        archive_out.write(line)
        i = 2

archive_in.close()
archive_out.close()

EDIT, now write lines with closest values to list inputs.

import pandas as pd

df = pd.read_csv('lines.txt', header=None)
archive_out = open('out.txt', 'w')
inputs = (1, 5, 10)

for input in inputs:

    archive_out.write(str(df.ix[(df[0] - input).abs().argsort()[:1]].values[0])[1:-1].strip() + '\n')

archive_out.close()


问:
OOP/Function Help
I would like some recommendations on the following situation:

I have to build a page that shows all data from 2 tables on a page called "view" with box down below that says "edit".  On the edit page they have the option to edit one row and all of the 2nd table.

How would you write the functions for this.  Would you have each individual row as a function?  or would you combine it into one big function?  - if so how?

Thanks

Jess

答:
It's hard to answer this question, since functionality of your website and relations between object are not clear.

Generally, if you are doing two non-related actions with significantly different abstractions, I'd recommend to separate these actions into two different methods or even classes. Each functionality unit must have specific responsibilities.

Title: OOP/Function Help


答:
If you want to write out each 5th row you can simply do

```<code>df.iloc[::5, :].to_csv('file_name.csv')
</code>```

whereby df is a pandas dataframe created like this:

```<code>import pandas as pd
df = pd.read_csv('input.csv')
</code>```

Otherwise, you can also do

```<code># define all indexes here
out_rows = [1, 5]

df.iloc[out_rows, :].to_csv('file_name.csv')
</code>```

You need to specify in more detail what exactly you want to achieve, then we can help better.

EDIT:

As far as I understand now, you want to select based on floats close to certain values. This might be a bit hacky and also assumes that you don't leave out integers (which seems to be a reasonable assumption based on your description of the values):

Let's say your df looks like this (replace by actual data):

```<code>          x,  y
0   0.955425  1
1   0.602229  2
2   1.520194  6
3   1.748095  1
4   2.422760  0
5   2.051359  6
6   3.268572  9
7   3.981412  1
8   4.687532  0
9   4.215138  8
10  5.029877  7
11  5.197888  7
12  6.795040  1
13  6.452637  0
14  7.413032  8
15  7.127841  5
16  8.597014  7
17  8.002060  8
18  9.713273  3
19  9.912318  7
</code>```

As written, first sort the values according to x,

```<code>df = df.sort_values('x,')

          x,  y
1   0.602229  2
0   0.955425  1
2   1.520194  6
3   1.748095  1
5   2.051359  6
4   2.422760  0
6   3.268572  9
7   3.981412  1
9   4.215138  8
8   4.687532  0
10  5.029877  7
11  5.197888  7
13  6.452637  0
12  6.795040  1
15  7.127841  5
14  7.413032  8
17  8.002060  8
16  8.597014  7
18  9.713273  3
19  9.912318  7
</code>```

Then add a helper column where you floor the values in x,

```<code>df['helper'] = df['x,'].apply(np.floor).astype(int)

          x,  y  helper
1   0.602229  2       0
0   0.955425  1       0
2   1.520194  6       1
3   1.748095  1       1
5   2.051359  6       2
4   2.422760  0       2
6   3.268572  9       3
7   3.981412  1       3
9   4.215138  8       4
8   4.687532  0       4
10  5.029877  7       5
11  5.197888  7       5
13  6.452637  0       6
12  6.795040  1       6
15  7.127841  5       7
14  7.413032  8       7
17  8.002060  8       8
16  8.597014  7       8
18  9.713273  3       9
19  9.912318  7       9
</code>```

Now drop the duplicates in helper:

```<code>df = df.drop_duplicates('helper')

          x,  y  helper
1   0.602229  2       0
2   1.520194  6       1
5   2.051359  6       2
6   3.268572  9       3
9   4.215138  8       4
10  5.029877  7       5
13  6.452637  0       6
15  7.127841  5       7
17  8.002060  8       8
18  9.713273  3       9
</code>```

and export the solution:

```<code>df.iloc[::5, :].drop('helper', axis=1)

          x,  y
1   0.602229  2
10  5.029877  7
</code>```

Title: How do I extract the particular row from .csv file and write out in to another file

Body:
If you want to write out each 5th row you can simply do

df.iloc[::5, :].to_csv('file_name.csv')

whereby df is a pandas dataframe created like this:

import pandas as pd
df = pd.read_csv('input.csv')

Otherwise, you can also do

# define all indexes here
out_rows = [1, 5]

df.iloc[out_rows, :].to_csv('file_name.csv')

You need to specify in more detail what exactly you want to achieve, then we can help better.

EDIT:

As far as I understand now, you want to select based on floats close to certain values. This might be a bit hacky and also assumes that you don't leave out integers (which seems to be a reasonable assumption based on your description of the values):

Let's say your df looks like this (replace by actual data):

          x,  y
0   0.955425  1
1   0.602229  2
2   1.520194  6
3   1.748095  1
4   2.422760  0
5   2.051359  6
6   3.268572  9
7   3.981412  1
8   4.687532  0
9   4.215138  8
10  5.029877  7
11  5.197888  7
12  6.795040  1
13  6.452637  0
14  7.413032  8
15  7.127841  5
16  8.597014  7
17  8.002060  8
18  9.713273  3
19  9.912318  7

As written, first sort the values according to x,

df = df.sort_values('x,')

          x,  y
1   0.602229  2
0   0.955425  1
2   1.520194  6
3   1.748095  1
5   2.051359  6
4   2.422760  0
6   3.268572  9
7   3.981412  1
9   4.215138  8
8   4.687532  0
10  5.029877  7
11  5.197888  7
13  6.452637  0
12  6.795040  1
15  7.127841  5
14  7.413032  8
17  8.002060  8
16  8.597014  7
18  9.713273  3
19  9.912318  7

Then add a helper column where you floor the values in x,

df['helper'] = df['x,'].apply(np.floor).astype(int)

          x,  y  helper
1   0.602229  2       0
0   0.955425  1       0
2   1.520194  6       1
3   1.748095  1       1
5   2.051359  6       2
4   2.422760  0       2
6   3.268572  9       3
7   3.981412  1       3
9   4.215138  8       4
8   4.687532  0       4
10  5.029877  7       5
11  5.197888  7       5
13  6.452637  0       6
12  6.795040  1       6
15  7.127841  5       7
14  7.413032  8       7
17  8.002060  8       8
16  8.597014  7       8
18  9.713273  3       9
19  9.912318  7       9

Now drop the duplicates in helper:

df = df.drop_duplicates('helper')

          x,  y  helper
1   0.602229  2       0
2   1.520194  6       1
5   2.051359  6       2
6   3.268572  9       3
9   4.215138  8       4
10  5.029877  7       5
13  6.452637  0       6
15  7.127841  5       7
17  8.002060  8       8
18  9.713273  3       9

and export the solution:

df.iloc[::5, :].drop('helper', axis=1)

          x,  y
1   0.602229  2
10  5.029877  7


问:
Mixing futures and vectors in a for comprehension
I'd like to iterate over a vector that I get from a future.  I'd like the following to work, but it gives a type mismatch compiler error on the user <- usersToReview line.

```<code>import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
import scala.concurrent.duration._

object Main3 {
  var counter = 0

  val fUsersToReview: Future[Vector[String]] = Future {Vector("u1", "u2", "u3")}

  def doIt(user: String): Future[Int] = {
    counter = counter + 1
    Future.successful(counter)
  }

  def main(args: Array[String]): Unit = {
    val result:Future[Vector[Int]] = for {
      usersToReview ← fUsersToReview
      user ← usersToReview
      msg_id ← doIt(user)
    } yield {
      msg_id
    }

    println(Await.result(result, 1.second))
  }
}
</code>```

The following works, but seems very clunky.  Suggestions on how to improve this?

```<code>  def main(args: Array[String]): Unit = {
    val result:Future[Vector[Int]] = (for {
      usersToReview ← fUsersToReview
    } yield {

      Future.sequence(
        for (u ← usersToReview) yield {
          doIt(u)
        }
      )
    }).flatMap(identity)

    println(Await.result(result, 1.second))
  }
}
</code>```

答:
This is one instance where it's probably cleaner to not use a for-comprehension and instead just use map:

```<code>val result: Future[Vector[Int]] = fUsersToReview.map(_.map(doIt(_)))
</code>```

For things like Option and Either, you can use monad transformers like OptionT and EitherT, but there isn't anything for Vector.

Body:
I'd like to iterate over a vector that I get from a future.  I'd like the following to work, but it gives a type mismatch compiler error on the user <- usersToReview line.

import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
import scala.concurrent.duration._

object Main3 {
  var counter = 0

  val fUsersToReview: Future[Vector[String]] = Future {Vector("u1", "u2", "u3")}

  def doIt(user: String): Future[Int] = {
    counter = counter + 1
    Future.successful(counter)
  }

  def main(args: Array[String]): Unit = {
    val result:Future[Vector[Int]] = for {
      usersToReview ← fUsersToReview
      user ← usersToReview
      msg_id ← doIt(user)
    } yield {
      msg_id
    }

    println(Await.result(result, 1.second))
  }
}

The following works, but seems very clunky.  Suggestions on how to improve this?

  def main(args: Array[String]): Unit = {
    val result:Future[Vector[Int]] = (for {
      usersToReview ← fUsersToReview
    } yield {

      Future.sequence(
        for (u ← usersToReview) yield {
          doIt(u)
        }
      )
    }).flatMap(identity)

    println(Await.result(result, 1.second))
  }
}

Body:
This is one instance where it's probably cleaner to not use a for-comprehension and instead just use map:

val result: Future[Vector[Int]] = fUsersToReview.map(_.map(doIt(_)))

For things like Option and Either, you can use monad transformers like OptionT and EitherT, but there isn't anything for Vector.


问:
C Research vowel and consonant with fork()
As the title says I'm tryng to create a program in C in which 2 son process research a vowel(son2) and a consonant(son2). To perform the research i use 2 function, the first to research a vowel and the second to research a consonant.
I give to the program 3 more file from command line:

-1° is the file in which is stored a combination of vowel and consonant

-2° is the file in which will be stored all the vowel founded

-3° is the file in which will be stored all the consonant founded

The program is compiled without error/warning but it doesn't complete the research correctly, here is an example:

-first file: qwerty

-second file: ey

-third file: qr

```<code>#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctype.h>

int test_vowel(char ch)
{
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'y')
    return(1);
else
    return(0);
}

int main(int argc, char *argv[])
{
char c, d;
int s;
pid_t pid1 = 10, pid2 = 10;

if((pid1 = fork()) < 0)
{
  printf("Error in the creation of the first fork\n");
  _exit(0);
}
if(pid1 > 0)
{
 if((pid2 = fork()) < 0)
    {
      printf("Error in the creation of the second fork\n");
      _exit(0);
    }
}

int input = open(argv[1],O_RDONLY);
int output1 = open(argv[2],O_RDWR | O_CREAT | O_TRUNC, 0666);
int output2 = open(argv[3],O_RDWR | O_CREAT | O_TRUNC, 0666);

if(pid2 == 0)
    {
     while((s = read(input, &c, 1)) != 0)
        {
         if(test_vowel(tolower(c)) == 1)
            {
             printf("I've read a vowel = %d\n", d);
             write(output1, &c, 1);
            }
        }
    }

if(pid1 == 0)
    {
     while((s = read(input, &d, 1)) != 0)
        {
         if(test_vowel(tolower(d)) == 0)
            {
             printf("I've read a consonant = %d\n", d);
             write(output2, &d,1);
            }
        }
    }

}
</code>```

I use these command to compile it

```<code>gcc c.c
./a.out c.txt v.txt b.txt
</code>```

Thanks in advance for the help!

EDIT(final)
  Code (now is working) simplified following all of the tips of David C. Rankin

答: You don't initialize pid1 or pid2 to any particular value. And if pid1 is zero, you don't set pid2 to any value at all. But your first if checks the value of pid2. That can't be right.

Body:
As the title says I'm tryng to create a program in C in which 2 son process research a vowel(son2) and a consonant(son2). To perform the research i use 2 function, the first to research a vowel and the second to research a consonant.
I give to the program 3 more file from command line:

-1° is the file in which is stored a combination of vowel and consonant

-2° is the file in which will be stored all the vowel founded

-3° is the file in which will be stored all the consonant founded

The program is compiled without error/warning but it doesn't complete the research correctly, here is an example:

-first file: qwerty

-second file: ey

-third file: qr

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctype.h>

int test_vowel(char ch)
{
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'y')
    return(1);
else
    return(0);
}

int main(int argc, char *argv[])
{
char c, d;
int s;
pid_t pid1 = 10, pid2 = 10;

if((pid1 = fork()) < 0)
{
  printf("Error in the creation of the first fork\n");
  _exit(0);
}
if(pid1 > 0)
{
 if((pid2 = fork()) < 0)
    {
      printf("Error in the creation of the second fork\n");
      _exit(0);
    }
}

int input = open(argv[1],O_RDONLY);
int output1 = open(argv[2],O_RDWR | O_CREAT | O_TRUNC, 0666);
int output2 = open(argv[3],O_RDWR | O_CREAT | O_TRUNC, 0666);

if(pid2 == 0)
    {
     while((s = read(input, &c, 1)) != 0)
        {
         if(test_vowel(tolower(c)) == 1)
            {
             printf("I've read a vowel = %d\n", d);
             write(output1, &c, 1);
            }
        }
    }

if(pid1 == 0)
    {
     while((s = read(input, &d, 1)) != 0)
        {
         if(test_vowel(tolower(d)) == 0)
            {
             printf("I've read a consonant = %d\n", d);
             write(output2, &d,1);
            }
        }
    }

}

I use these command to compile it

gcc c.c
./a.out c.txt v.txt b.txt

Thanks in advance for the help!

EDIT(final)
  Code (now is working) simplified following all of the tips of David C. Rankin


问:
How to pass object as paramaters to function?
I have defination of function:

```<code>def setup(self, **kwargs):
    pass
</code>```

And calling this like:

```<code>params = {
        "advert_id": adv_id,
        "enabled": True,
        "from_hour": 2,
        "to_hour": 1,
        "interval": 0,
        "weekdays": [1]
    }

setup(params)
</code>```

I tried to pass params as object, but it does not work. I know correct way is:

```<code>setup(advert_id=1,enabled=True,from_hour=3,to_hour=4,interval=0,weekdays=[])
</code>```

Anyway I don't want to enumerate all parameters and want to pack it to object.

答:
Unpack params in the function call:

```<code>def setup(self, **kwargs):
   pass
params = {
    "advert_id": adv_id,
    "enabled": True,
    "from_hour": 2,
    "to_hour": 1,
    "interval": 0,
    "weekdays": [1]
}

setup(**params)
</code>```

Body:
I have defination of function:

def setup(self, **kwargs):
    pass

And calling this like:

params = {
        "advert_id": adv_id,
        "enabled": True,
        "from_hour": 2,
        "to_hour": 1,
        "interval": 0,
        "weekdays": [1]
    }

setup(params)

I tried to pass params as object, but it does not work. I know correct way is:

setup(advert_id=1,enabled=True,from_hour=3,to_hour=4,interval=0,weekdays=[])

Anyway I don't want to enumerate all parameters and want to pack it to object.

Body:
Unpack params in the function call:

def setup(self, **kwargs):
   pass
params = {
    "advert_id": adv_id,
    "enabled": True,
    "from_hour": 2,
    "to_hour": 1,
    "interval": 0,
    "weekdays": [1]
}

setup(**params)


答:
crude example using the pandas library which convert the csv into a data-frame.

```<code>import pandas as pd

df = pd.read_csv('asdf.csv')
for i in range(200+1):
     df.iloc[i*5]
</code>```

This is assuming you want to go up in 5's

Body:
crude example using the pandas library which convert the csv into a data-frame.

import pandas as pd

df = pd.read_csv('asdf.csv')
for i in range(200+1):
     df.iloc[i*5]

This is assuming you want to go up in 5's


问:
Split a 2d array creating array from row to row values with unitary displacement
I want to split a 2D array this way:

Example:

From this 4x4 2D array:

```<code>np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
</code>```

Create these five 2x2 2D arrays, with unitary displacement (shift):

```<code>np.array([[1,2],[3,4]])
np.array([[4,5],[6,7]])
np.array([[7,8],[9,10]])
np.array([[10,11],[12,13]])
np.array([[13,14],[15,16]])
</code>```

In a general case, from an NXN 2D array (square arrays) create Y 2D arrays of MXM shape, as many as possible.

Just to be more precise: to create the output array, not necessarily it will be made of all values from the row.

Example:

From a 2D 8x8 array, with values from 1 to 64, if I want to split this array in 2D 2x2 arrays, the first row from 8x8 array is a row from 1 to 8, and the first output 2D 2x2 array will be np.array([[1,2],[3,4]]), and the second output 2D 2x2 array will be np.array([[4,5],[6,7]])... It continues until the last output 2D array, that will be np.array([[61,62],[63,64]]). Look that each 2D 2x2 array was not filled with all the values from the row (CORRECT). And that exists a unitary displacement (shift) from previous array to next array.

There is a Numpy method that do this?

MSeifert answered here (How to split an 2D array, creating arrays from "row to row" values) a question that solves almost 95% of this question, except the unitary displacement (shift) part.

So, from the 4x4 2D array example:

```<code>np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
</code>```

Instead of create these FOUR 2x2 2D arrays (without unitary shift/displacement):

```<code>np.array([[1,2],[3,4]])
np.array([[5,6],[7,8]])
np.array([[9,10],[11,12]])
np.array([[13,14],[15,16]])
</code>```

Create these FIVE 2x2 2D arrays (with unitary shift/displacement):

```<code>np.array([[1,2],[3,4]])
np.array([[4,5],[6,7]])
np.array([[7,8],[9,10]])
np.array([[10,11],[12,13]])
np.array([[13,14],[15,16]])
</code>```

And, of course, it should work for the general case of, given a square NXN 2D array, to create Y MXM square 2D arrays.

Example: from a 60x60 square 2d array, create Y MXM square 2D arrays (10x10, for example).

Plus: I need to know what is the rule that relates the number of points of the original square 2D array (4x4 2D array, in the example), with points of mini square 2D arrays (2X2 2D arrays, in the example). In the case, given 16 points (4x4 2D array), it is possible create 5 2x2 2D arrays (each one with 4 points).

答:
The condition for the subarrays to exactly fit is (M+1)*(M-1) divides (N+1)*(N-1), the number of subarrays you can put is the quotient of these numbers. Note that these numbers are equal to M*M-1 and N*N-1. In this form the rule also applies to non square matrices.

Examples

```<code>M      N      M*M-1  N*N-1  Y
-----------------------------
3      5      8      24     3
3      7      8      48     6
5      7      24     48     2
4      11     15     120    8
</code>```

Implementation: Please note that this returns overlapping views into the original array. If you want to modify them you may want to make a copy. Also note that this implementation fits as many subsquares as fit, any leftover elements in the larger matrix are dropped.

Update: I've added two functions which calculate given N all possible M and vice versa.

Output:

```<code># Testing predictions ...
# ok

# M = 105
# solutions: [105, 1273, 1377, 4135, 4239, 5407, 5511, 5513]
# this pattern repeats at offsets 5512, 11024, 16536, ...

# N = 1000001
# solutions: [2, 3, 4, 5, 7, 9, 11, 31, 49, 1000001]

# example N, M = (5, 3)
# [[[ 0  1  2]
#   [ 3  4  5]
#   [ 6  7  8]]

#  [[ 8  9 10]
#   [11 12 13]
#   [14 15 16]]

#  [[16 17 18]
#   [19 20 21]
#   [22 23 24]]]
</code>```

Code:

```<code>import numpy as np
import sympy
import itertools as it
import functools as ft
import operator as op

def get_subsquares(SqNN, M0, M1=None):
    M1 = M0 if M1 is None else M1
    N0, N1 = SqNN.shape
    K = (N0*N1-1) // (M0*M1-1)
    SqNN = SqNN.ravel()
    s, = SqNN.strides
    return np.lib.stride_tricks.as_strided(SqNN, (K, M0, M1),
                                           (s*(M0*M1-1), s*M1, s))

def get_M_for_N(N):
    """Given N return all possible M
    """
    assert N >= 2
    f = 1 + (N & 1)
    factors = sympy.factorint((N+1)//f)
    factors.update(sympy.factorint((N-1)//f))
    if f == 2:
        factors[2] += 2
    factors = [ft.reduce(op.mul, fs) for fs in it.product(
        *([a**k for k in range(n+1)] for a, n in factors.items()))]
    return [fs + 1 for fs in sorted(set(factors) & set(fs - 2 for fs in factors)) if (N*N-1) % (fs * (fs+2)) == 0]

def get_N_for_M(M):
    """Given M return all possible N in the form period, smallest

    smallest is a list of all solutions between M and M*M if M is even
    and between M and (M*M+1) / 2 if M is odd, all other solutions can be
    obtained by adding multiples of period
    """
    assert M >= 2
    f = 1 + (M & 1)
    factors = sympy.factorint((M+1)//f)
    factors.update(sympy.factorint((M-1)//f))
    factors = [k**v for k, v in factors.items()]
    rep = (M+1)*(M-1) // f
    f0 = [ft.reduce(op.mul, fs) for fs in it.product(*zip(it.repeat(1), factors))]
    f1 = [rep // (f*a) for a in f0]
    inv = [f if b==1 else f*b + 2 if a==1 else 2 * sympy.mod_inverse(a, b)
           for a, b in zip(f1, f0)]
    if f==1:
        inv[1:-1] = [a%b for a, b in zip(inv[1:-1], f0[1:-1])]
    return rep, sorted(a*b - 1 for a, b in zip(f1, inv))

def test_predict(N):
    def brute_force(a, b):
        return [i for i in range(a, b) if (i*i-1) % (a*a-1) == 0]
    for x in range(2, N+1):
        period, pred = get_N_for_M(x)
        assert brute_force(x, period*4+2) \
            == [a + b for b in range(0, 4*period, period) for a in pred]
    def brute_force(b):
        return [i for i in range(2, b+1) if (b*b-1) % (i*i-1) == 0]
    for x in range(2, N+1):
        assert brute_force(x) == get_M_for_N(x)
    print('ok')

# test
print("Testing predictions ...")
test_predict(200)
print()
# examples
M = 105
period, pred = get_N_for_M(M)
print(f"M = {M}")
print(f"solutions: {pred}")
print(f"this pattern repeats at offsets {period}, {2*period}, {3*period}, ...")
print()
N = 1000001
pred = get_M_for_N(N)
print(f"N = {N}")
print(f"solutions: {pred}")
print()
N, M = 5, 3
SqNN = np.arange(N*N).reshape(N, N)
print(f"example N, M = ({N}, {M})")
print(get_subsquares(SqNN, M))
</code>```

Body:
I want to split a 2D array this way:

Example:

From this 4x4 2D array:

np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])

Create these five 2x2 2D arrays, with unitary displacement (shift):

np.array([[1,2],[3,4]])
np.array([[4,5],[6,7]])
np.array([[7,8],[9,10]])
np.array([[10,11],[12,13]])
np.array([[13,14],[15,16]])

In a general case, from an NXN 2D array (square arrays) create Y 2D arrays of MXM shape, as many as possible.

Just to be more precise: to create the output array, not necessarily it will be made of all values from the row.

Example:

From a 2D 8x8 array, with values from 1 to 64, if I want to split this array in 2D 2x2 arrays, the first row from 8x8 array is a row from 1 to 8, and the first output 2D 2x2 array will be np.array([[1,2],[3,4]]), and the second output 2D 2x2 array will be np.array([[4,5],[6,7]])... It continues until the last output 2D array, that will be np.array([[61,62],[63,64]]). Look that each 2D 2x2 array was not filled with all the values from the row (CORRECT). And that exists a unitary displacement (shift) from previous array to next array.

There is a Numpy method that do this?

MSeifert answered here (How to split an 2D array, creating arrays from "row to row" values) a question that solves almost 95% of this question, except the unitary displacement (shift) part.

So, from the 4x4 2D array example:

np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])

Instead of create these FOUR 2x2 2D arrays (without unitary shift/displacement):

np.array([[1,2],[3,4]])
np.array([[5,6],[7,8]])
np.array([[9,10],[11,12]])
np.array([[13,14],[15,16]])

Create these FIVE 2x2 2D arrays (with unitary shift/displacement):

np.array([[1,2],[3,4]])
np.array([[4,5],[6,7]])
np.array([[7,8],[9,10]])
np.array([[10,11],[12,13]])
np.array([[13,14],[15,16]])

And, of course, it should work for the general case of, given a square NXN 2D array, to create Y MXM square 2D arrays.

Example: from a 60x60 square 2d array, create Y MXM square 2D arrays (10x10, for example).

Plus: I need to know what is the rule that relates the number of points of the original square 2D array (4x4 2D array, in the example), with points of mini square 2D arrays (2X2 2D arrays, in the example). In the case, given 16 points (4x4 2D array), it is possible create 5 2x2 2D arrays (each one with 4 points).

Body:
The condition for the subarrays to exactly fit is (M+1)*(M-1) divides (N+1)*(N-1), the number of subarrays you can put is the quotient of these numbers. Note that these numbers are equal to M*M-1 and N*N-1. In this form the rule also applies to non square matrices.

Examples

M      N      M*M-1  N*N-1  Y
-----------------------------
3      5      8      24     3
3      7      8      48     6
5      7      24     48     2
4      11     15     120    8

Implementation: Please note that this returns overlapping views into the original array. If you want to modify them you may want to make a copy. Also note that this implementation fits as many subsquares as fit, any leftover elements in the larger matrix are dropped.

Update: I've added two functions which calculate given N all possible M and vice versa.

Output:

# Testing predictions ...
# ok

# M = 105
# solutions: [105, 1273, 1377, 4135, 4239, 5407, 5511, 5513]
# this pattern repeats at offsets 5512, 11024, 16536, ...

# N = 1000001
# solutions: [2, 3, 4, 5, 7, 9, 11, 31, 49, 1000001]

# example N, M = (5, 3)
# [[[ 0  1  2]
#   [ 3  4  5]
#   [ 6  7  8]]

#  [[ 8  9 10]
#   [11 12 13]
#   [14 15 16]]

#  [[16 17 18]
#   [19 20 21]
#   [22 23 24]]]

Code:

import numpy as np
import sympy
import itertools as it
import functools as ft
import operator as op

def get_subsquares(SqNN, M0, M1=None):
    M1 = M0 if M1 is None else M1
    N0, N1 = SqNN.shape
    K = (N0*N1-1) // (M0*M1-1)
    SqNN = SqNN.ravel()
    s, = SqNN.strides
    return np.lib.stride_tricks.as_strided(SqNN, (K, M0, M1),
                                           (s*(M0*M1-1), s*M1, s))

def get_M_for_N(N):
    """Given N return all possible M
    """
    assert N >= 2
    f = 1 + (N & 1)
    factors = sympy.factorint((N+1)//f)
    factors.update(sympy.factorint((N-1)//f))
    if f == 2:
        factors[2] += 2
    factors = [ft.reduce(op.mul, fs) for fs in it.product(
        *([a**k for k in range(n+1)] for a, n in factors.items()))]
    return [fs + 1 for fs in sorted(set(factors) & set(fs - 2 for fs in factors)) if (N*N-1) % (fs * (fs+2)) == 0]

def get_N_for_M(M):
    """Given M return all possible N in the form period, smallest

    smallest is a list of all solutions between M and M*M if M is even
    and between M and (M*M+1) / 2 if M is odd, all other solutions can be
    obtained by adding multiples of period
    """
    assert M >= 2
    f = 1 + (M & 1)
    factors = sympy.factorint((M+1)//f)
    factors.update(sympy.factorint((M-1)//f))
    factors = [k**v for k, v in factors.items()]
    rep = (M+1)*(M-1) // f
    f0 = [ft.reduce(op.mul, fs) for fs in it.product(*zip(it.repeat(1), factors))]
    f1 = [rep // (f*a) for a in f0]
    inv = [f if b==1 else f*b + 2 if a==1 else 2 * sympy.mod_inverse(a, b)
           for a, b in zip(f1, f0)]
    if f==1:
        inv[1:-1] = [a%b for a, b in zip(inv[1:-1], f0[1:-1])]
    return rep, sorted(a*b - 1 for a, b in zip(f1, inv))

def test_predict(N):
    def brute_force(a, b):
        return [i for i in range(a, b) if (i*i-1) % (a*a-1) == 0]
    for x in range(2, N+1):
        period, pred = get_N_for_M(x)
        assert brute_force(x, period*4+2) \
            == [a + b for b in range(0, 4*period, period) for a in pred]
    def brute_force(b):
        return [i for i in range(2, b+1) if (b*b-1) % (i*i-1) == 0]
    for x in range(2, N+1):
        assert brute_force(x) == get_M_for_N(x)
    print('ok')

# test
print("Testing predictions ...")
test_predict(200)
print()
# examples
M = 105
period, pred = get_N_for_M(M)
print(f"M = {M}")
print(f"solutions: {pred}")
print(f"this pattern repeats at offsets {period}, {2*period}, {3*period}, ...")
print()
N = 1000001
pred = get_M_for_N(N)
print(f"N = {N}")
print(f"solutions: {pred}")
print()
N, M = 5, 3
SqNN = np.arange(N*N).reshape(N, N)
print(f"example N, M = ({N}, {M})")
print(get_subsquares(SqNN, M))


问:
Display passed data from one Ionic 3 vpage to another
So, I have data displaying on one page with a (click) event that passes data to another page, except I can only get the data to print in the console and not the page itself.  I've been at it for hours and am at my breaking point :)

I am only going to show the relevant code below to keep the post shortened (well, what I think is relevant)

list2page.html

```<code>...
<button class="list-item" tappable ion-item (click)="goToFeed(item)" *ngFor="let item of list2.items">
  ...
</button>
...
</code>```

list2page.ts

```<code>...
goToFeed(item) {
  this.nav.push(ProfilePage, {item: item});
}
...
</code>```

profile.ts - it will print the entire item to console - see screenshot

```<code>import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

import 'rxjs/Rx';

@Component({
  selector: 'profile-page',
  templateUrl: 'profile.html'
})
export class ProfilePage {

  constructor(
    public nav: NavController,
    public navParams: NavParams,
  ) {
  }

  ionViewDidLoad() {
    let veteran_first = (this.navParams.get('item.veteran_first'));
    console.log(this.navParams.get('item'));
  }

}
</code>```

答:
Delcare a parameter on your model:

```<code>public data: any;
</code>```

Then instantiate like so:

```<code>this.data = this.navParams.data;
</code>```

or this should also work

```<code>this.data = this.navParams.get('item');
</code>```

then after you have it, you should be able to drill into it

```<code>this.data.item.veteran_first
</code>```

or something to that effect. I have used both ways to fetch data passed thru the navCtrl.

Body:
So, I have data displaying on one page with a (click) event that passes data to another page, except I can only get the data to print in the console and not the page itself.  I've been at it for hours and am at my breaking point :)

I am only going to show the relevant code below to keep the post shortened (well, what I think is relevant)

list2page.html

...
<button class="list-item" tappable ion-item (click)="goToFeed(item)" *ngFor="let item of list2.items">
  ...
</button>
...

list2page.ts

...
goToFeed(item) {
  this.nav.push(ProfilePage, {item: item});
}
...

profile.ts - it will print the entire item to console - see screenshot

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

import 'rxjs/Rx';

@Component({
  selector: 'profile-page',
  templateUrl: 'profile.html'
})
export class ProfilePage {

  constructor(
    public nav: NavController,
    public navParams: NavParams,
  ) {
  }

  ionViewDidLoad() {
    let veteran_first = (this.navParams.get('item.veteran_first'));
    console.log(this.navParams.get('item'));
  }

}

Body:
Delcare a parameter on your model:

public data: any;

Then instantiate like so:

this.data = this.navParams.data;

or this should also work

this.data = this.navParams.get('item');

then after you have it, you should be able to drill into it

this.data.item.veteran_first

or something to that effect. I have used both ways to fetch data passed thru the navCtrl.


问:
HTML - MDL Checkbox/Toggle Centering
I have tried to use both of these components in my html document but neither of them will center. With the checkbox the text gets centered but the icon will remain to the left of the page.

  <input type="checkbox" id="checkbox-1" class="mdl-checkbox__input" checked>
  Checkbox

  <input type="checkbox" id="switch-1" class="mdl-switch__input" checked>

```

答:
I used flex on the label to center the items inside. It also aligns the content vertically so your input is inline with your label.

.mdl-checkbox, .mdl-switch{
display:flex;
justify-content:center;
align-items:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="checkbox-1">
  <input type="checkbox" id="checkbox-1" class="mdl-checkbox__input" checked>
  <span class="mdl-checkbox__label">Checkbox</span>
</label>

<label class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="switch-1">
  <input type="checkbox" id="switch-1" class="mdl-switch__input" checked>
  <span class="mdl-switch__label">Checkbox 2</span>
</label></code>```

Title: HTML - MDL Checkbox/Toggle Centering

Body:
I used flex on the label to center the items inside. It also aligns the content vertically so your input is inline with your label.

.mdl-checkbox, .mdl-switch{
display:flex;
justify-content:center;
align-items:center;
}

<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="checkbox-1">
  <input type="checkbox" id="checkbox-1" class="mdl-checkbox__input" checked>
  <span class="mdl-checkbox__label">Checkbox</span>
</label>

<label class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="switch-1">
  <input type="checkbox" id="switch-1" class="mdl-switch__input" checked>
  <span class="mdl-switch__label">Checkbox 2</span>
</label>


问:
Mac App: 'Auto Loading' the last used Document
I'm currently writing a document based application, and was curious to how I would load the most recently used document ('File > Open Recent'section) by default at application startup? Any good info on this or code snippets? New to Obj-C

Thanks,
Zach

答:
In your application delegate, you'd want to implement applicationShouldOpenUntitledFile:

```<code>- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender
{
    NSURL *lastURL=[[[NSDocumentController sharedDocumentController] recentDocumentURLs] objectAtIndex:0];
    if (lastURL!=nil)
    {
        [[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:lastURL display:YES error:nil];
        return NO;
    }

    return YES;
}
</code>```

Apparently, the default NSDocument-based cocoa app in XCode doesn't come with an AppDelegate.  Weird.  To add one:

Add a new class to your Project, call it MyAppDelegate, or whatever you want.

In the interface for MyAppDelegate, add the protocol NSApplicationDelegate, it should look something like this:

@interface MyAppDelegate : NSObject<NSApplicationDelegate>
{
}

Open up MainMenu.xib

Drag an Object instance to the xib's window, the Object instance looks like a blue box.

Select the Object instance and in the inspector, go to the Identity tab (the blue i)

Set the Class to MyAppDelegate

Select the "Application" in the xib

In the inspector, click on the Connections tab (the blue arrow icon) and drag from "delegate" to the application delegate you just set up.

You are good to go now.

Body:
In your application delegate, you'd want to implement applicationShouldOpenUntitledFile:

- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender
{
    NSURL *lastURL=[[[NSDocumentController sharedDocumentController] recentDocumentURLs] objectAtIndex:0];
    if (lastURL!=nil)
    {
        [[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:lastURL display:YES error:nil];
        return NO;
    }

    return YES;
}

Apparently, the default NSDocument-based cocoa app in XCode doesn't come with an AppDelegate.  Weird.  To add one:

Add a new class to your Project, call it MyAppDelegate, or whatever you want.

In the interface for MyAppDelegate, add the protocol NSApplicationDelegate, it should look something like this:

@interface MyAppDelegate : NSObject<NSApplicationDelegate>
{
}

Open up MainMenu.xib

Drag an Object instance to the xib's window, the Object instance looks like a blue box.

Select the Object instance and in the inspector, go to the Identity tab (the blue i)

Set the Class to MyAppDelegate

Select the "Application" in the xib

In the inspector, click on the Connections tab (the blue arrow icon) and drag from "delegate" to the application delegate you just set up.

You are good to go now.


问:
Error Domain=NSPOSIXErrorDomain Code=100 "Protocol error"
I am trying to call a service using Alamofire using a .get method.
The request has nothing special no parameters just an Authorization header.

I am going a bit mad here because to request works fine when I run it on postman with the same URL and Authorization token, but when I run my app code with Alamofire it returns this error:

Error Domain=NSPOSIXErrorDomain Code=100 "Protocol error" UserInfo={NSErrorPeerAddressKey={length = 16, capacity = 16, bytes = 0x100201bbd83ad0b10000000000000000}, _kCFStreamErrorCodeKey=100, _kCFStreamErrorDomainKey=1}

I am using:

```<code>Alamofire.request("https://myserverURL", method: .get, parameters: [:], encoding: JSONEncoding.default, headers: ["Authorization":"myToken"])
        .responseJSON {response in

    guard response.result.error == nil else {
       //HERE IS WHERE IS GOING IN WITH THE ERROR
    }
}
</code>```

Any thoughts will be much appreciated or point me in the right direction :)

答: Adding ["Content-Type": "application/json"]  to the headers helped.

Body:
I am trying to call a service using Alamofire using a .get method.
The request has nothing special no parameters just an Authorization header.

I am going a bit mad here because to request works fine when I run it on postman with the same URL and Authorization token, but when I run my app code with Alamofire it returns this error:

Error Domain=NSPOSIXErrorDomain Code=100 "Protocol error" UserInfo={NSErrorPeerAddressKey={length = 16, capacity = 16, bytes = 0x100201bbd83ad0b10000000000000000}, _kCFStreamErrorCodeKey=100, _kCFStreamErrorDomainKey=1}

I am using:

Alamofire.request("https://myserverURL", method: .get, parameters: [:], encoding: JSONEncoding.default, headers: ["Authorization":"myToken"])
        .responseJSON {response in

    guard response.result.error == nil else {
       //HERE IS WHERE IS GOING IN WITH THE ERROR
    }
}

Any thoughts will be much appreciated or point me in the right direction :)


问:
Python time greeting program
I'm trying to create a program that greats users base on the time of the day but when I run my code I get this error:
    unorderable types: str() < int()

I dont think I'm doing it the right way and I cant figure out a better way to do it, so are the better ways to write this program???

Here is my Code:

```<code>import time
currentTime = time.strftime('%H:%M')

if currentTime.hour < 12 :
     print('Good morning')
if currentTime.hour > 12 :
     print('Good afternoon')
if currentTime.hour > 6 :
     print('Good evening')
</code>```

答:
I saw that the answers listed here were quite lengthy so created a more concise version for those that need it (even though this post is more than 2 years old).
However this top version may break the formatting outlined in PEP-8 because the third line goes over 80 characters (92), so feel free to use the longer version.

```<code>import datetime
hour = datetime.datetime.now().hour
greeting = "Good morning" if 5<=hour<12 else "Good afternoon" if hour<18 else "Good evening"
</code>```

Then use this wherever you need it...

```<code>print("{}!".format(greeting))
</code>```

...or broken down for readability...

```<code>import datetime
now = datetime.datetime.now()
hour = now.hour

if hour < 12:
    greeting = "Good morning"
elif hour < 18:
    greeting = "Good afternoon"
else:
    greeting = "Good night"

print("{}!".format(greeting))
</code>```

An example usage case would be saying a random 'goodbye' to make the program seem more lifelike. This would be done something like this...

```<code>import random, datetime
hour = datetime.datetime.now().hour
greeting = "Have a nice day" if hour<20 else "Good night"
print(random.choice(["I look forward to our next meeting!",greeting+"!"]))
</code>```

Title: Python time greeting program

Body:
I'm trying to create a program that greats users base on the time of the day but when I run my code I get this error:
    unorderable types: str() < int()

I dont think I'm doing it the right way and I cant figure out a better way to do it, so are the better ways to write this program???

Here is my Code:

import time
currentTime = time.strftime('%H:%M')

if currentTime.hour < 12 :
     print('Good morning')
if currentTime.hour > 12 :
     print('Good afternoon')
if currentTime.hour > 6 :
     print('Good evening')

Body:
I saw that the answers listed here were quite lengthy so created a more concise version for those that need it (even though this post is more than 2 years old).
However this top version may break the formatting outlined in PEP-8 because the third line goes over 80 characters (92), so feel free to use the longer version.

import datetime
hour = datetime.datetime.now().hour
greeting = "Good morning" if 5<=hour<12 else "Good afternoon" if hour<18 else "Good evening"

Then use this wherever you need it...

print("{}!".format(greeting))

...or broken down for readability...

import datetime
now = datetime.datetime.now()
hour = now.hour

if hour < 12:
    greeting = "Good morning"
elif hour < 18:
    greeting = "Good afternoon"
else:
    greeting = "Good night"

print("{}!".format(greeting))

An example usage case would be saying a random 'goodbye' to make the program seem more lifelike. This would be done something like this...

import random, datetime
hour = datetime.datetime.now().hour
greeting = "Have a nice day" if hour<20 else "Good night"
print(random.choice(["I look forward to our next meeting!",greeting+"!"]))

ContentLicense: CC BY-SA 4.0


问:
Angularcli headers
What is the equivalent to jquery

```<code>$scope.SetHeaders = function () {
        $.ajaxSetup({
            headers: {
                'ValueID': ValueID
            }
        });
    };
</code>```

What I tried so far in angular cli.

```<code>pushvalueId(paramid: number): Observable<any[]> {
    let myHeaders = new Headers();
    myHeaders.set('ValueID', '77');
    let myParams = new URLSearchParams();
    myParams.set('ValueID', paramid.toString());
    let options = new RequestOptions({ headers: myHeaders, params: myParams });
    return this._http.post(this._getreport, options)
}
</code>```

What I am trying to do initially is retrieve the header value in my class.

```<code> public int ValueID { get; set; }
  ValueID = Convert.ToInt32(HttpContext.Current.Request.Headers.GetValues("ValueID"));

`import { Http, Response, JsonpModule, HttpModule, Headers, RequestOptions } from '@angular/http';`
</code>```

答:
First you are using deprecated http client. You should use '@angular/common/http'

Second argument for post method is body. For options you have to use 3rd argument:

```<code>this._http.post(this._getreport, null, {headers: myHeaders, params: myParams})
</code>```

Don't use RequestOptions - these are part of the old http client and deprecated

Title: Angularcli headers

Body:
What is the equivalent to jquery

$scope.SetHeaders = function () {
        $.ajaxSetup({
            headers: {
                'ValueID': ValueID
            }
        });
    };

What I tried so far in angular cli.

pushvalueId(paramid: number): Observable<any[]> {
    let myHeaders = new Headers();
    myHeaders.set('ValueID', '77');
    let myParams = new URLSearchParams();
    myParams.set('ValueID', paramid.toString());
    let options = new RequestOptions({ headers: myHeaders, params: myParams });
    return this._http.post(this._getreport, options)
}

What I am trying to do initially is retrieve the header value in my class.

 public int ValueID { get; set; }
  ValueID = Convert.ToInt32(HttpContext.Current.Request.Headers.GetValues("ValueID"));

`import { Http, Response, JsonpModule, HttpModule, Headers, RequestOptions } from '@angular/http';`

Body:
First you are using deprecated http client. You should use '@angular/common/http'

Second argument for post method is body. For options you have to use 3rd argument:

this._http.post(this._getreport, null, {headers: myHeaders, params: myParams})

Don't use RequestOptions - these are part of the old http client and deprecated


问:
Best way to compare std::strings
What is the best way to compare std::strings? The obvious way would be with if/else:

```<code>std::string input;
std::cin >> input;

if ( input == "blahblahblah" )
{
    // do something.
}

else if ( input == "blahblah" )
{
    // do something else.
}

else if ( input == "blah" )
{
    // do something else yet.
}

// etc. etc. etc.
</code>```

Another possibility is to use an std::map and a switch/case. What is the best way when doing lots (like 8, 10, 12+) of these comparisons?

答: With 8, 10 and even 12 comparisons you can still use if ... else if ... scheme, nothing bad. If you want 100 or something, I'd recommend writing a function which would calculate a hash of string (even by simple xoring all the characters, but some other good method would be preferable for better distribution) and then switching over its result as Evan proposed. If function returns unique numbers for all the possible input strings - that's even better and doesn't require additional comparisons.

Title: Best way to compare std::strings

Body:
What is the best way to compare std::strings? The obvious way would be with if/else:

std::string input;
std::cin >> input;

if ( input == "blahblahblah" )
{
    // do something.
}

else if ( input == "blahblah" )
{
    // do something else.
}

else if ( input == "blah" )
{
    // do something else yet.
}

// etc. etc. etc.

Another possibility is to use an std::map and a switch/case. What is the best way when doing lots (like 8, 10, 12+) of these comparisons?


问:
Two layers for loop in `JavaScript`

function convertObjectToList(obj) {
  var innerArr= [];
  var outerArr=[];
  for (var prop in obj) {
    innerArr.push(prop);
    innerArr.push(obj[prop]);
    console.log(innerArr);
    outerArr.push(innerArr);
    console.log(outerArr);
  } return outerArr;
}

convertObjectToList({
  name: 'Holly',
  age: 35,
})```

Can someone help me to figure out what happened inside the for loop?

Q: my question is on the second round: outerArr[0]= [ ‘name’, ‘Holly’ ], but the console shows me outerArr[0]= [ ‘name’, ‘Holly’, ‘age’, 35 ]

Actual output:

1. first round: innerArr=[ ‘name’, ‘Holly’ ]  & outerArr = [ [ ‘name’, ‘Holly’ ] ]

2. second round:
 innerArr=[ ‘name’, ‘Holly’, ‘age’, 35 ] & outerArr=[ [ ‘name’, ‘Holly’, ‘age’, 35 ],[ ‘name’, ‘Holly’, ‘age’, 35 ] ]

But I expeced: outerArr= [ [ ‘name’, ‘Holly’ ], [ ‘name’, ‘Holly’, ‘age’, 35 ] ]

答:
Use toString() to convert array to string then store it in outer array

    function convertObjectToList(obj) {
      var innerArr = [];
      var outerArr = [];
      for (var prop in obj) {
        var arry = []
        innerArr.push(prop.toString());
        innerArr.push(obj[prop].toString());
        arry.push(innerArr.toString())
        outerArr.push(arry);
      }

       console.log(outerArr);

      return outerArr;
    }

    convertObjectToList({
      name: 'Holly',
      age: 35,
    })```

Actually  for (var prop in obj) {} is a foreach loop it will navigate through each element of the obj array

Title: Two layers for loop in `JavaScript`

Body:
function convertObjectToList(obj) {
  var innerArr= [];
  var outerArr=[];
  for (var prop in obj) {
    innerArr.push(prop);
    innerArr.push(obj[prop]);
    console.log(innerArr);
    outerArr.push(innerArr);
    console.log(outerArr);
  } return outerArr;
}

convertObjectToList({
  name: 'Holly',
  age: 35,
})

Can someone help me to figure out what happened inside the for loop?

Q: my question is on the second round: outerArr[0]= [ ‘name’, ‘Holly’ ], but the console shows me outerArr[0]= [ ‘name’, ‘Holly’, ‘age’, 35 ]

Actual output:

1. first round: innerArr=[ ‘name’, ‘Holly’ ]  & outerArr = [ [ ‘name’, ‘Holly’ ] ]

2. second round:
 innerArr=[ ‘name’, ‘Holly’, ‘age’, 35 ] & outerArr=[ [ ‘name’, ‘Holly’, ‘age’, 35 ],[ ‘name’, ‘Holly’, ‘age’, 35 ] ]

But I expeced: outerArr= [ [ ‘name’, ‘Holly’ ], [ ‘name’, ‘Holly’, ‘age’, 35 ] ]

Body:
Use toString() to convert array to string then store it in outer array

    function convertObjectToList(obj) {
      var innerArr = [];
      var outerArr = [];
      for (var prop in obj) {
        var arry = []
        innerArr.push(prop.toString());
        innerArr.push(obj[prop].toString());
        arry.push(innerArr.toString())
        outerArr.push(arry);
      }

       console.log(outerArr);

      return outerArr;
    }

    convertObjectToList({
      name: 'Holly',
      age: 35,
    })

Actually  for (var prop in obj) {} is a foreach loop it will navigate through each element of the obj array


问:
bug? bash select-- typed data is returned as "unbound variable"
I'm running Linux 3.10.0-693.2.2.el7.x86_64, and for the life of me can't figure why this would happen.  It appears to be a bug and shellchecker finds no issues.

```<code>#!/bin/bash
set -o nounset

### functions
options=(one two three)

select var in "${options[@]}"; do
    # make sure it is a valid choice
    if (( REPLY <= ${#options[@]} )) && [[ $REPLY  =~ ^[0-9]+$ ]]; then
        case $var in
            one)   exit;;
            two)  df -h /tmp;;
            *)      echo $var;;
        esac
        break
    else
        printf "Invalid selection.\n" >&2
    fi
</code>```

I used set -xv to trouble shoot, but here's the output without it.  In production, the options[@] will be set by a command, and the number they return will be dynamic.  So I want the menu to execute a command in *) on $var-- but I have to check for an out of bounds selection in REPLY.  Here is the output.

```<code>$ bad_select.bash
1) one
2) two
3) three
#? 4
Invalid selection.
#? t
/home/lc5550358/bin/select_menu.wip: line 9: t: unbound variable
</code>```

The t that I typed?  I can also avoid the unbound variable, but entering k=2 or var (the latter is defined in the select).  Why and what is the work around
(set -o nounset is needed)?

答:
Inside an arithmetic expression, bash evaluates the value of a variable.  Thus, in (( REPLY <= ${#options[@]} )), the value of REPLY is evaluated.  If the value of REPLY is t and t is unbound, then that triggers the unbound variable error.

Observe:

```<code>$ t=2*3; REPLY=t; echo $(( REPLY + 2 ))
8
$ REPLY=t; t=a+b; a=6; b=c; c=10; echo $(( REPLY + 2 ))
18
$ unset t; REPLY=t; echo $(( REPLY + 2 ))
bash: t: unbound variable
</code>```

As jm666 explained, one solution is reverse the order of the tests so that arithmetic is done on REPLY only after it is verified that REPLY is an integer.

Alternatively, you can test var instead of REPLY:

```<code>#!/bin/bash
set -o nounset

### functions
options=(one two three)

select var in "${options[@]}"; do
    # make sure it is a valid choice
    if [ "$var" ]; then
        case "$var" in
            one)   exit;;
            two)  df -h /tmp;;
            *)      echo "$var";;
        esac
        break
    else
        printf "Invalid selection.\n" >&2
    fi
done
</code>```

This works because var is only assigned a value if the user provided a valid response at the prompt.  Otherwise, var is set to be null.

Documentation

From the man bash section on arithmetic evaluation:

Shell variables are allowed as operands; parameter expansion is
  performed before the expression is evaluated.  Within an expression,
  shell variables may also be referenced by    name without using the
  parameter expansion syntax.  A shell variable that is null or unset
  evaluates to 0 when referenced by name without using the parameter
  expansion  syn‐    tax.   The  value of a variable is evaluated as an
  arithmetic expression when it is referenced, or when a variable which
  has been given the integer attribute using declare -i    is assigned a
  value.  A null value evaluates to 0.  A shell variable need not have
  its integer attribute turned on to be used in an expression.

Body:
I'm running Linux 3.10.0-693.2.2.el7.x86_64, and for the life of me can't figure why this would happen.  It appears to be a bug and shellchecker finds no issues.

#!/bin/bash
set -o nounset

### functions
options=(one two three)

select var in "${options[@]}"; do
    # make sure it is a valid choice
    if (( REPLY <= ${#options[@]} )) && [[ $REPLY  =~ ^[0-9]+$ ]]; then
        case $var in
            one)   exit;;
            two)  df -h /tmp;;
            *)      echo $var;;
        esac
        break
    else
        printf "Invalid selection.\n" >&2
    fi

I used set -xv to trouble shoot, but here's the output without it.  In production, the options[@] will be set by a command, and the number they return will be dynamic.  So I want the menu to execute a command in *) on $var-- but I have to check for an out of bounds selection in REPLY.  Here is the output.

$ bad_select.bash
1) one
2) two
3) three
#? 4
Invalid selection.
#? t
/home/lc5550358/bin/select_menu.wip: line 9: t: unbound variable

The t that I typed?  I can also avoid the unbound variable, but entering k=2 or var (the latter is defined in the select).  Why and what is the work around
(set -o nounset is needed)?

Body:
Inside an arithmetic expression, bash evaluates the value of a variable.  Thus, in (( REPLY <= ${#options[@]} )), the value of REPLY is evaluated.  If the value of REPLY is t and t is unbound, then that triggers the unbound variable error.

Observe:

$ t=2*3; REPLY=t; echo $(( REPLY + 2 ))
8
$ REPLY=t; t=a+b; a=6; b=c; c=10; echo $(( REPLY + 2 ))
18
$ unset t; REPLY=t; echo $(( REPLY + 2 ))
bash: t: unbound variable

As jm666 explained, one solution is reverse the order of the tests so that arithmetic is done on REPLY only after it is verified that REPLY is an integer.

Alternatively, you can test var instead of REPLY:

#!/bin/bash
set -o nounset

### functions
options=(one two three)

select var in "${options[@]}"; do
    # make sure it is a valid choice
    if [ "$var" ]; then
        case "$var" in
            one)   exit;;
            two)  df -h /tmp;;
            *)      echo "$var";;
        esac
        break
    else
        printf "Invalid selection.\n" >&2
    fi
done

This works because var is only assigned a value if the user provided a valid response at the prompt.  Otherwise, var is set to be null.

Documentation

From the man bash section on arithmetic evaluation:

Shell variables are allowed as operands; parameter expansion is
  performed before the expression is evaluated.  Within an expression,
  shell variables may also be referenced by    name without using the
  parameter expansion syntax.  A shell variable that is null or unset
  evaluates to 0 when referenced by name without using the parameter
  expansion  syn‐    tax.   The  value of a variable is evaluated as an
  arithmetic expression when it is referenced, or when a variable which
  has been given the integer attribute using declare -i    is assigned a
  value.  A null value evaluates to 0.  A shell variable need not have
  its integer attribute turned on to be used in an expression.


问:
Laravel 5.2 redirect back with success message
I'm trying to get a success message back to my home page on laravel.

```<code>return redirect()->back()->withSuccess('IT WORKS!');
</code>```

For some reason the variable $success doesn't get any value after running this code.

The code I'm using to display the succes message:

```<code>@if (!empty($success))
    <h1>{{$success}}</h1>
@endif
</code>```

I have added the home and newsletter page to the web middleware group in routes.php like this:

```<code>Route::group(['middleware' => 'web'], function () {
    Route::auth();

    Route::get('/', function () {
        return view('home');
    });

    Route::post('/newsletter/subscribe','NewsletterController@subscribe');
});
</code>```

Does anyone have any idea why this doesn't seem to work?

答:
you can use this :

```<code>return redirect()->back()->withSuccess('IT WORKS!');
</code>```

and use this in your view :

```<code>@if(session('success'))
    <h1>{{session('success')}}</h1>
@endif
</code>```

Body:
I'm trying to get a success message back to my home page on laravel.

return redirect()->back()->withSuccess('IT WORKS!');

For some reason the variable $success doesn't get any value after running this code.

The code I'm using to display the succes message:

@if (!empty($success))

{{$success}}

@endif

I have added the home and newsletter page to the web middleware group in routes.php like this:

Route::group(['middleware' => 'web'], function () {
    Route::auth();

    Route::get('/', function () {
        return view('home');
    });

    Route::post('/newsletter/subscribe','NewsletterController@subscribe');
});

Does anyone have any idea why this doesn't seem to work?

Body:
you can use this :

return redirect()->back()->withSuccess('IT WORKS!');

and use this in your view :

@if(session('success'))
    <h1>{{session('success')}}</h1>
@endif


问:
std::array with unknown length as a type for template function specification
I want to pass std::array class with a known type, but unknown size to the template function specialization:

```<code>class foo {
public:
void bar<class T>(T arg1, int arg2, int arg3) {
    //For any other T
}
void bar<std::array<rs::float3, size>>(T arg1, arg2) {
    //Specific function for type std::array of rs::float3's and unknown length (size is not a type, just variable).
}
</code>```

答:
What about something like

```<code>template <typename T>
void foo (T const &)
 { std::cout << "foo generic" << std::endl; }

template <std::size_t Dim>
void foo (std::array<float, Dim> const &)
 { std::cout << "foo float array dim " << Dim << std::endl; }
</code>```

?

The following is a full working example

```<code>#include <array>
#include <iostream>

template <typename T>
void foo (T const &)
 { std::cout << "foo generic" << std::endl; }

template <std::size_t Dim>
void foo (std::array<float, Dim> const &)
 { std::cout << "foo floar array dim " << Dim << std::endl; }

int main ()
 {
   foo(0);
   foo(std::array<float, 12U>{});
 }
</code>```

Body:
I want to pass std::array class with a known type, but unknown size to the template function specialization:

class foo {
public:
void bar<class T>(T arg1, int arg2, int arg3) {
    //For any other T
}
void bar<std::array<rs::float3, size>>(T arg1, arg2) {
    //Specific function for type std::array of rs::float3's and unknown length (size is not a type, just variable).
}

Body:
What about something like

template <typename T>
void foo (T const &)
 { std::cout << "foo generic" << std::endl; }

template <std::size_t Dim>
void foo (std::array<float, Dim> const &)
 { std::cout << "foo float array dim " << Dim << std::endl; }

?

The following is a full working example

#include <array>
#include <iostream>

template <typename T>
void foo (T const &)
 { std::cout << "foo generic" << std::endl; }

template <std::size_t Dim>
void foo (std::array<float, Dim> const &)
 { std::cout << "foo floar array dim " << Dim << std::endl; }

int main ()
 {
   foo(0);
   foo(std::array<float, 12U>{});
 }


问:
How can I close a Bootstrap Collapse using JavaScript?
I want to be able to close or open a collapse using javasript. Any idea?</p>

```<code><button data-toggle="collapse" data-target="#demo">Collapsible</button>

<div id="demo" class="collapse">
<!--Something else here-->
</div>
</code>```

Body:
I want to be able to close or open a collapse using javasript. Any idea?

<button data-toggle="collapse" data-target="#demo">Collapsible</button>

Body:
$("element-selector").collapse('hide')
$("element-selector").collapse('toggle')
$("element-selector").collapse('show')

https://getbootstrap.com/docs/4.0/components/collapse/#methods


问:
getbounds on google api v2 is not working
getbounds() return error on firebug. May I know what is the problem? Thanks.

```<code>map=new GMap2(document.getElementbyId('map'));
map.setCenter(new GLatLng(la,lo),15);
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
map.enableScrollWheelZoom();
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var southEast = bounds.getSouthEast();
var northWest = bounds.getNorthWest();
</code>```

Firebug states that getSouthWest() is not a functions. Thank you.

答: I think the simple problem here is that GLatLngBounds only has getSouthWest() and getNorthEast() methods, not getSouthEast() and getNorthWest() (see the API reference). Are you sure Firebug is giving you an error on getSouthWest? I am able to get your code working without an error if I remove the last two function calls.</p>

Body:
getbounds() return error on firebug. May I know what is the problem? Thanks.

map=new GMap2(document.getElementbyId('map'));
map.setCenter(new GLatLng(la,lo),15);
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
map.enableScrollWheelZoom();
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var southEast = bounds.getSouthEast();
var northWest = bounds.getNorthWest();

Firebug states that getSouthWest() is not a functions. Thank you.


问:
json file not loaded via angular threeJS
I have made a simple model in blender and exported it as a json file to use on my app, i used angular cli to generate a base aplication where i added the threeJS, everything is working fine except i can't add my new model, it cannot find the json file dunno why, do i need to use http module with angular to accomplish this?
im a little confused

At the moment i have this:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    HttpClientModule
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

my component

```<code>import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import * as THREE from 'three';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  public constructor(private http: HttpClient) {

  }
  private container: HTMLElement;

  @ViewChild('container') elementRef: ElementRef;
  private scene: THREE.Scene;
  private camera: THREE.PerspectiveCamera;
  private renderer: THREE.WebGLRenderer;

  private cube: THREE.Mesh;

  ngOnInit() {
    this.container = this.elementRef.nativeElement;

    console.log(this.container);

    this.init();
    this.http
  }

  init() {
    let screen = {
      width: window.innerWidth,
      height: window.innerHeight,
      color: 0xffffff
    },
      view = {
        angle: 45,
        aspect: screen.width / screen.height,
        near: 0.1,
        far: 1000
      };

    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera(view.angle, view.aspect, view.near, view.far);
    this.renderer = new THREE.WebGLRenderer();
    this.renderer.setClearColor( 0x000000, 1);

    this.scene.add(this.camera);
    this.scene.add(new THREE.AxisHelper(20));

    this.camera.position.set(10, 10, 10);
    this.camera.lookAt(new THREE.Vector3(0, 0, 0));
    this.renderer.setSize(screen.width, screen.height);
    this.container.appendChild(this.renderer.domElement);

    var mesh = null;
    var loader = new THREE.JSONLoader();
    this.http.get('assets/DAMA1.json');
    loader.load('./DAMA1.json', function (geometry) {
      mesh = new THREE.Mesh(geometry);
      this.scene.add(mesh);
    });

    let geometry = new THREE.BoxGeometry(5, 5, 5),
      material = new THREE.MeshBasicMaterial({ color: 0xFFFFFF, wireframe: true });

    this.cube = new THREE.Mesh(geometry, material);
    this.cube.position.set(-50, -50, -50);

    this.scene.add(this.cube);

    this.render();
  }

  render() {

    let self: AppComponent = this;

    (function render() {
      requestAnimationFrame(render);
      self.renderer.render(self.scene, self.camera);
      self.renderer.setClearColor( 0xffffff, 1);

      self.animate();
    }());

  }

  onResize(event) {
    this.renderer.setSize(window.innerWidth, window.innerHeight);
  }

  animate() {
    this.cube.rotateX(0.1);
    this.cube.rotateY(0.1);
    this.cube.position.addScalar(0.2);

  }

}
</code>```

any help?

答:
You are loading it twice with two distinct paths.

```<code>this.http.get('assets/DAMA1.json');
loader.load('./DAMA1.json');
</code>```

Could be a path problem.

By the way, apparently, the function

```<code> new THREE.Mesh(geometry);
</code>```

accepts a json. If your assets are local, why dont you load them via imports, at the top of the file.

You could do:

```<code>import geometry from 'assets/DATA1.json';
</code>```

And then, inside the component:

```<code>new THREE.Mesh(geometry);
</code>```

If this solution doesnt work, can you catch the error throwed by the THREE loader? The loader function probably accepts a error callback.

Body:
I have made a simple model in blender and exported it as a json file to use on my app, i used angular cli to generate a base aplication where i added the threeJS, everything is working fine except i can't add my new model, it cannot find the json file dunno why, do i need to use http module with angular to accomplish this?
im a little confused

At the moment i have this:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    HttpClientModule
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

my component

import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import * as THREE from 'three';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  public constructor(private http: HttpClient) {

  }
  private container: HTMLElement;

  @ViewChild('container') elementRef: ElementRef;
  private scene: THREE.Scene;
  private camera: THREE.PerspectiveCamera;
  private renderer: THREE.WebGLRenderer;

  private cube: THREE.Mesh;

  ngOnInit() {
    this.container = this.elementRef.nativeElement;

    console.log(this.container);

    this.init();
    this.http
  }

  init() {
    let screen = {
      width: window.innerWidth,
      height: window.innerHeight,
      color: 0xffffff
    },
      view = {
        angle: 45,
        aspect: screen.width / screen.height,
        near: 0.1,
        far: 1000
      };

    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera(view.angle, view.aspect, view.near, view.far);
    this.renderer = new THREE.WebGLRenderer();
    this.renderer.setClearColor( 0x000000, 1);

    this.scene.add(this.camera);
    this.scene.add(new THREE.AxisHelper(20));

    this.camera.position.set(10, 10, 10);
    this.camera.lookAt(new THREE.Vector3(0, 0, 0));
    this.renderer.setSize(screen.width, screen.height);
    this.container.appendChild(this.renderer.domElement);

    var mesh = null;
    var loader = new THREE.JSONLoader();
    this.http.get('assets/DAMA1.json');
    loader.load('./DAMA1.json', function (geometry) {
      mesh = new THREE.Mesh(geometry);
      this.scene.add(mesh);
    });

    let geometry = new THREE.BoxGeometry(5, 5, 5),
      material = new THREE.MeshBasicMaterial({ color: 0xFFFFFF, wireframe: true });

    this.cube = new THREE.Mesh(geometry, material);
    this.cube.position.set(-50, -50, -50);

    this.scene.add(this.cube);

    this.render();
  }

  render() {

    let self: AppComponent = this;

    (function render() {
      requestAnimationFrame(render);
      self.renderer.render(self.scene, self.camera);
      self.renderer.setClearColor( 0xffffff, 1);

      self.animate();
    }());

  }

  onResize(event) {
    this.renderer.setSize(window.innerWidth, window.innerHeight);
  }

  animate() {
    this.cube.rotateX(0.1);
    this.cube.rotateY(0.1);
    this.cube.position.addScalar(0.2);

  }

}

any help?

Body:
You are loading it twice with two distinct paths.

this.http.get('assets/DAMA1.json');
loader.load('./DAMA1.json');

Could be a path problem.

By the way, apparently, the function

 new THREE.Mesh(geometry);

accepts a json. If your assets are local, why dont you load them via imports, at the top of the file.

You could do:

import geometry from 'assets/DATA1.json';

And then, inside the component:

new THREE.Mesh(geometry);

If this solution doesnt work, can you catch the error throwed by the THREE loader? The loader function probably accepts a error callback.


问:
instantiate a class from a variable in PHP?
I know this question sounds rather vague so I will make it more clear with an example:

```<code>$var = 'bar';
$bar = new {$var}Class('var for __construct()'); //$bar = new barClass('var for __construct()');
</code>```

This is what I want to do. How would you do it? I could off course use eval() like this:

```<code>$var = 'bar';
eval('$bar = new '.$var.'Class(\'var for __construct()\');');
</code>```

But I'd rather stay away from eval(). Is there any way to do this without eval()?

答:
I would recommend the call_user_func() or call_user_func_arrayphp methods.
You can check them out here (call_user_func_array , call_user_func).

example

```<code>class Foo {
static public function test() {
    print "Hello world!\n";
}
}

 call_user_func('Foo::test');//FOO is the class, test is the method both separated by ::
 //or
 call_user_func(array('Foo', 'test'));//alternatively you can pass the class and method as an array
</code>```

If you have arguments you are passing to the method , then use the call_user_func_array() function.

example.

```<code>class foo {
function bar($arg, $arg2) {
    echo __METHOD__, " got $arg and $arg2\n";
}
}

// Call the $foo->bar() method with 2 arguments
call_user_func_array(array("foo", "bar"), array("three", "four"));
//or
//FOO is the class, bar is the method both separated by ::
call_user_func_array("foo::bar"), array("three", "four"));
</code>```

OwnerDisplayName: Pim Jager

Body:
I know this question sounds rather vague so I will make it more clear with an example:

$var = 'bar';
$bar = new {$var}Class('var for __construct()'); //$bar = new barClass('var for __construct()');

This is what I want to do. How would you do it? I could off course use eval() like this:

$var = 'bar';
eval('$bar = new '.$var.'Class(\'var for __construct()\');');

But I'd rather stay away from eval(). Is there any way to do this without eval()?

Body:
I would recommend the call_user_func() or call_user_func_arrayphp methods.
You can check them out here (call_user_func_array , call_user_func).

example

class Foo {
static public function test() {
    print "Hello world!\n";
}
}

 call_user_func('Foo::test');//FOO is the class, test is the method both separated by ::
 //or
 call_user_func(array('Foo', 'test'));//alternatively you can pass the class and method as an array

If you have arguments you are passing to the method , then use the call_user_func_array() function.

example.

class foo {
function bar($arg, $arg2) {
    echo __METHOD__, " got $arg and $arg2\n";
}
}

// Call the $foo->bar() method with 2 arguments
call_user_func_array(array("foo", "bar"), array("three", "four"));
//or
//FOO is the class, bar is the method both separated by ::
call_user_func_array("foo::bar"), array("three", "four"));