问:
Efficient algorithm for comparing elements in the same list
I have a list of BaseBallGame objects with start and end time. I need to make sure that each game are happening at a separate time so that a user can watch the live stream of all the game.

I have an algorithm of O(n^2). I need to at least make it nlog(n).
Can someone give me a pointer on how we can improve the performance of my implementation?

```<code>public class GameTime {

    public static Boolean canViewAll(Collection<BaseBallGame> baseBallGames) {

        List<BaseBallGame> games_list = (List<BaseBallGame>) baseBallGames;
        boolean isOverlap = false;

        for (int i = 0; i < games_list(); i++) {

            for (int j = i + 1; j < games_list(); j++) {

                Date startA = games_list(i).getStart();
                Date endA = games_list(i).getEnd();
                Date startB = games_list(j).getStart();
                Date endB = games_list(j).getEnd();

                boolean isStartABeforeEndB = (startA.compareTo(endB)) < 0;
                boolean isEndAAfterStartB = (endA.compareTo(startB)) > 0;

                boolean isCurrentPairOverlap = false;

                isCurrentPairOverlap = isStartABeforeEndB && isEndAAfterStartB;

                if (isCurrentPairOverlap) {
                    isOverlap = true;
                }
            }
        }
        return !isOverlap;
    }

    boolean overlap(Date start1, Date end1, Date start2, Date end2){
        return start1.getTime() <= end2.getTime() && start2.getTime() <= end1.getTime();
    }

    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("y-M-d H:m");

        ArrayList<BaseBallGame> baseBallGames = new ArrayList<BaseBallGame>();
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 20:00"), sdf.parse("2015-01-01 21:30")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 21:30"), sdf.parse("2015-01-01 23:00")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 23:10"), sdf.parse("2015-01-01 23:30")));

        System.out.println(GameTime.canViewAll(baseBallGames));
    }
}

class BaseBallGame {
    private Date start, end;

    public BaseBallGame(Date start, Date end) {
        this.start = start;
        this.end = end;
    }

    public Date getStart() {
        return this.start;
    }

    public Date getEnd() {
        return this.end;
    }

}
</code>```

答:
The most efficent algorithm to adapt this problem is interval search tree. You have beginning time and endtime, means you have an intervals. Once your game starts and if it does not overlap the time of other game then put it in the tree. When you start a new game then put that game time and if it overlaps the time of previous game then tree will report because it has an interscetion.

The tree looks like this:
.

Instead of checking for everytime for a new game , all you need is to put your interval in tree, if it intersect an other interval then tree datastructure will automatically detect it and report it. Time complexity of this algorithm for insertion and deletion is ~logN which super efficient. If you have R intersections then the complexity will be ~RlogN where R are number of intersections.

You can also follow video of robert sedgewick here.

Body:
I have a list of BaseBallGame objects with start and end time. I need to make sure that each game are happening at a separate time so that a user can watch the live stream of all the game.

I have an algorithm of O(n^2). I need to at least make it nlog(n).
Can someone give me a pointer on how we can improve the performance of my implementation?

public class GameTime {

    public static Boolean canViewAll(Collection<BaseBallGame> baseBallGames) {

        List<BaseBallGame> games_list = (List<BaseBallGame>) baseBallGames;
        boolean isOverlap = false;

        for (int i = 0; i < games_list(); i++) {

            for (int j = i + 1; j < games_list(); j++) {

                Date startA = games_list(i).getStart();
                Date endA = games_list(i).getEnd();
                Date startB = games_list(j).getStart();
                Date endB = games_list(j).getEnd();

                boolean isStartABeforeEndB = (startA.compareTo(endB)) < 0;
                boolean isEndAAfterStartB = (endA.compareTo(startB)) > 0;

                boolean isCurrentPairOverlap = false;

                isCurrentPairOverlap = isStartABeforeEndB && isEndAAfterStartB;

                if (isCurrentPairOverlap) {
                    isOverlap = true;
                }
            }
        }
        return !isOverlap;
    }

    boolean overlap(Date start1, Date end1, Date start2, Date end2){
        return start1.getTime() <= end2.getTime() && start2.getTime() <= end1.getTime();
    }

    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("y-M-d H:m");

        ArrayList<BaseBallGame> baseBallGames = new ArrayList<BaseBallGame>();
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 20:00"), sdf.parse("2015-01-01 21:30")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 21:30"), sdf.parse("2015-01-01 23:00")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 23:10"), sdf.parse("2015-01-01 23:30")));

        System.out.println(GameTime.canViewAll(baseBallGames));
    }
}

class BaseBallGame {
    private Date start, end;

    public BaseBallGame(Date start, Date end) {
        this.start = start;
        this.end = end;
    }

    public Date getStart() {
        return this.start;
    }

    public Date getEnd() {
        return this.end;
    }

}


来源: stackexchange

问:
ORA-01791: oracle join
I want to know how to organize this code in a way where I'm only getting the data from customer. my problem is I'm getting repeated data from rental which is against what I need.

```<code> SELECT DISTINCT C.CUSTOMER_ID , (C.FIRST_NAME|| ' ' || C.LAST_NAME) "Customer Name"
 FROM CUSTOMER C
   JOIN RENTAL R ON C.CUSTOMER_ID = R.CUSTOMER_ID
 ORDER BY C.LAST_NAME;
</code>```

exactly I should get 599 rows, when this is giving me 16044 rows.

答:
You can do that with</p>

```<code>SELECT C.CUSTOMER_ID , (C.FIRST_NAME|| ' ' || C.LAST_NAME) "Customer Name"
FROM
CUSTOMER C
WHERE
C.CUSTOMER_ID IN
(SELECT DISTINCT CUSTOMER_ID FROM RENTAL)
ORDER BY
C.CUSTOMER_ID
</code>```

ContentLicense: CC BY-SA 3.0

Title: ORA-01791: oracle join

Body:
I want to know how to organize this code in a way where I'm only getting the data from customer. my problem is I'm getting repeated data from rental which is against what I need.

 SELECT DISTINCT C.CUSTOMER_ID , (C.FIRST_NAME|| ' ' || C.LAST_NAME) "Customer Name"
 FROM CUSTOMER C
   JOIN RENTAL R ON C.CUSTOMER_ID = R.CUSTOMER_ID
 ORDER BY C.LAST_NAME;

exactly I should get 599 rows, when this is giving me 16044 rows.

Body:
You can do that with

SELECT C.CUSTOMER_ID , (C.FIRST_NAME|| ' ' || C.LAST_NAME) "Customer Name"
FROM
CUSTOMER C
WHERE
C.CUSTOMER_ID IN
(SELECT DISTINCT CUSTOMER_ID FROM RENTAL)
ORDER BY
C.CUSTOMER_ID


问:
reset userdefualts every time button is pressed (swift4)
I am trying to use userdefualts to save a tuple displayed on a label. Right now my code uses userdefulats as followed. If a, 2 then a, 3 is entered. The label displays a,2 a,2, a,3. The label is just appending each new entry. I need the userdefualt to overwrite whatever was just saved. So it should only display a,2 a,3. </p>

```<code>        @IBAction func submitText(_ sender: Any) {
        if let domain = Bundle.main.bundleIdentifier {
            UserDefaults.standard.removePersistentDomain(forName: domain)
        }

        llble.text = String(describing: result) + "\n"
                    UserDefaults.standard.set(llble.text, forKey: "name")

        }

    override func viewDidAppear(_ animated: Bool) {
        let save : String? = UserDefaults.standard.object(forKey: "name") as? String
        if let nameToDisplay = save {
            llble.text = nameToDisplay
        }
    }
</code>```

答: You should check the logic of result variable that is providing the string to the userdefault.</p>

Body:
I am trying to use userdefualts to save a tuple displayed on a label. Right now my code uses userdefulats as followed. If a, 2 then a, 3 is entered. The label displays a,2 a,2, a,3. The label is just appending each new entry. I need the userdefualt to overwrite whatever was just saved. So it should only display a,2 a,3.

        @IBAction func submitText(_ sender: Any) {
        if let domain = Bundle.main.bundleIdentifier {
            UserDefaults.standard.removePersistentDomain(forName: domain)
        }

        llble.text = String(describing: result) + "\n"
                    UserDefaults.standard.set(llble.text, forKey: "name")

        }

    override func viewDidAppear(_ animated: Bool) {
        let save : String? = UserDefaults.standard.object(forKey: "name") as? String
        if let nameToDisplay = save {
            llble.text = nameToDisplay
        }
    }


问:
php imap get from email address
How do I retrieve the email address from an email with imap_open?

If the sender name is known I get the sender name instead of the email address if I use the 'from' parameter.

Code: http://gist.github.com/514207

答:
```<code>$header = imap_headerinfo($imap_conn, $msgnum);
$fromaddr = $header->from[0]->mailbox . "@" . $header->from[0]->host;
</code>```

Title: php imap get from email address

ContentLicense: CC BY-SA 2.5


问:
R :: How to find if any letters exist in an factor variable
I have an factor variable in a data table with values as below :

```<code>TC02345,TC02734,TS3234,34566,79800,.....
</code>```

I need to concatenate "S" only for those records which has no letters at the beginning. (i.e) 34566,79800.

So final expected output needs to be as below :

```<code>TC02345,TC02734,TS3234,S37666,S778800.
</code>```

Kindly guide.

答:
Using stringr package.

```<code>library(stringr)
str_replace(df$my_factor, "(^[:digit:])","S\\1")

"TC02345" "TC02734" "TS3234"  "S34566"  "S79800"
</code>```

Body:
I have an factor variable in a data table with values as below :

TC02345,TC02734,TS3234,34566,79800,.....

I need to concatenate "S" only for those records which has no letters at the beginning. (i.e) 34566,79800.

So final expected output needs to be as below :

TC02345,TC02734,TS3234,S37666,S778800.

Kindly guide.

Body:
Using stringr package.

library(stringr)
str_replace(df$my_factor, "(^[:digit:])","S\\1")

"TC02345" "TC02734" "TS3234"  "S34566"  "S79800"


答:
Swift 4:

```<code>if let domain = Bundle.main.bundleIdentifier {
    UserDefaults.standard.removePersistentDomain(forName: domain)
}
</code>```

Swift 3:

```<code>if let domain = NSBundle.mainBundle().bundleIdentifier {
    NSUserDefaults.standardUserDefaults().removePersistentDomainForName(
domain)
}
</code>```

Objective-C:

```<code>NSString *domain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName: domain];
</code>```

Calling this method is equivalent to initializing a user defaults object with init(suiteName:) passing domainName, and calling the removeObject(forKey:) method on each of its keys.

Also synchronize() is a legacy method and is unnecessary and shouldn't be used.

Title: reset userdefualts every time button is pressed (swift4)

Body:
Swift 4:

if let domain = Bundle.main.bundleIdentifier {
    UserDefaults.standard.removePersistentDomain(forName: domain)
}

Swift 3:

if let domain = NSBundle.mainBundle().bundleIdentifier {
    NSUserDefaults.standardUserDefaults().removePersistentDomainForName(
domain)
}

Objective-C:

NSString *domain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName: domain];

Calling this method is equivalent to initializing a user defaults object with init(suiteName:) passing domainName, and calling the removeObject(forKey:) method on each of its keys.

Also synchronize() is a legacy method and is unnecessary and shouldn't be used.


问:
file not dowloading in react , node js
I want to download a file in my download folder . The file is in the uploads folder, both the folders are in same directory . The file name is BasicUserFile-id.jpg

/// 2nd attempt: This time I am trying to get the file by hardcoding the file name but it's also not working, instead a blank file is getting downloaded.

app.js

```<code>  Filedownload(e) {

    e.preventDefault();

    var id = this.props.params.id;

    console.log(id);

    $.ajax({
      type: 'GET',
      url: '/download/' + id,
      success: function (data, textStatus, request) {
        window.open('./downloads/ ', '_self');
      }

    });

  }

   <button type="button" value="Download File" onClick={this.Filedownload}
   className="btn btn-success btn-lg">Download file</button>
</code>```

////server.js

```<code>app.get('/download/:id', function(req, res){
  var basic_id = req.params.id
  var file = __dirname + '/uploads/BasicUserFile-'+ basic_id+ ".jpg";
  res.download(file);
});
</code>```

/// 2nd try .

```<code> Filedownload(e) {

    e.preventDefault();

    $.ajax({
      type: 'GET',
      url: '/download/' ,
      success : function(data)

      {

        fileDownload(data, 'filename.jpg');
        console.log("file downloaded")

      }

    });

  }
</code>```

///server

```<code>app.get('/download/', function(req, res){

  var file = __dirname + '/uploads/BasicUserFile-5a093a24870eb12148262248.jpg';
  res.download(file);
});
</code>```

答:
Your call on the client is for a GET but your server defines a POST.  For standards compliance sake, change your server to accept a GET request like so:

```<code>app.get('/download/:id', function(req, res){
  var basic_id = req.params.id
  var file = __dirname + '/uploads/BasicUserFile-'+ basic_id+ ".jpg";
  res.download(file);
});
</code>```

Also, it's not clear from what you've posted whether the client is constructing the right URL in any case, so make sure you double check that.

Title: file not dowloading in react , node js

Body:
I want to download a file in my download folder . The file is in the uploads folder, both the folders are in same directory . The file name is BasicUserFile-id.jpg

/// 2nd attempt: This time I am trying to get the file by hardcoding the file name but it's also not working, instead a blank file is getting downloaded.

app.js

  Filedownload(e) {

    e.preventDefault();

    var id = this.props.params.id;

    console.log(id);

    $.ajax({
      type: 'GET',
      url: '/download/' + id,
      success: function (data, textStatus, request) {
        window.open('./downloads/ ', '_self');
      }

    });

  }

   <button type="button" value="Download File" onClick={this.Filedownload}
   className="btn btn-success btn-lg">Download file</button>

////server.js

app.get('/download/:id', function(req, res){
  var basic_id = req.params.id
  var file = __dirname + '/uploads/BasicUserFile-'+ basic_id+ ".jpg";
  res.download(file);
});

/// 2nd try .

 Filedownload(e) {

    e.preventDefault();

    $.ajax({
      type: 'GET',
      url: '/download/' ,
      success : function(data)

      {

        fileDownload(data, 'filename.jpg');
        console.log("file downloaded")

      }

    });

  }

///server

app.get('/download/', function(req, res){

  var file = __dirname + '/uploads/BasicUserFile-5a093a24870eb12148262248.jpg';
  res.download(file);
});

Body:
Your call on the client is for a GET but your server defines a POST.  For standards compliance sake, change your server to accept a GET request like so:

app.get('/download/:id', function(req, res){
  var basic_id = req.params.id
  var file = __dirname + '/uploads/BasicUserFile-'+ basic_id+ ".jpg";
  res.download(file);
});

Also, it's not clear from what you've posted whether the client is constructing the right URL in any case, so make sure you double check that.


问:
mongoimport - treat CSV "Infinity" string literal as string, not as Double value
I am importing data for a client and have noticed that the string literal "Infinity", when it appears in a CSV file, is treated as a Double value rather than an actual string.

This could make sense when the value was not enclosed in quotes, but I believe in this context it should be treated as a string.

Take the following (simplified) CSV input file:

```<code>ID,Name
1,"Infinity"
</code>```

When imported as follows:

mongoimport.exe -v --host localhost:27017 --username admin --password password --authenticationDatabase admin -d "infinity-test" -c "test-data" --file C:\test-data.csv --type csv --headerline

It yields the following result:

```<code>MongoDB shell version v3.4.10
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.10
> use infinity-test
switched to db infinity-test
> db.getCollection('test-data').find()
{ "_id" : ObjectId("5a09c48ba7025b2e68885f91"), "ID" : 1, "Name" : Infinity }
>
</code>```

The issue is easier to spot in MongoBooster where it gives the field type:

Is there a way to force mongoimport to treat the literal "Infinity" as a string?

答:
Just to elaborate on Neil's comment, in MongoDB 3.4, mongoimport accepts --columnsHaveTypes parameter, which specifies the datatype of the field. By default, it guesses the type based on the content.

The full documentation on possible types is https://docs.mongodb.com/manual/reference/program/mongoimport/#cmdoption-columnshavetypes

For example, you can modify the CSV headerfile to specify that both fields are string instead of numbers:

```<code>ID.string(),Name.string()
1,"Infinity"
</code>```

and import using mongoimport --type=csv --columnsHaveTypes ...

Body:
I am importing data for a client and have noticed that the string literal "Infinity", when it appears in a CSV file, is treated as a Double value rather than an actual string.

This could make sense when the value was not enclosed in quotes, but I believe in this context it should be treated as a string.

Take the following (simplified) CSV input file:

ID,Name
1,"Infinity"

When imported as follows:

mongoimport.exe -v --host localhost:27017 --username admin --password password --authenticationDatabase admin -d "infinity-test" -c "test-data" --file C:\test-data.csv --type csv --headerline

It yields the following result:

MongoDB shell version v3.4.10
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.10
> use infinity-test
switched to db infinity-test
> db.getCollection('test-data').find()
{ "_id" : ObjectId("5a09c48ba7025b2e68885f91"), "ID" : 1, "Name" : Infinity }
>

The issue is easier to spot in MongoBooster where it gives the field type:

Is there a way to force mongoimport to treat the literal "Infinity" as a string?

Body:
Just to elaborate on Neil's comment, in MongoDB 3.4, mongoimport accepts --columnsHaveTypes parameter, which specifies the datatype of the field. By default, it guesses the type based on the content.

The full documentation on possible types is https://docs.mongodb.com/manual/reference/program/mongoimport/#cmdoption-columnshavetypes

For example, you can modify the CSV headerfile to specify that both fields are string instead of numbers:

ID.string(),Name.string()
1,"Infinity"

and import using mongoimport --type=csv --columnsHaveTypes ...


问:
adonis-scheduler module running several times
I've installed adonis-scheduler module, and I set up the time to run everyday, following the pattern according to node-scheduler which it makes use of:

```<code>static get schedule() {
  return '* */23 * * *'
}
</code>```

But it happens that I saw results many times today, like it wasn't set for every day. Is this correct?

答:
The cron expression you have listed should run every minute. You may be looking for something like 0 */23 * * *.

This site is helpful for writing cron expressions.

Body:
I've installed adonis-scheduler module, and I set up the time to run everyday, following the pattern according to node-scheduler which it makes use of:

static get schedule() {
  return '* */23 * * *'
}

But it happens that I saw results many times today, like it wasn't set for every day. Is this correct?


问:
Entity Framework "Unexpected Connection State" Exception
After three hours of debugging and searching, I'm hoping someone here has an answer. Entity Framework (using MySQL) throws the following exception if I call the following function quickly in succession (e.g. < 0.1 seconds apart).

System.InvalidOperationException: Unexpected connection state. When using a wrapping provider ensure that the StateChange event is implemented on the wrapped DbConnection.

However, sometimes the function works without any problems. The exception is thrown on the first ToList() call:

```<code>void InsertOrUpdateMaterials(List<Material> materials)
{
    var id = GetUserId();
    var materialIds = materials.Select(x => x.MaterialId).ToList();

    // Remove old materials from DB
    var oldMaterials = Db.Materials.Where(p => p.CreatedBy == id &&
            materialIds.Contains(p.MaterialId)).ToList(); // exception
    Db.Materials.RemoveRange(oldMaterials);
    Db.SaveChanges();

    // Replace previous materials with the new ones in list
    Db.Materials.AddRange(materials);
    Db.SaveChanges();
}
</code>```

Oddly, this error never occurred on the development server, so I looked into possible configuration issues to no avail.

Sometimes, Entity Framework throws:

System.Data.Entity.Core.EntityCommandExecutionException: There is already an open DataReader associated with this Connection which must be closed first.

Again pointing to the ToList() call. Any ideas?

答: I had this issue with Effort.EF6 1.3.0. The fix for me was to update the NMemory dependency from 1.1.0 to 1.1.2.

Body:
After three hours of debugging and searching, I'm hoping someone here has an answer. Entity Framework (using MySQL) throws the following exception if I call the following function quickly in succession (e.g. < 0.1 seconds apart).

System.InvalidOperationException: Unexpected connection state. When using a wrapping provider ensure that the StateChange event is implemented on the wrapped DbConnection.

However, sometimes the function works without any problems. The exception is thrown on the first ToList() call:

void InsertOrUpdateMaterials(List<Material> materials)
{
    var id = GetUserId();
    var materialIds = materials.Select(x => x.MaterialId).ToList();

    // Remove old materials from DB
    var oldMaterials = Db.Materials.Where(p => p.CreatedBy == id &&
            materialIds.Contains(p.MaterialId)).ToList(); // exception
    Db.Materials.RemoveRange(oldMaterials);
    Db.SaveChanges();

    // Replace previous materials with the new ones in list
    Db.Materials.AddRange(materials);
    Db.SaveChanges();
}

Oddly, this error never occurred on the development server, so I looked into possible configuration issues to no avail.

Sometimes, Entity Framework throws:

System.Data.Entity.Core.EntityCommandExecutionException: There is already an open DataReader associated with this Connection which must be closed first.

Again pointing to the ToList() call. Any ideas?


问:
Angular 4 unit testing OKTA SignIn not defined error
I am trying to write unit tests in Angular 4. In our application OKTA Sign In is being used. How to mock OKTA Sign in? I am getting an error OktaSignIn not defined</p>

答:
We are using okta-sign-in.min.js in our index.html. OktaSignIn object is declared in a service as below:

```<code>declare let OktaSignIn: any;
</code>```

This object is being used in the constructor of the service. During testing this object is not available.

Solution:
As mentioned in this link - https://developer.okta.com/blog/2017/03/27/angular-okta-sign-in-widget instead of including in index.html install the package and use it. One issue I faced not mentioned in the post is overriding Global Promise object of Zone.js. To fix this okta-sign-in-widget should be included before loading zone.js

Body:
We are using okta-sign-in.min.js in our index.html. OktaSignIn object is declared in a service as below:

declare let OktaSignIn: any;

This object is being used in the constructor of the service. During testing this object is not available.

Solution:
As mentioned in this link - https://developer.okta.com/blog/2017/03/27/angular-okta-sign-in-widget instead of including in index.html install the package and use it. One issue I faced not mentioned in the post is overriding Global Promise object of Zone.js. To fix this okta-sign-in-widget should be included before loading zone.js


问:
How can I serialize a redundant object to the serializer?
I have a model name CloudServer, which has a openstackserverid field, through it I can get a object:

```<code>class CloudServer(models.Model):
    openstackserverid = models.CharField(max_length=128)
    buytime = models.ForeignKey(to=BuyTime)
    expiration_time = models.DateTimeField()
    availablearea = models.ForeignKey(to=AvailableArea)
    profile = models.TextField()
</code>```

In the serializer:

```<code>class CloudServerListSerializer(ModelSerializer):
    class Meta:
        model = CloudServer
        fields = "__all__"
</code>```

In the views:

```<code>class CloudServerListAPIView(ListAPIView):
    serializer_class = CloudServerListSerializer
</code>```

I can use the bellow function to get the openstackserver object.

```<code>def getOpenstackServer(openstackserverid):

    ...
    return openstackserver
</code>```

The openstackserver object is like bellow:

```<code>openstack.compute.v2.server.ServerDetail(OS-EXT-STS:task_state=None,
addresses={u'private': [{u'OS-EXT-IPS-MAC:mac_addr': u'fa:16:3e:23:75:7b', u'version': 4, u'addr': u'192.168.1.8', u'OS-EXT-IPS:type': u'fixed'}]},
links=[{u'href': u'http://controller:8774/v2.1/99a50773b170406b8902227118bb72bf/servers/0672107f-e580-4a24-9d0a-867831d6b7d2', u'rel': u'self'}, {u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/servers/0672107f-e580-4a24-9d0a-867831d6b7d2', u'rel': u'bookmark'}],
image={u'id': u'ecbd1ef0-7dcf-41ff-8618-4501aa4e3945',
u'links': [{u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/images/ecbd1ef0-7dcf-41ff-8618-4501aa4e3945', u'rel': u'bookmark'}]},
OS-EXT-STS:vm_state=active, OS-EXT-SRV-ATTR:instance_name=instance-00000047, OS-SRV-USG:launched_at=2017-11-10T12:52:09.000000, flavor={u'id': u'a27c55bc-ef20-4dcf-a924-a02a4361fc01',
u'links': [{u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/flavors/a27c55bc-ef20-4dcf-a924-a02a4361fc01', u'rel': u'bookmark'}]}, id=0672107f-e580-4a24-9d0a-867831d6b7d2,
security_groups=[{u'name': u'default'}], user_id=fb52853bde3d4d3e8e831749781f8671, OS-DCF:diskConfig=MANUAL, accessIPv4=, accessIPv6=, progress=0, OS-EXT-STS:power_state=1, OS-EXT-AZ:availability_zone=nova, metadata={}, status=ACTIVE, updated=2017-11-10T12:52:09Z, hostId=76f61a58cf6d411a30e3e34da4dd252a03aa0093d9dd19c653b234b3, OS-SRV-USG:terminated_at=None, key_name=None, OS-EXT-SRV-ATTR:hypervisor_hostname=controller, name=vm-00000, created=2017-11-10T12:51:44Z, tenant_id=99a50773b170406b8902227118bb72bf, os-extended-volumes:volumes_attached=[], config_drive=)
</code>```

So far, as all I know, I only can serialize the CloudServer model's fields.

Where I can serialize the object, is in the serializers or views ? and how to do with that?

答:
If I understand correctly, the openstackserver is not a Django Model.
You could add a method field in your serializer:

Firstly, you will need to define a serializer for your openstackserver objects:

```<code>class OpenStackServerSerializer(serializers.Serializer):
    """Serializer for the `openstackserver` object"""

    addresses = serializers.DictField()
    # Other fields of your `openstackserver` object

    class Meta:
        fields = (
            'adresses',
            # Other fields of your `openstackserver` object
        )

class CloudServerListSerializer(serializers.ModelSerializer):
     """Serializer for the `CloudServer` object"""

     openstackserver = serializers.SerializerMethodField()

     class Meta:
          fields = (
              'openstackserver',
              # Other fields...
          )

     def get_openstackserver(self, cloud_server):
         """Get the openstack from the current `CloudServer` instance and serialize it"""

         openstackserver = getOpenstackServer(cloud_server.openstackserverid)
         return OpenStackServerSerializer(openstackserver).data
</code>```

Like this, you should have a representation of each openstackserver associated with your cloud server.

Body:
I have a model name CloudServer, which has a openstackserverid field, through it I can get a object:

class CloudServer(models.Model):
    openstackserverid = models.CharField(max_length=128)
    buytime = models.ForeignKey(to=BuyTime)
    expiration_time = models.DateTimeField()
    availablearea = models.ForeignKey(to=AvailableArea)
    profile = models.TextField()

In the serializer:

class CloudServerListSerializer(ModelSerializer):
    class Meta:
        model = CloudServer
        fields = "__all__"

In the views:

class CloudServerListAPIView(ListAPIView):
    serializer_class = CloudServerListSerializer

I can use the bellow function to get the openstackserver object.

def getOpenstackServer(openstackserverid):

    ...
    return openstackserver

The openstackserver object is like bellow:

openstack.compute.v2.server.ServerDetail(OS-EXT-STS:task_state=None,
addresses={u'private': [{u'OS-EXT-IPS-MAC:mac_addr': u'fa:16:3e:23:75:7b', u'version': 4, u'addr': u'192.168.1.8', u'OS-EXT-IPS:type': u'fixed'}]},
links=[{u'href': u'http://controller:8774/v2.1/99a50773b170406b8902227118bb72bf/servers/0672107f-e580-4a24-9d0a-867831d6b7d2', u'rel': u'self'}, {u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/servers/0672107f-e580-4a24-9d0a-867831d6b7d2', u'rel': u'bookmark'}],
image={u'id': u'ecbd1ef0-7dcf-41ff-8618-4501aa4e3945',
u'links': [{u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/images/ecbd1ef0-7dcf-41ff-8618-4501aa4e3945', u'rel': u'bookmark'}]},
OS-EXT-STS:vm_state=active, OS-EXT-SRV-ATTR:instance_name=instance-00000047, OS-SRV-USG:launched_at=2017-11-10T12:52:09.000000, flavor={u'id': u'a27c55bc-ef20-4dcf-a924-a02a4361fc01',
u'links': [{u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/flavors/a27c55bc-ef20-4dcf-a924-a02a4361fc01', u'rel': u'bookmark'}]}, id=0672107f-e580-4a24-9d0a-867831d6b7d2,
security_groups=[{u'name': u'default'}], user_id=fb52853bde3d4d3e8e831749781f8671, OS-DCF:diskConfig=MANUAL, accessIPv4=, accessIPv6=, progress=0, OS-EXT-STS:power_state=1, OS-EXT-AZ:availability_zone=nova, metadata={}, status=ACTIVE, updated=2017-11-10T12:52:09Z, hostId=76f61a58cf6d411a30e3e34da4dd252a03aa0093d9dd19c653b234b3, OS-SRV-USG:terminated_at=None, key_name=None, OS-EXT-SRV-ATTR:hypervisor_hostname=controller, name=vm-00000, created=2017-11-10T12:51:44Z, tenant_id=99a50773b170406b8902227118bb72bf, os-extended-volumes:volumes_attached=[], config_drive=)

So far, as all I know, I only can serialize the CloudServer model's fields.

Where I can serialize the object, is in the serializers or views ? and how to do with that?

Body:
If I understand correctly, the openstackserver is not a Django Model.
You could add a method field in your serializer:

Firstly, you will need to define a serializer for your openstackserver objects:

class OpenStackServerSerializer(serializers.Serializer):
    """Serializer for the `openstackserver` object"""

    addresses = serializers.DictField()
    # Other fields of your `openstackserver` object

    class Meta:
        fields = (
            'adresses',
            # Other fields of your `openstackserver` object
        )

class CloudServerListSerializer(serializers.ModelSerializer):
     """Serializer for the `CloudServer` object"""

     openstackserver = serializers.SerializerMethodField()

     class Meta:
          fields = (
              'openstackserver',
              # Other fields...
          )

     def get_openstackserver(self, cloud_server):
         """Get the openstack from the current `CloudServer` instance and serialize it"""

         openstackserver = getOpenstackServer(cloud_server.openstackserverid)
         return OpenStackServerSerializer(openstackserver).data

Like this, you should have a representation of each openstackserver associated with your cloud server.


问:
Resize Bootstrap 4 Dropdown Caret Size
Im using Bootstrap v4 framework in my html page. now i would like to resize or increase caret size in my dropdown list. Does anyone know how to do this?

Here it is my code

```<code><div class="container">
<form name="books">
    <div class="form-group">
    <select class="form-control" style="height:3rem">
        <option>Select Category</option>
        <option value="1">Tamil</option>
        <option value="2">English</option>
        <option value="3">Mathematics</option>
        <option value="4">Science</option>
    </select>
    </div>
</form>
</div>
</code>```

答:
Try this css

-webkit-appearance: none; to disable default caret and add it as background image.

 select.form-control{
    background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #fff;
    -webkit-appearance: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<form name="books">
    <div class="form-group">
    <select class="form-control" style="height:3rem">
        <option>Select Category</option>
        <option value="1">Tamil</option>
        <option value="2">English</option>
        <option value="3">Mathematics</option>
        <option value="4">Science</option>
    </select>
    </div>
</form>
</div></code>```

Title: Resize Bootstrap 4 Dropdown Caret Size

Body:
Im using Bootstrap v4 framework in my html page. now i would like to resize or increase caret size in my dropdown list. Does anyone know how to do this?

Here it is my code

<form name="books">

    <select class="form-control" style="height:3rem">
        <option>Select Category</option>
        <option value="1">Tamil</option>
        <option value="2">English</option>
        <option value="3">Mathematics</option>
        <option value="4">Science</option>
    </select>

</form>

Body:
Try this css

-webkit-appearance: none; to disable default caret and add it as background image.

 select.form-control{
    background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #fff;
    -webkit-appearance: none;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<form name="books">
    <div class="form-group">
    <select class="form-control" style="height:3rem">
        <option>Select Category</option>
        <option value="1">Tamil</option>
        <option value="2">English</option>
        <option value="3">Mathematics</option>
        <option value="4">Science</option>
    </select>
    </div>
</form>
</div>


问:
Results fixed on webpage
When I try to display content from another blade template, it will only show certain data on the webpage. What I want is inside this page, the content from test.blade.php together with the button, when click will pop up a form(I don't want the test.blade.php content to be inside). But whenever I try to do it, only certain information is shown and when I view page source, all the data has already been loaded. I have asked this question before already and someone told me it was the fault of my css, but I when I try to look at it, I don't really see anything which is causing this to happen. Can someone help me please? Thanks in advance!

I will put the screenshot here first in the question.

This is what it is suppose to look like where it will have a scroll down bar, and below there should be a button for the popup form.

But this is what I am getting (I have checked that all the data are already loaded)

elements.css (here is the css that I used)

```<code>#abc {
  width: 100%;
  height: 100%;
  opacity: .95;
  top: 0;
  left: 0;
  display: none;
  position: fixed;
  background-color: #313131;
  overflow: auto;
}

img#close {
  position: absolute;
  right: -14px;
  top: -14px;
  cursor: pointer;
}

div#popupContact {
  position: absolute;
  left: 50%;
  top: 17%;
  margin-left: -202px;
  font-family: 'Raleway', sans-serif;
}

form {
  max-width: 300px;
  min-width: 250px;
  padding: 10px 50px;
  border: 2px solid gray;
  border-radius: 10px;
  font-family: raleway;
  background-color: #fff;
}

p {
  margin-top: 30px;
}

h2 {
  background-color: #FEFFED;
  padding: 20px 35px;
  margin: -10px -50px;
  text-align: center;
  border-radius: 10px 10px 0 0;
}

hr {
  margin: 10px -50px;
  border: 0;
  border-top: 1px solid #ccc;
}

input[type=text] {
  width: 82%;
  padding: 10px;
  margin-top: 30px;
  border: 1px solid #ccc;
  padding-left: 40px;
  font-size: 16px;
  font-family: raleway;
}

#name {
  background-image: url(../images/name.jpg);
  background-repeat: no-repeat;
  background-position: 5px 7px;
}

#email {
  background-image: url(../images/email.png);
  background-repeat: no-repeat;
  background-position: 5px 7px;
}

textarea {
  background-image: url(../images/msg.png);
  background-repeat: no-repeat;
  background-position: 5px 7px;
  width: 82%;
  height: 95px;
  padding: 10px;
  resize: none;
  margin-top: 30px;
  border: 1px solid #ccc;
  padding-left: 40px;
  font-size: 16px;
  font-family: raleway;
  margin-bottom: 30px;
}

#submit {
  text-decoration: none;
  width: 100%;
  text-align: center;
  display: block;
  background-color: #FFBC00;
  color: #fff;
  border: 1px solid #FFCB00;
  padding: 10px 0;
  font-size: 20px;
  cursor: pointer;
  border-radius: 5px;
}

span {
  color: red;
  font-weight: 700;
}

button {
  width: 10%;
  height: 45px;
  border-radius: 3px;
  background-color: #cd853f;
  color: #fff;
  font-family: 'Raleway', sans-serif;
  font-size: 18px;
  cursor: pointer;
}
</code>```

evaltest.blade.php

```<code><html>
  <head>
    <title>Popup form </title>
    <meta name="robots" content="noindex, nofollow">
    <link href="{{ asset('css/elements.css') }}" rel="stylesheet">
    <script type="text/javascript">
      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-43981329-1']);
      _gaq.push(['_trackPageview']);
      (function () {
      var ga = document.createElement('script');
      ga.type = 'text/javascript';
      ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(ga, s);
      })();
    </script>
  </head>
  <!-- body starts here -->
  <body id ="bdy" style="overflow:hidden;">
    <div id="abc">
      <!-- Popup div starts here -->
      <div id="popupContact">
        <!-- contact us form -->
        <form class="form-horizontal" method="post" action="{{ url('/evaltest/'.$data0->id) }}">
          {{ csrf_field() }}
          <img id ="close" src="{{ URL::to('/image') }}/3.png" onclick ="div_hide()">
          <input type="hidden" name="user_id" value="{{$data0->id}}">
          <div class="form-group">
            <label class="col-md-2"><b>Recommendation:</b></label>
            <div class="col-md-6">
              <input type="radio" id ="recommendation" name="recommendation" value="Yes"> Yes<br>
              <input type="radio" id ="recommendation" name="recommendation" value="No"> No<br>
            </div>
          </div>
          <div class="form-group">
            <div class="col-md-6-offset-2">
              <input id= "submit" type="submit" href="javascript: check_empty()" class="btn btn-primary" value="Save">
            </div>
          </div>
        </form>
      </div>
      <!-- Popup Div Ends Here -->
      // @include('test')
      //it will show all data if I were to put here but I don't want to put it together with the popup form
    </div>
    <!-- Display Popup Button -->
    //this will show a few info but no button
    @include('test')
    <h1>Click Button to Evaluate</h1>
    <button id="popup" onclick="div_show()">Popup</button>
    <script src="{{ asset('/js/my_js.js') }}"></script>
    //this will show even lesser info but button is shown
    //@include('test')
  </body>
</html>
</code>```

test.blade.php (there are more information inside but I only put some as an example of how I got the information)

```<code><div class="container">
  @foreach ($data as $object)
    <b>Name: </b>{{ $object->Name }}<br><br>
    <b>Alias: </b>{{ $object->Alias }}<br><br>
    <b>Email: </b>{{$object->Email}}<br><br>
  @endforeach
</div>
</code>```

I have tried removing some of the things inside the css but nothing happen, I even try removing those with the position: fixed and also added .container but it still doesn't work.

myjs.js

```<code>// function to display popup
function div_show() {
  document.getElementById('abc').style.display = "block";
}

// function to hide popup
function div_hide(){
  document.getElementById('abc').style.display = "none";
}
</code>```

答: I have figured it out how to show my data is that I have to remove the style="overflow:hidden;" part so that it will work

Title: Results fixed on webpage

Body:
When I try to display content from another blade template, it will only show certain data on the webpage. What I want is inside this page, the content from test.blade.php together with the button, when click will pop up a form(I don't want the test.blade.php content to be inside). But whenever I try to do it, only certain information is shown and when I view page source, all the data has already been loaded. I have asked this question before already and someone told me it was the fault of my css, but I when I try to look at it, I don't really see anything which is causing this to happen. Can someone help me please? Thanks in advance!

I will put the screenshot here first in the question.

This is what it is suppose to look like where it will have a scroll down bar, and below there should be a button for the popup form.

But this is what I am getting (I have checked that all the data are already loaded)

elements.css (here is the css that I used)

#abc {
  width: 100%;
  height: 100%;
  opacity: .95;
  top: 0;
  left: 0;
  display: none;
  position: fixed;
  background-color: #313131;
  overflow: auto;
}

img#close {
  position: absolute;
  right: -14px;
  top: -14px;
  cursor: pointer;
}

div#popupContact {
  position: absolute;
  left: 50%;
  top: 17%;
  margin-left: -202px;
  font-family: 'Raleway', sans-serif;
}

form {
  max-width: 300px;
  min-width: 250px;
  padding: 10px 50px;
  border: 2px solid gray;
  border-radius: 10px;
  font-family: raleway;
  background-color: #fff;
}

p {
  margin-top: 30px;
}

h2 {
  background-color: #FEFFED;
  padding: 20px 35px;
  margin: -10px -50px;
  text-align: center;
  border-radius: 10px 10px 0 0;
}

hr {
  margin: 10px -50px;
  border: 0;
  border-top: 1px solid #ccc;
}

input[type=text] {
  width: 82%;
  padding: 10px;
  margin-top: 30px;
  border: 1px solid #ccc;
  padding-left: 40px;
  font-size: 16px;
  font-family: raleway;
}

#name {
  background-image: url(../images/name.jpg);
  background-repeat: no-repeat;
  background-position: 5px 7px;
}

#email {
  background-image: url(../images/email.png);
  background-repeat: no-repeat;
  background-position: 5px 7px;
}

textarea {
  background-image: url(../images/msg.png);
  background-repeat: no-repeat;
  background-position: 5px 7px;
  width: 82%;
  height: 95px;
  padding: 10px;
  resize: none;
  margin-top: 30px;
  border: 1px solid #ccc;
  padding-left: 40px;
  font-size: 16px;
  font-family: raleway;
  margin-bottom: 30px;
}

#submit {
  text-decoration: none;
  width: 100%;
  text-align: center;
  display: block;
  background-color: #FFBC00;
  color: #fff;
  border: 1px solid #FFCB00;
  padding: 10px 0;
  font-size: 20px;
  cursor: pointer;
  border-radius: 5px;
}

span {
  color: red;
  font-weight: 700;
}

button {
  width: 10%;
  height: 45px;
  border-radius: 3px;
  background-color: #cd853f;
  color: #fff;
  font-family: 'Raleway', sans-serif;
  font-size: 18px;
  cursor: pointer;
}

evaltest.blade.php

    <title>Popup form </title>
    <meta name="robots" content="noindex, nofollow">
    <link href="{{ asset('css/elements.css') }}" rel="stylesheet">

        <form class="form-horizontal" method="post" action="{{ url('/evaltest/'.$data0->id) }}">
          {{ csrf_field() }}

          <input type="hidden" name="user_id" value="{{$data0->id}}">

            Recommendation:

              <input type="radio" id ="recommendation" name="recommendation" value="Yes"> Yes

              <input type="radio" id ="recommendation" name="recommendation" value="No"> No

              <input id= "submit" type="submit" href="javascript: check_empty()" class="btn btn-primary" value="Save">

        </form>

      // @include('test')
      //it will show all data if I were to put here but I don't want to put it together with the popup form

    //this will show a few info but no button
    @include('test')

Click Button to Evaluate

    <button id="popup" onclick="div_show()">Popup</button>

    //this will show even lesser info but button is shown
    //@include('test')

test.blade.php (there are more information inside but I only put some as an example of how I got the information)

  @foreach ($data as $object)
    Name: {{ $object->Name }}

    Alias: {{ $object->Alias }}

    Email: {{$object->Email}}

  @endforeach

I have tried removing some of the things inside the css but nothing happen, I even try removing those with the position: fixed and also added .container but it still doesn't work.

myjs.js

// function to display popup
function div_show() {
  document.getElementById('abc').style.display = "block";
}

// function to hide popup
function div_hide(){
  document.getElementById('abc').style.display = "none";
}


问:
how do i find element  and click
Can someone help me how do i find  and click on it using Protractor

```<code><div class="col-md-3 col-sm-6 col-xs-8">
    <div class="nav-control pull-right">
            <li>
                <a class="btn theme-button" ng-click="loginSignUp()">Login/Signup</a>
            </li>
        </ul>
    </div>
</div>
</code>```

My attempts but none of them successfully so for.

```<code>$('.nav-control pull-right a').click();

var li = element(by.xpath('//ul/li/a'));
expect(li.getText()).toBe('Doge meme');

// by class name
element(by.className('btn theme-button')).click();

// by css
element(by.css('.btn')).click();
element(by.xpath('.//*[.="Login/Signup"]')).click();
element(by.xpath('//*[@id="top"]/div[4]/div/div/div[1]/div/div[1]/div[3]/div/ul/li/a')).click();
</code>```

Update:

I am able to click the  tag with following code.

```<code>  let el = element(by.cssContainingText('a', 'Login/Signup'));
  var EC = protractor.ExpectedConditions;
  browser.driver.wait(function () {
      browser.wait(EC.visibilityOf(el), 10000);
      browser.driver.manage().window().setSize(1280, 1024);
      el.click();
  });
</code>```

However, even it clicks the anchor tag but still complains in the console

Failed: unknown error: Element ... is not clickable at point (1164, 27).
  Other element would receive the click: ...
        (Session info: chrome=61.0.3163.100)
        (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT
  10.0.15063 x86_64)

答:
Can you try once with javascript executor click</p>

```<code>var elm = element(by.linkText('Login/Signup'));
browser.executeScript("arguments[0].click();", elm.getWebElement());
</code>```

Title: how do i find element <a> and click

Body:
Can someone help me how do i find  and click on it using Protractor

                Login/Signup

My attempts but none of them successfully so for.

$('.nav-control pull-right a').click();

var li = element(by.xpath('//ul/li/a'));
expect(li.getText()).toBe('Doge meme');

// by class name
element(by.className('btn theme-button')).click();

// by css
element(by.css('.btn')).click();
element(by.xpath('.//*[.="Login/Signup"]')).click();
element(by.xpath('//*[@id="top"]/div[4]/div/div/div[1]/div/div[1]/div[3]/div/ul/li/a')).click();

Update:

I am able to click the  tag with following code.

  let el = element(by.cssContainingText('a', 'Login/Signup'));
  var EC = protractor.ExpectedConditions;
  browser.driver.wait(function () {
      browser.wait(EC.visibilityOf(el), 10000);
      browser.driver.manage().window().setSize(1280, 1024);
      el.click();
  });

However, even it clicks the anchor tag but still complains in the console

Failed: unknown error: Element ... is not clickable at point (1164, 27).
  Other element would receive the click: ...
        (Session info: chrome=61.0.3163.100)
        (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT
  10.0.15063 x86_64)

Body:
Can you try once with javascript executor click

var elm = element(by.linkText('Login/Signup'));
browser.executeScript("arguments[0].click();", elm.getWebElement());


问:
Why does scanf skip getting string input?
I am trying to get multiple words input and multiple lines into one array. But somewhere the code skips getting the input and skips to end the program. I have tried adding space before and after the ' %s' (or '%s ') but it won't work (maybe because it's inside a loop?). Would really appreciate anyone's help! It also starts to act weird if I enter more than two-three words :(
My goal is to find how many times a specific letter has occurred throughout all those words and lines.</p>

```<code>#include <stdio.h> //include standard library

int main(){
  int lineCount, occuranceCount;
  printf("How many lines are you going to enter?");
  scanf("%d", &lineCount);

  char input[lineCount][100], searchChar;

  for(int i=0; i<lineCount; i++){
    printf("Please enter line #%d (100 characters of less):",i+1);
    scanf("%s", &input[i]);
  }

  printf("What letter do you want to check the frequence in those lines? ");
  scanf("%c", &searchChar);

  for(int j=0; j<lineCount; j++){
    for(int k=0; k<100; k++){
      if(input[j][k] != '\0'){
        if(input[j][k]==searchChar)
          occuranceCount++;
      }
    }
  }

  printf("The letter occurs for %d time", occuranceCount);

  return 0;
}
</code>```

答:
```<code>  scanf(" %c", &searchChar);
         ^
</code>```

You need the space over here to consume any \n from stdin.

Also scanf() will read one word not a line(space separated words) as you are thinking.

And also it is better to use strlen(input[j]) to know how much you should read.

Another thing, use size_t instead of int in the looping.

Intialize occuranceCount to 0.

Also to avoid buffer overrun exploits use scanf("%99s", input[i]); in your code.

In order to read a line you can use fgets().

Body:
I am trying to get multiple words input and multiple lines into one array. But somewhere the code skips getting the input and skips to end the program. I have tried adding space before and after the ' %s' (or '%s ') but it won't work (maybe because it's inside a loop?). Would really appreciate anyone's help! It also starts to act weird if I enter more than two-three words :(
My goal is to find how many times a specific letter has occurred throughout all those words and lines.

#include <stdio.h> //include standard library

int main(){
  int lineCount, occuranceCount;
  printf("How many lines are you going to enter?");
  scanf("%d", &lineCount);

  char input[lineCount][100], searchChar;

  for(int i=0; i<lineCount; i++){
    printf("Please enter line #%d (100 characters of less):",i+1);
    scanf("%s", &input[i]);
  }

  printf("What letter do you want to check the frequence in those lines? ");
  scanf("%c", &searchChar);

  for(int j=0; j<lineCount; j++){
    for(int k=0; k<100; k++){
      if(input[j][k] != '\0'){
        if(input[j][k]==searchChar)
          occuranceCount++;
      }
    }
  }

  printf("The letter occurs for %d time", occuranceCount);

  return 0;
}

Body:
  scanf(" %c", &searchChar);
         ^

You need the space over here to consume any \n from stdin.

Also scanf() will read one word not a line(space separated words) as you are thinking.

And also it is better to use strlen(input[j]) to know how much you should read.

Another thing, use size_t instead of int in the looping.

Intialize occuranceCount to 0.

Also to avoid buffer overrun exploits use scanf("%99s", input[i]); in your code.

In order to read a line you can use fgets().


问:
angular 2 function calling inside an http post function
I have a http post function.

```<code>login(){

    var data = {
      email : this.name,
      password : this.pass,
      appId : this.appId
    };
    console.log(data);

    this.http.post(SERVER_URL+"/templatesAuth/authenticateForApp",data)
      .subscribe(function(res){

         let requestParams = {
            "token": res.token,
            "email": data.email,
            "name": res.user.name,
            "phone": res.user.phone,
            "streetNumber": res.user.streetNumber,
            "streetName": res.user.streetName,
            "country": res.user.country,
            "city": res.user.city,
            "zip": res.user.zip,
            "type": 'internal',
            "appId":res.user.appId,
            "registeredUser": res.user.sub
          };

        },
        function(err){
          alert('login failed');
        })

  }
</code>```

inside the function(req){ } I cannot write or use calls like examplearray.push();
im always having an error Cannot read property 'push' of undefined

when I use Local storage functions like.

```<code>this.localStorageService.set('test'+this.appId,(requestParams));
</code>```

error : Cannot read property 'set' of undefined

but I can use them out side of the function(req){ }. couldn't figure-out the problem

is there any way to get the requestParams outside.

答:
This is very common issue of scoping :

Just change the line

```<code>.subscribe(function(res){
</code>```

to

```<code>.subscribe((res) => {
</code>```

Another way of doing is :

```<code>.subscribe(function(res){ ... }).bind(this)
</code>```

Great article to read : https://toddmotto.com/es6-arrow-functions-syntaxes-and-lexical-scoping/
and check  this answer for : Difference between arrow function and bind()

Body:
I have a http post function.

login(){

    var data = {
      email : this.name,
      password : this.pass,
      appId : this.appId
    };
    console.log(data);

    this.http.post(SERVER_URL+"/templatesAuth/authenticateForApp",data)
      .subscribe(function(res){

         let requestParams = {
            "token": res.token,
            "email": data.email,
            "name": res.user.name,
            "phone": res.user.phone,
            "streetNumber": res.user.streetNumber,
            "streetName": res.user.streetName,
            "country": res.user.country,
            "city": res.user.city,
            "zip": res.user.zip,
            "type": 'internal',
            "appId":res.user.appId,
            "registeredUser": res.user.sub
          };

        },
        function(err){
          alert('login failed');
        })

  }

inside the function(req){ } I cannot write or use calls like examplearray.push();
im always having an error Cannot read property 'push' of undefined

when I use Local storage functions like.

this.localStorageService.set('test'+this.appId,(requestParams));

error : Cannot read property 'set' of undefined

but I can use them out side of the function(req){ }. couldn't figure-out the problem

is there any way to get the requestParams outside.

Body:
This is very common issue of scoping :

Just change the line

.subscribe(function(res){

to

.subscribe((res) => {

Another way of doing is :

.subscribe(function(res){ ... }).bind(this)

Great article to read : https://toddmotto.com/es6-arrow-functions-syntaxes-and-lexical-scoping/
and check  this answer for : Difference between arrow function and bind()


问:
How to remove border right form last child div?

How do i remove border right form the last div?

.process {
  border-right: 1px solid #e0e0e0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="job-posting">
  <div class="row">
    <div class="col-md-4">
      <div class="process">
        <header>STEP 1</header>
        <div class="process-content">
          <i class="fa fa-user-plus icon" aria-hidden="true"></i>
          <h1>Signup</h1>
          <p>Sign Up as a Company or an Individual</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 2</header>
        <div class="process-content">
          <i class="fa fa-upload icon" aria-hidden="true"></i>
          <h1>Upload Resume</h1>
          <p>Upload your resume and provide us with details of you experience and skills</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 3</header>
        <div class="process-content">
          <i class="fa fa-smile-o icon" aria-hidden="true"></i>
          <h1>Get Hired</h1>
          <p>Browse the available job postings and get hired according to your skills</p>
        </div>
      </div>
    </div>
  </div>
</div></code>```

I'm having trouble removing the right border form the last div I tried using the :last-child:border:remove;

答:
Just add this css:

```<code>.job-posting .col-md-4:last-child .process {
  border-right: 0;
}
</code>```

.process {
  border-right: 1px solid #e0e0e0;
}
.job-posting .col-md-4:last-child .process {
  border-right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="job-posting">
  <div class="row">
    <div class="col-md-4">
      <div class="process">
        <header>STEP 1</header>
        <div class="process-content">
          <i class="fa fa-user-plus icon" aria-hidden="true"></i>
          <h1>Signup</h1>
          <p>Sign Up as a Company or an Individual</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 2</header>
        <div class="process-content">
          <i class="fa fa-upload icon" aria-hidden="true"></i>
          <h1>Upload Resume</h1>
          <p>Upload your resume and provide us with details of you experience and skills</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 3</header>
        <div class="process-content">
          <i class="fa fa-smile-o icon" aria-hidden="true"></i>
          <h1>Get Hired</h1>
          <p>Browse the available job postings and get hired according to your skills</p>
        </div>
      </div>
    </div>
  </div>
</div></code>```

Body:
How do i remove border right form the last div?

.process {
  border-right: 1px solid #e0e0e0;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        STEP 1

Signup

Sign Up as a Company or an Individual

        STEP 2

Upload Resume

Upload your resume and provide us with details of you experience and skills

        STEP 3

Get Hired

Browse the available job postings and get hired according to your skills

I'm having trouble removing the right border form the last div I tried using the :last-child:border:remove;

Body:
Just add this css:

.job-posting .col-md-4:last-child .process {
  border-right: 0;
}

.process {
  border-right: 1px solid #e0e0e0;
}
.job-posting .col-md-4:last-child .process {
  border-right: 0;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="job-posting">
  <div class="row">
    <div class="col-md-4">
      <div class="process">
        <header>STEP 1</header>
        <div class="process-content">
          <i class="fa fa-user-plus icon" aria-hidden="true"></i>
          <h1>Signup</h1>
          <p>Sign Up as a Company or an Individual</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 2</header>
        <div class="process-content">
          <i class="fa fa-upload icon" aria-hidden="true"></i>
          <h1>Upload Resume</h1>
          <p>Upload your resume and provide us with details of you experience and skills</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 3</header>
        <div class="process-content">
          <i class="fa fa-smile-o icon" aria-hidden="true"></i>
          <h1>Get Hired</h1>
          <p>Browse the available job postings and get hired according to your skills</p>
        </div>
      </div>
    </div>
  </div>
</div>


问:
New line in subscript in share latex
I am trying to shift this extra long subscript to the line below, because it is too long. The code is

\mathop{\mathbb{E}}_{x \in p_{data}(x), z \in p_{z}(z)}

And the expression looks like :

I want the characters z onwards to be in a new line, while being the subscript to E.

Thanks!

答:
Instead of \mathop directive you can use the following:

```<code>$\mathbb{E}}_{x \in p_{data}(x),$

$z \in p_{z}(z)}$
</code>```

Which will render this:

Another alternative

```<code>$\mathbb{E}}_{x \in p_{data}(x),$

$_{z \in p_{z}(z)}}$
</code>```

which will render into:

Title: New line in subscript in share latex

Body:
Instead of \mathop directive you can use the following:

$\mathbb{E}}_{x \in p_{data}(x),$

$z \in p_{z}(z)}$

Which will render this:

Another alternative

$\mathbb{E}}_{x \in p_{data}(x),$

$_{z \in p_{z}(z)}}$

which will render into:


答:
1) Change

```<code>  scanf("%c", &searchChar); -->   scanf(" %c", &searchChar);
</code>```

to get rid of any \n left in the input buffer from previous scanf

2) Change

```<code>for(int k=0; k<100; k++){ --> for(int k=0; k<strlen(input[j]); k++){
</code>```

to avoid reading beyond the actual user input.

Besides that:

Never do scanf("%s", &input[i]); as the user can overflow your input buffer. At least change it to: scanf("%99s", &input[i]); but consider using fgets instead

Using fgets your program could be:

```<code>#include <stdio.h>

int main(){
  size_t lineCount = 0, occuranceCount = 0;
  printf("How many lines are you going to enter?");
  scanf("%zu ", &lineCount);
  if (lineCount == 0) return 0;  // Input error

  char input[lineCount][100], searchChar;

  for(size_t i=0; i<lineCount; i++){
    printf("Please enter line #%zu (100 characters of less):",i+1);
    fgets(input[i], 100, stdin);
  }

  printf("What letter do you want to check the frequence in those lines? ");
  scanf("%c", &searchChar);

  for(size_t j=0; j<lineCount; j++){
    for(size_t k=0; k<strlen(input[j]); k++){
        if(input[j][k]==searchChar) occuranceCount++;
    }
  }

  printf("The letter occurs for %zu time", occuranceCount);

  return 0;
}
</code>```

Title: Why does scanf skip getting string input?

Body:
1) Change

  scanf("%c", &searchChar); -->   scanf(" %c", &searchChar);

to get rid of any \n left in the input buffer from previous scanf

2) Change

for(int k=0; k<100; k++){ --> for(int k=0; k<strlen(input[j]); k++){

to avoid reading beyond the actual user input.

Besides that:

Never do scanf("%s", &input[i]); as the user can overflow your input buffer. At least change it to: scanf("%99s", &input[i]); but consider using fgets instead

Using fgets your program could be:

#include <stdio.h>

int main(){
  size_t lineCount = 0, occuranceCount = 0;
  printf("How many lines are you going to enter?");
  scanf("%zu ", &lineCount);
  if (lineCount == 0) return 0;  // Input error

  char input[lineCount][100], searchChar;

  for(size_t i=0; i<lineCount; i++){
    printf("Please enter line #%zu (100 characters of less):",i+1);
    fgets(input[i], 100, stdin);
  }

  printf("What letter do you want to check the frequence in those lines? ");
  scanf("%c", &searchChar);

  for(size_t j=0; j<lineCount; j++){
    for(size_t k=0; k<strlen(input[j]); k++){
        if(input[j][k]==searchChar) occuranceCount++;
    }
  }

  printf("The letter occurs for %zu time", occuranceCount);

  return 0;
}


答:
You should use arrow function .When using arrow functions,property is not overwritten
change it as,</p>

```<code>.subscribe((res) => {
</code>```

Title: angular 2 function calling inside an http post function

Body:
You should use arrow function .When using arrow functions,property is not overwritten
change it as,

.subscribe((res) => {


问:
How do I configure sqlalchemy to correctly store emoji?
With sqlalchemy 0.9.7, I am trying to store emoji into MySQL 5.5 with utf8mb4 enabled. However, for some reason sqlalchemy is killing my emoji chars and I cannot figure out why. I can see the emoji char in the object before attempting to save the data via sqlalchemy. After the save, an error is thrown and emoji is rendered as ????.

The error is the following. Note it is surrounded by debug messages that output type(post.message) and post.message.

```<code>--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:274]:
<type 'unicode'>
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:275]:

--------------------------------------------------------------------------------
/mnt/hgfs/crw/dev/hyper/env/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py:436: Warning: Incorrect string value: '\xF0\x9F\x98\x83' for column 'message' at row 1
  cursor.execute(statement, parameters)
--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:277]:
<type 'unicode'>
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:278]:
????
--------------------------------------------------------------------------------
</code>```

My code looks like:

```<code>Base = declarative_base()

post = Table('post', Base.metadata,
        Column("id", Integer, primary_key=True),
        Column("message", UnicodeText),
        Column("created_at", DateTime),
        Column("updated_at", DateTime),
    )

mapper(Post, post)
</code>```

Is there any other setup I need to do to make this work?

Update: If I do the following:

```<code>Base = declarative_base()

post = Table('post', Base.metadata,
        Column("id", Integer, primary_key=True),
        Column("message", UnicodeText),
        Column("created_at", DateTime),
        Column("updated_at", DateTime),
        mysql_engine='InnoDB',
        mysql_charset='utf8mb4'
    )

mapper(Post, post)
</code>```

I get the following:

```<code>--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:274]:
<type 'unicode'>
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:275]:

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:277]:
<type 'unicode'>
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:278]:
????
--------------------------------------------------------------------------------
</code>```

No error, but it is still obliterating the emoji. What is going on?!

Update 2:

Changing the database URI being called from:

```<code>mysql+mysqldb://user:pass@localhost/datab?charset=utf8
</code>```

To

```<code>mysql+mysqldb://user:pass@localhost/datab
</code>```

Fixed the problem. sqlalchemy threw an error when I tried to use charset=utf8mb4&use_unicode=0. But is that wise? According to http://docs.sqlalchemy.org/en/rel_0_9/dialects/mysql.html#module-sqlalchemy.dialects.mysql.mysqldb, it is not! Would love any feedback on this solution.

答:
Below's how I got emojis etc. working. I'm using Python 3.5 / Flask / Flask-SQLAlchemy.

Note: This fix assumes you're early enough in development that you're OK with recreating your database by running db.drop_all() and db.create_all().

As recommended in this guide, open up a database console and run ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

As recommended in this answer, add ?charset=utf8mb4 to the end of your SQLALCHEMY_DATABASE_URI string.

Before: mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}

After: mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}?charset=utf8mb4

Now just rerun db.drop_all() and db.create_all().

Body:
With sqlalchemy 0.9.7, I am trying to store emoji into MySQL 5.5 with utf8mb4 enabled. However, for some reason sqlalchemy is killing my emoji chars and I cannot figure out why. I can see the emoji char in the object before attempting to save the data via sqlalchemy. After the save, an error is thrown and emoji is rendered as ????.

The error is the following. Note it is surrounded by debug messages that output type(post.message) and post.message.

--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:274]:
<type 'unicode'>
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:275]:

--------------------------------------------------------------------------------
/mnt/hgfs/crw/dev/hyper/env/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py:436: Warning: Incorrect string value: '\xF0\x9F\x98\x83' for column 'message' at row 1
  cursor.execute(statement, parameters)
--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:277]:
<type 'unicode'>
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:278]:
????
--------------------------------------------------------------------------------

My code looks like:

Base = declarative_base()

post = Table('post', Base.metadata,
        Column("id", Integer, primary_key=True),
        Column("message", UnicodeText),
        Column("created_at", DateTime),
        Column("updated_at", DateTime),
    )

mapper(Post, post)

Is there any other setup I need to do to make this work?

Update: If I do the following:

Base = declarative_base()

post = Table('post', Base.metadata,
        Column("id", Integer, primary_key=True),
        Column("message", UnicodeText),
        Column("created_at", DateTime),
        Column("updated_at", DateTime),
        mysql_engine='InnoDB',
        mysql_charset='utf8mb4'
    )

mapper(Post, post)

I get the following:

--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:274]:
<type 'unicode'>
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:275]:

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:277]:
<type 'unicode'>
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
DEBUG in __init__ [/mnt/hgfs/crw/dev/hyper/hyper/blueprint/chat/__init__.py:278]:
????
--------------------------------------------------------------------------------

No error, but it is still obliterating the emoji. What is going on?!

Update 2:

Changing the database URI being called from:

mysql+mysqldb://user:pass@localhost/datab?charset=utf8

To

mysql+mysqldb://user:pass@localhost/datab

Fixed the problem. sqlalchemy threw an error when I tried to use charset=utf8mb4&use_unicode=0. But is that wise? According to http://docs.sqlalchemy.org/en/rel_0_9/dialects/mysql.html#module-sqlalchemy.dialects.mysql.mysqldb, it is not! Would love any feedback on this solution.


问:
Powershell LastWriteTime
I am writing a script to test for old files in a synchronized folder, and send a text message if a file is older than 2 hours (this would mean that a file failed to update). I haven't included the "texting" part, because that works fine.

When I run my script I get three date:times for many of the files. Why do I get three values for the "last" writetime? And, how do I only look at the most recent "last" writetime?

Here's my script...

```<code>$Store = “ALI”, “COR”, “ELD”, “GRY”, “HML”, “JB”, “SWN”, “LBT”, “LGC”, “MAU”, “MID”, “MPW”, “RKE”, “SPC”, “SSP”, “TWL”, “WRD”
foreach ($element in $Store)
{
$FPath = "E:\ServerFolders\SData\$element\$element-Cmp"
$FPath = $FPath.Replace("-", "_")
if(Get-Childitem $FPath  | Where-Object {$_.LastWriteTime -lt (get-date).addHours(-2) })
{
$FName = Get-ChildItem $FPath -name -Filter "*.7Z"
$FTime = (Get-ChildItem $FPath).LastWriteTime

$FName
$FTime
}}
</code>```

Here's my output...

```<code>TX029.7Z
Wednesday, September 13, 2017 11:44:54 AM
Monday, November 13, 2017 8:01:34 PM
Monday, November 13, 2017 7:45:45 PM
TX059.7Z
Tuesday, August 22, 2017 7:56:18 PM
Monday, November 13, 2017 8:03:56 PM
Monday, November 13, 2017 8:41:05 PM
TX013.7Z
Monday, November 13, 2017 8:01:33 PM
Monday, November 13, 2017 7:33:20 PM
Friday, November 10, 2017 2:38:20 PM
TX050.7z
Monday, November 13, 2017 8:02:17 PM
Monday, November 13, 2017 9:46:19 AM
Tuesday, October 31, 2017 7:46:01 AM
</code>```

Help would be greatly appreciated!!

I ran the code that Stephen suggested. I am still getting multiple values for LastWriteTime for many of my files.

This is the resultant output on 11/24/17 at 8:57 AM, when all files show a timestamp in a dir of approximately 8:46 AM or so.

```<code>PS C:\Windows\system32> $Store = “ALI”, “COR”, “ELD”, “GRY”, “HML”, “JB”, “SWN”, “LBT”, “LGC”, “MAU”, “MID”, “MPW”, “RKE”, “SPC”, “SSP”, “TWL”, “WRD”
foreach ($element in $Store)
{
    $FPath = "E:\ServerFolders\SData\$element\$element-Cmp"
    $FPath = $FPath.Replace("-", "_")
    #this if statement does not return a true / false value
    #PowerShell is using whether an object is returned by Get-ChildItem
    # or not to try and determine a boolean value
    if(Get-Childitem $FPath  | Where-Object {$_.LastWriteTime -lt (get-date).addHours(-2) })
{
#at this point all we know is that some file exists with a write time
#of more than 2 hours but it could be any file

#You then get the name but only of all *.7z files in the path
#but there's no guarantee that this is the file you need
$FName = Get-ChildItem $FPath -name -Filter "*.7Z"

#This line gets the lastwritetime for all files in the folder
#regardless of the lastwritetime of the file
$FTime = (Get-ChildItem $FPath).LastWriteTime

$FName
$FTime
}}
TX025.7Z

Thursday, November 23, 2017 11:04:20 AM
Friday, November 24, 2017 8:46:54 AM
TX029.7Z
Wednesday, September 13, 2017 11:44:54 AM
Thursday, November 23, 2017 11:01:26 AM
Friday, November 24, 2017 8:45:45 AM
TX049.7Z
Thursday, November 23, 2017 11:03:18 AM
Wednesday, November 22, 2017 5:46:02 PM
GA007.7Z
Thursday, November 23, 2017 7:45:38 PM
Thursday, November 23, 2017 11:02:20 AM
GA004.7Z
Friday, November 24, 2017 8:47:01 AM
Thursday, November 23, 2017 11:30:53 AM
GA003.7Z
Friday, November 24, 2017 8:47:10 AM
Thursday, November 23, 2017 10:30:48 AM
MO001.7Z
Thursday, November 23, 2017 11:04:45 AM
Thursday, November 23, 2017 7:47:08 PM
TX059.7Z
Tuesday, August 22, 2017 7:56:18 PM
Thursday, November 23, 2017 11:03:48 AM
Friday, November 24, 2017 8:41:02 AM
AR001.7Z
Thursday, November 23, 2017 7:46:02 PM
Thursday, November 23, 2017 11:05:08 AM
TX013.7Z
Thursday, November 23, 2017 11:01:25 AM
Friday, November 24, 2017 8:34:11 AM
TX050.7z
Thursday, November 23, 2017 11:02:03 AM
Friday, November 24, 2017 8:46:19 AM
TX024.7Z
Thursday, November 23, 2017 11:03:48 AM
Thursday, November 23, 2017 8:40:36 PM
GA010.7Z
Friday, November 24, 2017 8:45:24 AM
Thursday, November 23, 2017 11:02:39 AM
TX002.7Z
Thursday, November 23, 2017 11:02:03 AM
Friday, November 24, 2017 8:43:45 AM
TX035.7Z
Thursday, November 23, 2017 11:03:17 AM
Friday, November 24, 2017 8:51:39 AM

PS C:\Windows\system32>
</code>```

答:
You are overly complicating the process. You can simply add a select-object to grab the 2 properties you want.

```<code>$Store = “ALI”, “COR”, “ELD”, “GRY”, “HML”, “JB”, “SWN”, “LBT”, “LGC”, “MAU”, “MID”, “MPW”, “RKE”, “SPC”, “SSP”, “TWL”, “WRD”
foreach ($element in $Store)
{
    $FPath = "E:\ServerFolders\SData\$element\$element-Cmp"
    $FPath = $FPath.Replace("-", "_")
    #Filter for *.7z, with a lastwritetime older than 2 hours
    #Grab only the name and lastwritetime
    Get-Childitem $FPath -Filter "*.7z" |
        Where-Object {$_.LastWriteTime -lt (get-date).addHours(-2) } |
        Select-Object Name, LastWriteTime
}
</code>```

EDIT: Explaining the logic of the original process

```<code>$Store = “ALI”, “COR”, “ELD”, “GRY”, “HML”, “JB”, “SWN”, “LBT”, “LGC”, “MAU”, “MID”, “MPW”, “RKE”, “SPC”, “SSP”, “TWL”, “WRD”
foreach ($element in $Store)
{
    $FPath = "E:\ServerFolders\SData\$element\$element-Cmp"
    $FPath = $FPath.Replace("-", "_")
    #this if statement does not return a true / false value
    #PowerShell is using whether an object is returned by Get-ChildItem
    # or not to try and determine a boolean value
    if(Get-Childitem $FPath  | Where-Object {$_.LastWriteTime -lt (get-date).addHours(-2) })
{
#at this point all we know is that some file exists with a write time
#of more than 2 hours but it could be any file

#You then get the name but only of all *.7z files in the path
#but there's no guarantee that this is the file you need
$FName = Get-ChildItem $FPath -name -Filter "*.7Z"

#This line gets the lastwritetime for all files in the folder
#regardless of the lastwritetime of the file
$FTime = (Get-ChildItem $FPath).LastWriteTime

$FName
$FTime
}}
</code>```

Without seeing the original file structure its hard to tell exactly what you are working with but the above should explain why you are getting multiple lastwritetime values in your script.

Title: Powershell LastWriteTime

Body:
I am writing a script to test for old files in a synchronized folder, and send a text message if a file is older than 2 hours (this would mean that a file failed to update). I haven't included the "texting" part, because that works fine.

When I run my script I get three date:times for many of the files. Why do I get three values for the "last" writetime? And, how do I only look at the most recent "last" writetime?

Here's my script...

$Store = “ALI”, “COR”, “ELD”, “GRY”, “HML”, “JB”, “SWN”, “LBT”, “LGC”, “MAU”, “MID”, “MPW”, “RKE”, “SPC”, “SSP”, “TWL”, “WRD”
foreach ($element in $Store)
{
$FPath = "E:\ServerFolders\SData\$element\$element-Cmp"
$FPath = $FPath.Replace("-", "_")
if(Get-Childitem $FPath  | Where-Object {$_.LastWriteTime -lt (get-date).addHours(-2) })
{
$FName = Get-ChildItem $FPath -name -Filter "*.7Z"
$FTime = (Get-ChildItem $FPath).LastWriteTime

$FName
$FTime
}}

Here's my output...

TX029.7Z
Wednesday, September 13, 2017 11:44:54 AM
Monday, November 13, 2017 8:01:34 PM
Monday, November 13, 2017 7:45:45 PM
TX059.7Z
Tuesday, August 22, 2017 7:56:18 PM
Monday, November 13, 2017 8:03:56 PM
Monday, November 13, 2017 8:41:05 PM
TX013.7Z
Monday, November 13, 2017 8:01:33 PM
Monday, November 13, 2017 7:33:20 PM
Friday, November 10, 2017 2:38:20 PM
TX050.7z
Monday, November 13, 2017 8:02:17 PM
Monday, November 13, 2017 9:46:19 AM
Tuesday, October 31, 2017 7:46:01 AM

Help would be greatly appreciated!!

I ran the code that Stephen suggested. I am still getting multiple values for LastWriteTime for many of my files.

This is the resultant output on 11/24/17 at 8:57 AM, when all files show a timestamp in a dir of approximately 8:46 AM or so.

PS C:\Windows\system32> $Store = “ALI”, “COR”, “ELD”, “GRY”, “HML”, “JB”, “SWN”, “LBT”, “LGC”, “MAU”, “MID”, “MPW”, “RKE”, “SPC”, “SSP”, “TWL”, “WRD”
foreach ($element in $Store)
{
    $FPath = "E:\ServerFolders\SData\$element\$element-Cmp"
    $FPath = $FPath.Replace("-", "_")
    #this if statement does not return a true / false value
    #PowerShell is using whether an object is returned by Get-ChildItem
    # or not to try and determine a boolean value
    if(Get-Childitem $FPath  | Where-Object {$_.LastWriteTime -lt (get-date).addHours(-2) })
{
#at this point all we know is that some file exists with a write time
#of more than 2 hours but it could be any file

#You then get the name but only of all *.7z files in the path
#but there's no guarantee that this is the file you need
$FName = Get-ChildItem $FPath -name -Filter "*.7Z"

#This line gets the lastwritetime for all files in the folder
#regardless of the lastwritetime of the file
$FTime = (Get-ChildItem $FPath).LastWriteTime

$FName
$FTime
}}
TX025.7Z

Thursday, November 23, 2017 11:04:20 AM
Friday, November 24, 2017 8:46:54 AM
TX029.7Z
Wednesday, September 13, 2017 11:44:54 AM
Thursday, November 23, 2017 11:01:26 AM
Friday, November 24, 2017 8:45:45 AM
TX049.7Z
Thursday, November 23, 2017 11:03:18 AM
Wednesday, November 22, 2017 5:46:02 PM
GA007.7Z
Thursday, November 23, 2017 7:45:38 PM
Thursday, November 23, 2017 11:02:20 AM
GA004.7Z
Friday, November 24, 2017 8:47:01 AM
Thursday, November 23, 2017 11:30:53 AM
GA003.7Z
Friday, November 24, 2017 8:47:10 AM
Thursday, November 23, 2017 10:30:48 AM
MO001.7Z
Thursday, November 23, 2017 11:04:45 AM
Thursday, November 23, 2017 7:47:08 PM
TX059.7Z
Tuesday, August 22, 2017 7:56:18 PM
Thursday, November 23, 2017 11:03:48 AM
Friday, November 24, 2017 8:41:02 AM
AR001.7Z
Thursday, November 23, 2017 7:46:02 PM
Thursday, November 23, 2017 11:05:08 AM
TX013.7Z
Thursday, November 23, 2017 11:01:25 AM
Friday, November 24, 2017 8:34:11 AM
TX050.7z
Thursday, November 23, 2017 11:02:03 AM
Friday, November 24, 2017 8:46:19 AM
TX024.7Z
Thursday, November 23, 2017 11:03:48 AM
Thursday, November 23, 2017 8:40:36 PM
GA010.7Z
Friday, November 24, 2017 8:45:24 AM
Thursday, November 23, 2017 11:02:39 AM
TX002.7Z
Thursday, November 23, 2017 11:02:03 AM
Friday, November 24, 2017 8:43:45 AM
TX035.7Z
Thursday, November 23, 2017 11:03:17 AM
Friday, November 24, 2017 8:51:39 AM

PS C:\Windows\system32>

Body:
You are overly complicating the process. You can simply add a select-object to grab the 2 properties you want.

$Store = “ALI”, “COR”, “ELD”, “GRY”, “HML”, “JB”, “SWN”, “LBT”, “LGC”, “MAU”, “MID”, “MPW”, “RKE”, “SPC”, “SSP”, “TWL”, “WRD”
foreach ($element in $Store)
{
    $FPath = "E:\ServerFolders\SData\$element\$element-Cmp"
    $FPath = $FPath.Replace("-", "_")
    #Filter for *.7z, with a lastwritetime older than 2 hours
    #Grab only the name and lastwritetime
    Get-Childitem $FPath -Filter "*.7z" |
        Where-Object {$_.LastWriteTime -lt (get-date).addHours(-2) } |
        Select-Object Name, LastWriteTime
}

EDIT: Explaining the logic of the original process

$Store = “ALI”, “COR”, “ELD”, “GRY”, “HML”, “JB”, “SWN”, “LBT”, “LGC”, “MAU”, “MID”, “MPW”, “RKE”, “SPC”, “SSP”, “TWL”, “WRD”
foreach ($element in $Store)
{
    $FPath = "E:\ServerFolders\SData\$element\$element-Cmp"
    $FPath = $FPath.Replace("-", "_")
    #this if statement does not return a true / false value
    #PowerShell is using whether an object is returned by Get-ChildItem
    # or not to try and determine a boolean value
    if(Get-Childitem $FPath  | Where-Object {$_.LastWriteTime -lt (get-date).addHours(-2) })
{
#at this point all we know is that some file exists with a write time
#of more than 2 hours but it could be any file

#You then get the name but only of all *.7z files in the path
#but there's no guarantee that this is the file you need
$FName = Get-ChildItem $FPath -name -Filter "*.7Z"

#This line gets the lastwritetime for all files in the folder
#regardless of the lastwritetime of the file
$FTime = (Get-ChildItem $FPath).LastWriteTime

$FName
$FTime
}}

Without seeing the original file structure its hard to tell exactly what you are working with but the above should explain why you are getting multiple lastwritetime values in your script.


问:
Apply different class to table tr based on image title
```<code><table id='xhtmlgrid'>
<tbody>
<tr class='bgwhite'>
<td>
<table>
<tbody>
<tr>
<td>
<span>
<img src="./secured_off1.png">
</span>
</td>
<td>
<span>
<img src="./secured_off2.png">
</span>
</td>
<td>
<span>
<img src="./secured_off3.png" title="Locked">
</span>
</td>
<td>
<span>
<img src="./secured_off4.png">
</span>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</code>```

i have code like this,based on image title,i have multiple images in that tr, i want to change the tr class from bgwhite to bggreen,how can i do that,any help appreciated.

so far i'm using this code to find the image title

```<code>$("#xhtml_grid table > tbody > tr").each(function () {
        var hdnLock = $(this).find('td:eq(2)').find('img').attr('title');
        if (hdnLock == 'Locked') {
        }

    });
</code>```

for reference i'm adding the image of html

答:
Instead of traversing through each tr, traverse through each img, that would improve the performance and reduce the unnecessary traversing. Below is the updated code:

$("#xhtmlgrid table > tbody > tr > td > img").each(function() {
  if ($(this).attr('title') == 'Locked') {
    $(this).closest('tr').addClass('bggreen').removeClass('bgwhite');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bgwhite {
  background: red;
}

.bggreen {
  background: green;
}</code>```

```

Body:
i have code like this,based on image title,i have multiple images in that tr, i want to change the tr class from bgwhite to bggreen,how can i do that,any help appreciated.

so far i'm using this code to find the image title

$("#xhtml_grid table > tbody > tr").each(function () {
        var hdnLock = $(this).find('td:eq(2)').find('img').attr('title');
        if (hdnLock == 'Locked') {
        }

    });

for reference i'm adding the image of html

Body:
Instead of traversing through each tr, traverse through each img, that would improve the performance and reduce the unnecessary traversing. Below is the updated code:

$("#xhtmlgrid table > tbody > tr > td > img").each(function() {
  if ($(this).attr('title') == 'Locked') {
    $(this).closest('tr').addClass('bggreen').removeClass('bgwhite');
  }
});

.bgwhite {
  background: red;
}

.bggreen {
  background: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='xhtmlgrid'>
  <tbody>
    <tr class='bgwhite'>
      <td>
        <table>
          <tbody>
            <tr>
              <td>
                <img src="./secured_off.png" title="Locked">
              </td>
            </tr>
            <tr>
              <td>
                <img src="./secured_off.png" title="unlocked">
              </td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
  </tbody>
</table>


问:
A bash script to split a data file into many sub-files as per an index file using dd
I have a large data file that contains many joint files.
It has an separate index file has that file name, start + end byte of each file within the data file.
I'm needing help in creating a bash script to split the large file into it's 1000's of sub files.

Data File : fileafilebfilec etc

Index File:

filename.png<0>3049

folder\filename2.png<3049>6136.

I guess this needs to loop through each line of the index file, then using dd to extract the relevant bytes into a file. Maybe a fiddly part might be the folder structure bracket being windows style rather than linux style.

Any help much appreciated.

```<code>while read p; do

  q=${p#*<}
  startbyte=${q%>*}
  endbyte=${q#*>}
  filename=${p%<*}
  count=$(($endbyte - $startbyte))

toprint="processing $filename startbyte: $startbyte endbyte: $endbyte count: $c$
echo $toprint

done <indexfile
</code>```

答:
Worked it out :-) FYI:</p>

```<code>while read p; do

#sort out variables
  q=${p#*<}
  startbyte=${q%>*}
  endbyte=${q#*>}
  filename=${p%<*}
  count=$(($endbyte - $startbyte))

#let it know we're working
toprint="processing $filename startbyte: $startbyte endbyte: $endbyte count: $c$
echo $toprint

if [[ $filename == *"/"* ]]; then
  echo "have found /"

directory=${filename%/*}

#if no directory exists, create it
if [ ! -d "$directory" ]; then
  # Control will enter here if $directory doesn't exist.
echo "directory not found - creating one"
mkdir ~/etg/$directory
fi

fi

dd skip=$startbyte count=$count if=~/etg/largefile of=~/etg/$filename bs=1

done <indexfile
</code>```

Body:
I have a large data file that contains many joint files.
It has an separate index file has that file name, start + end byte of each file within the data file.
I'm needing help in creating a bash script to split the large file into it's 1000's of sub files.

Data File : fileafilebfilec etc

Index File:

filename.png<0>3049

folder\filename2.png<3049>6136.

I guess this needs to loop through each line of the index file, then using dd to extract the relevant bytes into a file. Maybe a fiddly part might be the folder structure bracket being windows style rather than linux style.

Any help much appreciated.

while read p; do

  q=${p#*<}
  startbyte=${q%>*}
  endbyte=${q#*>}
  filename=${p%<*}
  count=$(($endbyte - $startbyte))

toprint="processing $filename startbyte: $startbyte endbyte: $endbyte count: $c$
echo $toprint

done <indexfile

Body:
Worked it out :-) FYI:

while read p; do

#sort out variables
  q=${p#*<}
  startbyte=${q%>*}
  endbyte=${q#*>}
  filename=${p%<*}
  count=$(($endbyte - $startbyte))

#let it know we're working
toprint="processing $filename startbyte: $startbyte endbyte: $endbyte count: $c$
echo $toprint

if [[ $filename == *"/"* ]]; then
  echo "have found /"

directory=${filename%/*}

#if no directory exists, create it
if [ ! -d "$directory" ]; then
  # Control will enter here if $directory doesn't exist.
echo "directory not found - creating one"
mkdir ~/etg/$directory
fi

fi

dd skip=$startbyte count=$count if=~/etg/largefile of=~/etg/$filename bs=1

done <indexfile


问:
How can I pause a C# Console application (only when being run by a user)
How can I pause a C# console application only while being run by a user?

I've searched similar issues on stack overflow which recommend learning to debug properly, using readline, etc, but none of them cover the instance where your process might be being run by an automated system that needs to continue straight past (i.e. not pause, to let user read screen).

How can I determine whether the console is being run interactively or by a script?

If this were bash on a linux system, I could do something like

https://www.gnu.org/software/bash/manual/html_node/Is-this-Shell-Interactive_003f.html

答:
You need to check if someone is logged in as the interactive user, but this is mostly for usage with services. Some "automated" systems since you mention such a term may be faking a logged-in user.

There are some suggestions available at:
Check if no user is currently logged on to Windows

Probably the easiest way (especially if you don't want to rely on WMI API) is to enumerate user sessions via P/Invoke call, as shown here: http://www.pinvoke.net/default.aspx/wtsapi32/WTSEnumerateSessions.html


问:
Java ArrayList - Check if list is empty
How can I check if a list is empty? If so, the system has to give a message saying List is empty. If not, the system has to give a message saying List is not empty.
Users can enter numbers, -1 to stop the program.
This is the code I now have, but this doesn't work, it always says 'List isn't empty'.

```<code>import java.util.*;
import javax.swing.JOptionPane;

public class ArrayListEmpty
{
    public static void main(String[] args)
    {
        List<Integer> numbers = new ArrayList<Integer>();
        int number;
        do {
            number = Integer.parseInt(JOptionPane.showInputDialog("Enter a number (-1 to stop)"));
            numbers.add(number);
        } while (number != -1);
        giveList(numbers);
    }

    public static void giveList(List<Integer> numbers)
    {
        if (numbers != null)
            JOptionPane.showMessageDialog(null, "List isn't empty");
        else
            JOptionPane.showMessageDialog(null, "List is empty!");
    }
}
</code>```

答:
Alternatively, you may also want to check by the .size() method. The list that isn't empty will have a size more than zero</p>

```<code>if (numbers.size()>0){
//execute your code
}
</code>```

Title: Java ArrayList - Check if list is empty

Body:
How can I check if a list is empty? If so, the system has to give a message saying List is empty. If not, the system has to give a message saying List is not empty.
Users can enter numbers, -1 to stop the program.
This is the code I now have, but this doesn't work, it always says 'List isn't empty'.

import java.util.*;
import javax.swing.JOptionPane;

public class ArrayListEmpty
{
    public static void main(String[] args)
    {
        List<Integer> numbers = new ArrayList<Integer>();
        int number;
        do {
            number = Integer.parseInt(JOptionPane.showInputDialog("Enter a number (-1 to stop)"));
            numbers.add(number);
        } while (number != -1);
        giveList(numbers);
    }

    public static void giveList(List<Integer> numbers)
    {
        if (numbers != null)
            JOptionPane.showMessageDialog(null, "List isn't empty");
        else
            JOptionPane.showMessageDialog(null, "List is empty!");
    }
}

Body:
Alternatively, you may also want to check by the .size() method. The list that isn't empty will have a size more than zero

if (numbers.size()>0){
//execute your code
}


问:
Adding TensorFlow to my path
I did a clean install of my Anaconda because of some issues with pyQt. However, after installing tensorflow using the directions on their website here. I need to consistently activate the environment tensorflow before using it. Otherwise the module is not found.

How can I add a path to this installation such that I can continue to use the root environment but also import TensorFlow. How can I correctly deal with versioning with different environments, this seems like a real headache. I would like to just have 1 environment such that I can manage my libraries easily through conda.

If using the tensorflow environment is the same and it will keep track of versioning. How can I make this my default environment.

I feel as though this can be done with PYTHON_PATH with a regular python installation. However, anaconda does not create a PYTHON_PATH. All the existing questions and answers are either for older versions of python or tensorflow. For example, my tensorflow environment does not have a folder named lib. But, there is Lib, Library and libs. How can I add the correct folder to my path such that I can easily use tensorflow with my root environment?

Details:

```<code>C:\Users\eee>conda env list
# conda environments:
#
tensorflow               C:\Users\eee\Anaconda3\envs\tensorflow
root                  *  C:\Users\eee\Anaconda3
</code>```

And,

```<code>C:\Users\eee>python
Python 3.6.3 |Anaconda custom (64-bit)| (default,
Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)] on win32 Type
"help", "copyright", "credits" or "license" for more information.
</code>```

答:
What is your real problem? You want to use tensorflow under root environment? So why don't just install tensorflow under root environment?

You can install the latest version by just pip install tensorflow or pip install tensorflow-gpu to install a gpu version.

Further, the link you provide is points to a very old version, why don't you use latest one?

Title: Adding TensorFlow to my path

Body:
I did a clean install of my Anaconda because of some issues with pyQt. However, after installing tensorflow using the directions on their website here. I need to consistently activate the environment tensorflow before using it. Otherwise the module is not found.

How can I add a path to this installation such that I can continue to use the root environment but also import TensorFlow. How can I correctly deal with versioning with different environments, this seems like a real headache. I would like to just have 1 environment such that I can manage my libraries easily through conda.

If using the tensorflow environment is the same and it will keep track of versioning. How can I make this my default environment.

I feel as though this can be done with PYTHON_PATH with a regular python installation. However, anaconda does not create a PYTHON_PATH. All the existing questions and answers are either for older versions of python or tensorflow. For example, my tensorflow environment does not have a folder named lib. But, there is Lib, Library and libs. How can I add the correct folder to my path such that I can easily use tensorflow with my root environment?

Details:

C:\Users\eee>conda env list
# conda environments:
#
tensorflow               C:\Users\eee\Anaconda3\envs\tensorflow
root                  *  C:\Users\eee\Anaconda3

And,

C:\Users\eee>python
Python 3.6.3 |Anaconda custom (64-bit)| (default,
Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)] on win32 Type
"help", "copyright", "credits" or "license" for more information.