问:
Python Login Page
Hi I am trying to make a login page for a movie streaming website can anyone help me improve this code please

I need it to save the password and username and when it has done that i need that username to be invalid to anyone who trys to use it again to make an account

```<code>username = input("Please enter your username : ")
password = input("Please enter your password : ")
print ("Greetings," , username, "Please re enter your password to confirm
it")
command = input("Please type a command :")
if command == "log off":
print("You have now been logged off again",username)
username == ""
password == ""

username = input("Please enter your username : ")
password = input("Please enter your password : ")

while username != "username" and password != "password":

    print (" Sorry username and password incorrect please re-enter for
validation ")
    username = input("Please enter your username : ")
    password = input("Please enter your password : ")

else:
print ("Greetings," , username, "you are now logged in now with your new
password")

username = input("Please enter your username : ")
password = input("Please enter your password : ")
print ("Greetings," , username, "Please re enter your password to confirm
it")
command = input("Please type a command :")
if command == "log off":
print("You have now been logged off again",username)
username == ""
password == ""

file = open("testfile.txt","w")

file.write("Usernames and Passwords")
file.write(("Username :") username + ("Password :") password)

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

答:
I kind of made an elaborate program, I hope you can appreciate the time I spend on it. I think this questions was better asked on codereview since it does not ask about a specific bug but rather how to improve your code in general.

First of all I made some functions for reusability. That way the code becomes more readable and makes more sense in a whole. Secondly I added new_user() functionality. May I remind you SO is not a codewriting service, you should count yourself lucky I had nothing better to do

```<code>def log_in():
    username = input("Please enter your username : ")
    password = input("Please enter your password : ")

    with open('test_file.txt', 'r') as file:
        for line in file:
            if line == 'Username:{0}, Password:{1}'.format(username, password):
                print ("Greetings," , username, "you are now logged in")
                return True, username, password
    print (" Sorry username and password incorrect please re-enter for validation ")
    return False, '', ''

def new_user():
    succes = False
    while not succes:
        new_user = input("Please enter your new username : ")
        new_pass = input("Please enter your new password : ")

        exists = False
        with open("test_file.txt","r") as file:
            for line in file:
                if line.split(',')[0] == 'Username:'+new_user:
                    print ('Invalid username: {0} already exsist'.format(new_user))
                    exists = True

        if not exists:
            with open("test_file.txt","a") as file:
                file.write('Username:{0}, Password:{1}'.format(new_user, new_pass))
            succes = True
    print ('You made a new user with username:{0} and password:{1}'.format(new_user, new_pass))

def main():
    command = username = password = ''
    logged_in = False
    while command != 'quit':
        command = input('Please type a command: ')
        if command == 'log in':
            logged_in, username, passowrd = log_in()
        if command == 'log out':
            logged_in = False
            username = passowrd = ''
        if command == 'new user':
            if not logged_in:
                new_user()
            else:
                print ('First logout to make a new user')

main()
</code>```

Title: Python Login Page

Body:
Hi I am trying to make a login page for a movie streaming website can anyone help me improve this code please

I need it to save the password and username and when it has done that i need that username to be invalid to anyone who trys to use it again to make an account

username = input("Please enter your username : ")
password = input("Please enter your password : ")
print ("Greetings," , username, "Please re enter your password to confirm
it")
command = input("Please type a command :")
if command == "log off":
print("You have now been logged off again",username)
username == ""
password == ""

username = input("Please enter your username : ")
password = input("Please enter your password : ")

while username != "username" and password != "password":

    print (" Sorry username and password incorrect please re-enter for
validation ")
    username = input("Please enter your username : ")
    password = input("Please enter your password : ")

else:
print ("Greetings," , username, "you are now logged in now with your new
password")

username = input("Please enter your username : ")
password = input("Please enter your password : ")
print ("Greetings," , username, "Please re enter your password to confirm
it")
command = input("Please type a command :")
if command == "log off":
print("You have now been logged off again",username)
username == ""
password == ""

file = open("testfile.txt","w")

file.write("Usernames and Passwords")
file.write(("Username :") username + ("Password :") password)

file.close()

Body:
I kind of made an elaborate program, I hope you can appreciate the time I spend on it. I think this questions was better asked on codereview since it does not ask about a specific bug but rather how to improve your code in general.

First of all I made some functions for reusability. That way the code becomes more readable and makes more sense in a whole. Secondly I added new_user() functionality. May I remind you SO is not a codewriting service, you should count yourself lucky I had nothing better to do

def log_in():
    username = input("Please enter your username : ")
    password = input("Please enter your password : ")

    with open('test_file.txt', 'r') as file:
        for line in file:
            if line == 'Username:{0}, Password:{1}'.format(username, password):
                print ("Greetings," , username, "you are now logged in")
                return True, username, password
    print (" Sorry username and password incorrect please re-enter for validation ")
    return False, '', ''

def new_user():
    succes = False
    while not succes:
        new_user = input("Please enter your new username : ")
        new_pass = input("Please enter your new password : ")

        exists = False
        with open("test_file.txt","r") as file:
            for line in file:
                if line.split(',')[0] == 'Username:'+new_user:
                    print ('Invalid username: {0} already exsist'.format(new_user))
                    exists = True

        if not exists:
            with open("test_file.txt","a") as file:
                file.write('Username:{0}, Password:{1}'.format(new_user, new_pass))
            succes = True
    print ('You made a new user with username:{0} and password:{1}'.format(new_user, new_pass))

def main():
    command = username = password = ''
    logged_in = False
    while command != 'quit':
        command = input('Please type a command: ')
        if command == 'log in':
            logged_in, username, passowrd = log_in()
        if command == 'log out':
            logged_in = False
            username = passowrd = ''
        if command == 'new user':
            if not logged_in:
                new_user()
            else:
                print ('First logout to make a new user')

main()


来源: stackexchange

问:
Bootstrap Form border gradient
By default, clicking on a Bootsrap Form will display a gradient of color on the borders.

Is there a way to modify the bootsrap.css or bootsrap.js to display an other color for the gradient?

Here is a Fiddle with the example on the picture above: https://jsfiddle.net/bb61c412/122/

And the code:

#form-default {
  margin-top: 50px;
  width: 300px;
}
#form-green {
  border: 1px solid #000000;
  margin-top: 50px;
  width: 300px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" type="text/css" href="https://bootswatch.com/bower_components/bootstrap/dist/css/bootstrap.min.css" />

<div class="form-group">

  <select id=form-default name="Form1" class="form-control">
    <option value="0">Form1</option>
    <option value="1">Option2</option>
    <option value="2">Option3</option>
  </select>

  <select id=form-green name="Form2" class="form-control">
    <option value="0">Form2</option>
    <option value="1">Option2</option>
    <option value="2">Option3</option>
  </select>

</div>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script></code>```

答:
```<code> .form-control
  {
   border-color: rgba(126, 239, 104, 0.8) !important;
   box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset, 0 0 8px rgba(126, 239, 104, 0.6) !important;
   outline: 0 none !important;
  }
 .form-control:hover
  {
     border-color: blue !important;
  }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Bootstrap Form border gradient

Body:
By default, clicking on a Bootsrap Form will display a gradient of color on the borders.

Is there a way to modify the bootsrap.css or bootsrap.js to display an other color for the gradient?

Here is a Fiddle with the example on the picture above: https://jsfiddle.net/bb61c412/122/

And the code:

#form-default {
  margin-top: 50px;
  width: 300px;
}
#form-green {
  border: 1px solid #000000;
  margin-top: 50px;
  width: 300px;
}

<link rel="stylesheet" type="text/css" href="https://bootswatch.com/bower_components/bootstrap/dist/css/bootstrap.min.css" />

  <select id=form-default name="Form1" class="form-control">
    <option value="0">Form1</option>
    <option value="1">Option2</option>
    <option value="2">Option3</option>
  </select>

  <select id=form-green name="Form2" class="form-control">
    <option value="0">Form2</option>
    <option value="1">Option2</option>
    <option value="2">Option3</option>
  </select>

ContentLicense: CC BY-SA 3.0


问:
apache server is confusing with HTTPService responses
This is a very weird problem.
I have an apache server on solaris with php.
I wrote two php scripts that return values.
Sometimes, when I run the php scripts urls on the same time, the apache server returns the result of one php script to the other php page.

I tried to minimize the problem by write two php script:

hello.php - print hello

world.php - print world

sometimes when i run them on the same time by url, the hello.php return world.

when i'm using html pages it's working just fine so i think the problem is in the php installed on the server.

I'm a flex developer and I thought that the problem is in my flex client application but after I just run the php scripts directly, I see that the problem is in the server itself.

somebody know this problem?
thank you very much.

答:
I am perhaps not answering your question but what if you instead of making your scripts return hello in one and world in the other instead output something a bit less static like the date and time.

```<code>script1.php
echo "Script1:".date("Y-m-d H:i:s")."<br>";

script2.php
echo "Script2:".date("Y-m-d H:i:s")."<br>";
</code>```

That way you will know if this is caused by some caching.

ContentLicense: CC BY-SA 2.5

Body:
I am perhaps not answering your question but what if you instead of making your scripts return hello in one and world in the other instead output something a bit less static like the date and time.

script1.php
echo "Script1:".date("Y-m-d H:i:s")."<br>";

script2.php
echo "Script2:".date("Y-m-d H:i:s")."<br>";

That way you will know if this is caused by some caching.


问:
create url for file in my file system , web service
my file system

I tried to show these csv file as url but I failed

how I can get url for file in my file system?

```<code> public DownloadFileResponse downloadFile(DownloadFileRequest req) {

      //TODO: create and set ImportMarketResponse object and return the following as response data
      // "EventSet Id: " + req.eventSetId;

        String txt ="EventSet Id: " + req.eventSetId;
        DownloadFileResponse res = new DownloadFileResponse();
        res.setReturnDate(txt);

        return res;

    }
</code>```

答:
Get url for file:

Java 7+

```<code>Paths.get("path","to","file").toUri().toURL()
</code>```

Older Versions

```<code>new File(path).toURI().toURL();
</code>```

Body:
my file system

I tried to show these csv file as url but I failed

how I can get url for file in my file system?

 public DownloadFileResponse downloadFile(DownloadFileRequest req) {

      //TODO: create and set ImportMarketResponse object and return the following as response data
      // "EventSet Id: " + req.eventSetId;

        String txt ="EventSet Id: " + req.eventSetId;
        DownloadFileResponse res = new DownloadFileResponse();
        res.setReturnDate(txt);

        return res;

    }

Body:
Get url for file:

Java 7+

Paths.get("path","to","file").toUri().toURL()

Older Versions

new File(path).toURI().toURL();


问:
Limit this PHP foreach statement to just 5 loops
How could I limit this foraech statement to just 5 loops? I think I should just use Break but I'm not sure where to put it. </p>

```<code> <?php if(!empty($locations)): foreach($locations as $location):  ?>
<?php if(empty($location["title"])) continue; ?>
<li>
    <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
        <?php esc_html_e($location["title"]) ?>
    </a>
    <?php if($param->count): ?>
    <div class="wpjb-widget-item-count">
        <div class="wpjb-widget-item-num"><?php echo intval($location["count"]) ?></div>
    </div>
    <?php endif; ?>
</li>
<?php endforeach; ?>
</code>```

答:
Using a counter variable into your loop you can control/limit to any number.

Example:

```<code>$counter = 0;
foreach($locations as $location):
    if($counter++ == 5):
        break;
    // Your other content goes here
    endif;
endforeach;
</code>```

Body:
How could I limit this foraech statement to just 5 loops? I think I should just use Break but I'm not sure where to put it.

 <?php if(!empty($locations)): foreach($locations as $location):  ?>
<?php if(empty($location["title"])) continue; ?>

    <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
        <?php esc_html_e($location["title"]) ?>

    <?php if($param->count): ?>

<?php echo intval($location["count"]) ?>

    <?php endif; ?>

<?php endforeach; ?>

Body:
Using a counter variable into your loop you can control/limit to any number.

Example:

$counter = 0;
foreach($locations as $location):
    if($counter++ == 5):
        break;
    // Your other content goes here
    endif;
endforeach;


问:
Entity Framework 6 not saving changes
I've got an MVC5 web application that uses SQL Server 2008 as a back end database along with the Entity Framework 6. There's no error in adding code but data can not get stored in to database.

my model context.cs looks like

```<code>public partial class checkin_checkoutEntities2 : DbContext
    {
        public checkin_checkoutEntities2()
            : base("name=checkin_checkoutEntities2")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Advance_Booking> Advance_Bookings { get; set; }
        public virtual DbSet<employee_reg> employee_reg { get; set; }
        public virtual DbSet<Extend_Stay> Extend_Stay { get; set; }
        public virtual DbSet<Guest_reg> Guest_reg { get; set; }
        public virtual DbSet<RoomBooking> RoomBooking { get; set; }
        public virtual DbSet<Rooms_ms> Rooms_ms { get; set; }
    }
</code>```

and my adding method is as below

```<code> ab.Room_id = Convert.ToInt32(ab_rm_no.room_id);
 ab.Guest_id = Convert.ToInt32(frm["guest_id"].ToString());
 ab.Expected_checkin  = Convert.ToDateTime(frm["BookedDateFR"].ToString());
 ab.Expected_checkout = Convert.ToDateTime(frm["BookedDateTO"].ToString());

 db.Advance_Bookings.Add(ab);
 db.SaveChanges();
</code>```

答:
Can you change your code a bit and try following:
Rather using db.Advance_Bookings.Add(ab) can you use following:

```<code>db.Entry(ab).State = EntityState.Added;
</code>```

Also, as far my understanding this problem can only occur if the DbContext is disconnected (as it's not giving any error).
You can try to wrap your code in a using block

```<code>using (var ab = new DbContext())
{
//instantiate the object and saveChanges.
}
</code>```

Title: Entity Framework 6 not saving changes

Body:
I've got an MVC5 web application that uses SQL Server 2008 as a back end database along with the Entity Framework 6. There's no error in adding code but data can not get stored in to database.

my model context.cs looks like

public partial class checkin_checkoutEntities2 : DbContext
    {
        public checkin_checkoutEntities2()
            : base("name=checkin_checkoutEntities2")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Advance_Booking> Advance_Bookings { get; set; }
        public virtual DbSet<employee_reg> employee_reg { get; set; }
        public virtual DbSet<Extend_Stay> Extend_Stay { get; set; }
        public virtual DbSet<Guest_reg> Guest_reg { get; set; }
        public virtual DbSet<RoomBooking> RoomBooking { get; set; }
        public virtual DbSet<Rooms_ms> Rooms_ms { get; set; }
    }

and my adding method is as below

 ab.Room_id = Convert.ToInt32(ab_rm_no.room_id);
 ab.Guest_id = Convert.ToInt32(frm["guest_id"].ToString());
 ab.Expected_checkin  = Convert.ToDateTime(frm["BookedDateFR"].ToString());
 ab.Expected_checkout = Convert.ToDateTime(frm["BookedDateTO"].ToString());

 db.Advance_Bookings.Add(ab);
 db.SaveChanges();

Body:
Can you change your code a bit and try following:
Rather using db.Advance_Bookings.Add(ab) can you use following:

db.Entry(ab).State = EntityState.Added;

Also, as far my understanding this problem can only occur if the DbContext is disconnected (as it's not giving any error).
You can try to wrap your code in a using block

using (var ab = new DbContext())
{
//instantiate the object and saveChanges.
}


问:
IBM RIT - map current dateTime into request
Is there a function to map the current dateTime into a test request message in IBM RIT?

I found the "now" function in the online help but that doesn't work, the provider receives basically the string 'now("2016-10-10")'

If that's possible, I would like also to know which function does a datetimediff.

Thanks for your help

答:
There is an in built function you can use

```<code>tags["SYSTEM/CURRENT_TIME"]
</code>```

and yoiu can use the substring function to split it into whatever you want. for example:

```<code>tt = tags["SYSTEM/CURRENT_TIME"]

tthh = tt.substring(0,2) ******************this returns hour of the day

ttmm = tt.substring(3,5) ******************this returns minutes

ttss = tt.substring(6,8) ******************this returns seconds

ttNew = tthh+ttmm+ttss
</code>```

You can also do the same for the date using the inbuilt function

```<code>tt = tags["SYSTEM/CURRENT_DATE"]
</code>```

Body:
There is an in built function you can use

tags["SYSTEM/CURRENT_TIME"]

and yoiu can use the substring function to split it into whatever you want. for example:

tt = tags["SYSTEM/CURRENT_TIME"]

tthh = tt.substring(0,2) ******************this returns hour of the day

ttmm = tt.substring(3,5) ******************this returns minutes

ttss = tt.substring(6,8) ******************this returns seconds

ttNew = tthh+ttmm+ttss

You can also do the same for the date using the inbuilt function

tt = tags["SYSTEM/CURRENT_DATE"]


问:
Mosquitto MQTT devices slowing down
I have a problem with 2 esp8266 , both are wired up with ds18b28 via onewire and send data with MQTT .But , if i turn them on both , just one of them transmits data , i tested them separate and no problem , here is the code.Both esp-s use the same code</p>

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

#include <PubSubClient.h>

#include <OneWire.h>

#include <DallasTemperature.h>
#define ONE_WIRE_BUS 5
OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);

const char* ssid = "PIREV-PC_NETWORK";
const char* password = "********";
const char* mqtt_server = "192.168.0.4";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
float temp = 0;
int inPin = 5;

void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED)
{
 delay(500);
 Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("arduinoClient_temperature_sensor")) {
   Serial.println("connected");
} else {
   Serial.print("failed, rc=");
   Serial.print(client.state());
   Serial.println(" try again in 5 seconds");
   delay(5000);
  }
 }
}

void setup()
{
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
pinMode(inPin, INPUT);
sensors.begin();
}

void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();

long now = millis();
if (now - lastMsg > 300) {
 lastMsg = now;
 sensors.setResolution(12);
 sensors.requestTemperatures();
 temp = sensors.getTempCByIndex(0);
 Serial.println(temp);
 if((temp > -20) && (temp <60))
   {
   client.publish("dev/test/temp2", String(temp).c_str(),TRUE);
   }
  }
 }
</code>```

答:
The client id needs to be different for every client.

In this case it looks like you are using arduinoClient_temperature_sensor for both sensors, this won't work as the broker will always disconnect the first sensor when the second one connects (and then vice versa when that sensor tries to reconnect)

```<code>void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // The value passed to client.connect needs to be unique
    if (client.connect("arduinoClient_temperature_sensor")) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}
</code>```

Title: Mosquitto MQTT devices slowing down

Body:
I have a problem with 2 esp8266 , both are wired up with ds18b28 via onewire and send data with MQTT .But , if i turn them on both , just one of them transmits data , i tested them separate and no problem , here is the code.Both esp-s use the same code

#include <ESP8266WiFi.h>

#include <PubSubClient.h>

#include <OneWire.h>

#include <DallasTemperature.h>
#define ONE_WIRE_BUS 5
OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);

const char* ssid = "PIREV-PC_NETWORK";
const char* password = "********";
const char* mqtt_server = "192.168.0.4";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
float temp = 0;
int inPin = 5;

void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED)
{
 delay(500);
 Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("arduinoClient_temperature_sensor")) {
   Serial.println("connected");
} else {
   Serial.print("failed, rc=");
   Serial.print(client.state());
   Serial.println(" try again in 5 seconds");
   delay(5000);
  }
 }
}

void setup()
{
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
pinMode(inPin, INPUT);
sensors.begin();
}

void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();

long now = millis();
if (now - lastMsg > 300) {
 lastMsg = now;
 sensors.setResolution(12);
 sensors.requestTemperatures();
 temp = sensors.getTempCByIndex(0);
 Serial.println(temp);
 if((temp > -20) && (temp <60))
   {
   client.publish("dev/test/temp2", String(temp).c_str(),TRUE);
   }
  }
 }

Body:
The client id needs to be different for every client.

In this case it looks like you are using arduinoClient_temperature_sensor for both sensors, this won't work as the broker will always disconnect the first sensor when the second one connects (and then vice versa when that sensor tries to reconnect)

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // The value passed to client.connect needs to be unique
    if (client.connect("arduinoClient_temperature_sensor")) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}


问:
Pyparsing: How can I parse data and then edit a specific value in a .txt file?
my data is located in a .txt file (no, I can't change it to a different format) and it looks like this:

varaiablename = value

something = thisvalue

youget = the_idea

Here is my code so far (taken from the examples in Pyparsing):

```<code>from pyparsing import Word, alphas, alphanums, Literal, restOfLine, OneOrMore, \
empty, Suppress, replaceWith

input = open("text.txt", "r")
src = input.read()

# simple grammar to match #define's
ident = Word(alphas + alphanums + "_")
macroDef = ident.setResultsName("name") + "= " + ident.setResultsName("value") + Literal("#") + restOfLine.setResultsName("desc")
for t,s,e in macroDef.scanString(src):
print t.name,"=", t.value
</code>```

So how can I tell my script to edit a specific value for a specific variable?

Example:

I want to change the value of variablename, from value to new_value.
So essentially variable = (the data we want to edit).

I probably should make it clear that I don't want to go directly into the file and change the value by changing value to new_value but I want to parse the data, find the variable and then give it a new value.

答:
For this task you do not need to use special utility or module
What you need is reading lines and spliting them in list, so first index is left and second index is right side.
If you need these values later you might want to store them in dictionary.

Well here is simple way, for somebody new in python. Uncomment lines whit print to use it as debug.

```<code>f=open("conf.txt","r")
txt=f.read() #all text is in txt
f.close()

fwrite=open("modified.txt","w")
splitedlines = txt.splitlines():
#print splitedlines
for line in splitedlines:
    #print line
    conf = line.split('=')
    #conf[0] is what it is on left and conf[1] is what it is on right
    #print conf
    if conf[0] == "youget":
        #we get this
        conf[1] = "the_super_idea" #the_idea is now the_super_idea
    #join conf whit '=' and write
    newline = '='.join(conf)
    #print newline
    fwrite.write(newline+"\n")

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

Body:
my data is located in a .txt file (no, I can't change it to a different format) and it looks like this:

varaiablename = value

something = thisvalue

youget = the_idea

Here is my code so far (taken from the examples in Pyparsing):

from pyparsing import Word, alphas, alphanums, Literal, restOfLine, OneOrMore, \
empty, Suppress, replaceWith

input = open("text.txt", "r")
src = input.read()

# simple grammar to match #define's
ident = Word(alphas + alphanums + "_")
macroDef = ident.setResultsName("name") + "= " + ident.setResultsName("value") + Literal("#") + restOfLine.setResultsName("desc")
for t,s,e in macroDef.scanString(src):
print t.name,"=", t.value

So how can I tell my script to edit a specific value for a specific variable?

Example:

I want to change the value of variablename, from value to new_value.
So essentially variable = (the data we want to edit).

I probably should make it clear that I don't want to go directly into the file and change the value by changing value to new_value but I want to parse the data, find the variable and then give it a new value.

Body:
For this task you do not need to use special utility or module
What you need is reading lines and spliting them in list, so first index is left and second index is right side.
If you need these values later you might want to store them in dictionary.

Well here is simple way, for somebody new in python. Uncomment lines whit print to use it as debug.

f=open("conf.txt","r")
txt=f.read() #all text is in txt
f.close()

fwrite=open("modified.txt","w")
splitedlines = txt.splitlines():
#print splitedlines
for line in splitedlines:
    #print line
    conf = line.split('=')
    #conf[0] is what it is on left and conf[1] is what it is on right
    #print conf
    if conf[0] == "youget":
        #we get this
        conf[1] = "the_super_idea" #the_idea is now the_super_idea
    #join conf whit '=' and write
    newline = '='.join(conf)
    #print newline
    fwrite.write(newline+"\n")

fwrite.close()


问:
Why is my process taking higher resident memory as compared to virtual memory?
'top' logs of my linux process show that its resident memory is around 6 times of the virtual memory. I have researched a lot but couldn't find any reason for such a behavior. Ideally VIRT is always higher than RES due to linux kernel's memory management. Top output is below - </p>

```<code>13743 root 20 0 15.234g 0.010t 4372 R 13.4 4.0 7:43.41 q
</code>```

答:
Not quite.

The g suffix indicates Gibibyte(s), and t indicates Tebibyte(s).

Let's do the conversion of 0.010t to g (GiB):

```<code>zsh% print $((0.010 * 1024))g
10.24g
</code>```

And 10.24g < 15.234g, so yor assumption is not correct i.e. top is correctly showing the correct values for virtual set size (VSZ) and resident set size (RSS) -- just in different units (need to take a peek at the source for why).

Body:
'top' logs of my linux process show that its resident memory is around 6 times of the virtual memory. I have researched a lot but couldn't find any reason for such a behavior. Ideally VIRT is always higher than RES due to linux kernel's memory management. Top output is below -

13743 root 20 0 15.234g 0.010t 4372 R 13.4 4.0 7:43.41 q

Body:
Not quite.

The g suffix indicates Gibibyte(s), and t indicates Tebibyte(s).

Let's do the conversion of 0.010t to g (GiB):

zsh% print $((0.010 * 1024))g
10.24g

And 10.24g < 15.234g, so yor assumption is not correct i.e. top is correctly showing the correct values for virtual set size (VSZ) and resident set size (RSS) -- just in different units (need to take a peek at the source for why).


问:
Regex Pattern Matching until the first whitespace before the first series of characters containing a specific character
Consider the following string:

```<code>ab cd ef gh/
</code>```

How would I extract ab cd ef?

I would like to be able to match until the first whitespace before the first series containing a specific character, which in the case above is /.

EDIT: I'm trying to set a config file to parse some logs into Logstash, so I was wondering whether it was possible to do this just with regex rules.

答:
You can try something like that:

function matchInString(str) {
  regex = /(.*) \w*\/\w*/
  m = str.match(regex)
  if (m) {
    console.log(m[1])
  }
}

matchInString("ab cd ef gh/")
matchInString("ab cd ef gh/asdfasdf")
matchInString("ab cd ef gh/asdfasdf a/")
matchInString("ab cd ef gh/asdfasdf a/b")
matchInString("ab cd ef 12341234 /")```

Body:
Consider the following string:

ab cd ef gh/

How would I extract ab cd ef?

I would like to be able to match until the first whitespace before the first series containing a specific character, which in the case above is /.

EDIT: I'm trying to set a config file to parse some logs into Logstash, so I was wondering whether it was possible to do this just with regex rules.


问:
Determine when image finished loading with JavaScript or jQuery:
How can I detect with JavaScript or jQuery when an image has finished loading, be it from the server or the browser cache?
I want to load various images in the same  tag and detect when the loading of a new images has finished.

答:
```<code>$('img').on('load', function() {
    // do whatever you want
});
</code>```


问:
I am working on BIRT reporting
Is that possible to get multiple parameter values based on another parameter value. For example if I select facility id ,then it should populate below region and FQA parameters.</p>

答: I think you want to use cascading parameters. Check out this URL to see if it is close to what you are aiming for... https://www.eclipse.org/forums/index.php/t/503715/</p>

Title: I am working on BIRT reporting


问:
Loops dates Followers for Chart - PHP JSON
I want to build a day-to-day date loop that relies on a JSON file.
The loop should be adjusted to the graph.
The problem that the dates in the JSON file are not necessarily sequential (depending on whether it's a business day or not) I want to view every day (regardless of whether it's a business day or not) which means I want to complete the JSON loop on dates.

For illustration, I will present an example.
in case the json file will show me that

["1982-11-12", 0.4193],["1982-11-20", 0.3672],

i would like to display that into my graph

["1982-11-12", 0.4193],["1982-11-13", 0.4193],["1982-11-14", 0.4193],["1982-11-15", 0.4193],["1982-11-16", 0.4193],["1982-11-17", 0.4193],["1982-11-18", 0.4193],["1982-11-19", 0.4193],["1982-11-20", 0.3672]

In summary, I want the loop to continue to a consecutive date if the date is not. In addition to giving the same value of the previous date. TIA

Json file:

```<code>[
    {   "id":"XXX","dateTimeRanges":{},
        "price":[
                {"date":"1982-11-12", "value":0.5781},
                {"date":"1982-11-19","value":0.5513},
                {"date":"1982-11-26","value":0.5179},
                {"date":"1982-12-03","value":0.567},
                {"date":"1982-12-10","value":0.5223},
                {"date":"1982-12-17","value":0.5379},
                {"date":"1982-12-24","value":0.5714},
                {"date":"1982-12-31","value":0.5335},
                {"date":"1983-01-07","value":0.4911},
                {"date":"1983-01-14","value":0.5893},
                {"date":"1983-01-21","value":0.6674}
                ]}]
</code>```

Php file:

```<code>$json = file_get_contents($url);
//$json = json_encode($json, true);

$json_a = json_decode($json, true);
//print_r($json_a);
$n = count($json_a[0]['price']);
?>
<script type="text/javascript">
window.profileData = {
        "stats": [
<?php
    for($i=0;$i<$n;$i++){
        $date = trim($json_a[0]['price'][$i]['date']);
        $value = trim($json_a[0]['price'][$i]['value']);
        $tomorrow = date("Y-m-d",  strtotime('+1 day', strtotime($date)));

        if($i > 0 and trim($json_a[0]['price'][$i+1]['date']) !== $tomorrow){
?>
    ["<?php echo $tomorrow;?>", <?php echo $value;?>],
    <?php }else{ ?>
    ["<?php echo $date;?>", <?php echo $value;?>],
<?php }}?>],
        "profile": {
                "commonName": "<?php echo trim($name);?>",
                 }
        };
  </script>
</code>```

Body:
I want to build a day-to-day date loop that relies on a JSON file.
The loop should be adjusted to the graph.
The problem that the dates in the JSON file are not necessarily sequential (depending on whether it's a business day or not) I want to view every day (regardless of whether it's a business day or not) which means I want to complete the JSON loop on dates.

For illustration, I will present an example.
in case the json file will show me that

["1982-11-12", 0.4193],["1982-11-20", 0.3672],

i would like to display that into my graph

["1982-11-12", 0.4193],["1982-11-13", 0.4193],["1982-11-14", 0.4193],["1982-11-15", 0.4193],["1982-11-16", 0.4193],["1982-11-17", 0.4193],["1982-11-18", 0.4193],["1982-11-19", 0.4193],["1982-11-20", 0.3672]

In summary, I want the loop to continue to a consecutive date if the date is not. In addition to giving the same value of the previous date. TIA

Json file:

[
    {   "id":"XXX","dateTimeRanges":{},
        "price":[
                {"date":"1982-11-12", "value":0.5781},
                {"date":"1982-11-19","value":0.5513},
                {"date":"1982-11-26","value":0.5179},
                {"date":"1982-12-03","value":0.567},
                {"date":"1982-12-10","value":0.5223},
                {"date":"1982-12-17","value":0.5379},
                {"date":"1982-12-24","value":0.5714},
                {"date":"1982-12-31","value":0.5335},
                {"date":"1983-01-07","value":0.4911},
                {"date":"1983-01-14","value":0.5893},
                {"date":"1983-01-21","value":0.6674}
                ]}]

Php file:

$json = file_get_contents($url);
//$json = json_encode($json, true);

$json_a = json_decode($json, true);
//print_r($json_a);
$n = count($json_a[0]['price']);
?>

Body:
Here's how I would do it:

<?php
$data = json_decode(file_get_contents($url));

$json = []; $prev = null;
foreach ($data[0]->price as $item)
{
    while (isset($prev) && strtotime($item->date) != ($prev=strtotime('+1 day', $prev)))
        $json []= [date('Y-m-d', $prev), $item->value];

    $json []= [$item->date, $item->value];

    $prev = strtotime($item->date);
}
?>

<script type="text/javascript">window.profileData = <?=json_encode($json)?></script>

For this input:

$data = json_decode('[{"id":"XXX","dateTimeRanges":{},"price":[{"date":"1982-11-12","value":0.5781},{"date":"1982-11-19","value":0.5513},{"date":"1982-11-26","value":0.5179},{"date":"1982-12-03","value":0.567},{"date":"1982-12-10","value":0.5223},{"date":"1982-12-17","value":0.5379},{"date":"1982-12-24","value":0.5714},{"date":"1982-12-31","value":0.5335},{"date":"1983-01-07","value":0.4911},{"date":"1983-01-14","value":0.5893},{"date":"1983-01-21","value":0.6674}]}]');

It generates:

  window.profileData = [["1982-11-12",0.5781],["1982-11-13",0.5513],["1982-11-14",0.5513],["1982-11-15",0.5513],["1982-11-16",0.5513],["1982-11-17",0.5513],["1982-11-18",0.5513],["1982-11-19",0.5513],["1982-11-20",0.5179],["1982-11-21",0.5179],["1982-11-22",0.5179],["1982-11-23",0.5179],["1982-11-24",0.5179],["1982-11-25",0.5179],["1982-11-26",0.5179],["1982-11-27",0.567],["1982-11-28",0.567],["1982-11-29",0.567],["1982-11-30",0.567],["1982-12-01",0.567],["1982-12-02",0.567],["1982-12-03",0.567],["1982-12-04",0.5223],["1982-12-05",0.5223],["1982-12-06",0.5223],["1982-12-07",0.5223],["1982-12-08",0.5223],["1982-12-09",0.5223],["1982-12-10",0.5223],["1982-12-11",0.5379],["1982-12-12",0.5379],["1982-12-13",0.5379],["1982-12-14",0.5379],["1982-12-15",0.5379],["1982-12-16",0.5379],["1982-12-17",0.5379],["1982-12-18",0.5714],["1982-12-19",0.5714],["1982-12-20",0.5714],["1982-12-21",0.5714],["1982-12-22",0.5714],["1982-12-23",0.5714],["1982-12-24",0.5714],["1982-12-25",0.5335],["1982-12-26",0.5335],["1982-12-27",0.5335],["1982-12-28",0.5335],["1982-12-29",0.5335],["1982-12-30",0.5335],["1982-12-31",0.5335],["1983-01-01",0.4911],["1983-01-02",0.4911],["1983-01-03",0.4911],["1983-01-04",0.4911],["1983-01-05",0.4911],["1983-01-06",0.4911],["1983-01-07",0.4911],["1983-01-08",0.5893],["1983-01-09",0.5893],["1983-01-10",0.5893],["1983-01-11",0.5893],["1983-01-12",0.5893],["1983-01-13",0.5893],["1983-01-14",0.5893],["1983-01-15",0.6674],["1983-01-16",0.6674],["1983-01-17",0.6674],["1983-01-18",0.6674],["1983-01-19",0.6674],["1983-01-20",0.6674],["1983-01-21",0.6674]]


问:
React native - Change screen after x seconds
I have a problem that I haven't been able to solve.

In my React native application, I would like to display a welcome screen at the start. Then 5 seconds later just close it, and display another one. Both are 2 entirely different screens, no need to keep the "come back" arrow.

I have been searching for hours, but I haven't found out how to do it.

Here is my code for now:

```<code>import Defis from './components/defis'
import Quote from './components/quote'

export default class Betty extends Component {
    componentDidMount(){
        // Start counting when the page is loaded
        this.timeoutHandle = setTimeout(()=>{
            // Add your logic for the transition
            this.props.navigation.navigate('Defis') // what to push here?
        }, 5000);
    }

    componentWillUnmount(){
        clearTimeout(this.timeoutHandle);
    }

    render() {
        return (
            <Quote/>
        );
    }
}
</code>```

Does anybody know how to do it?

I'm not able to use Navigator.push, moreover Navigator seems deprecated.

答:
I have done this to show login screen after the splash screen in react-native as follows:

```<code>import Login from './Login'; // My next screen
....
....
const {navigate} = this.props.navigation;
setTimeout(() => {
    navigate('Login'); //this.props.navigation.navigate('Login')
}, 5000);  //5000 milliseconds
</code>```

I have used react-navigation for the navigation purpose.

Body:
I have a problem that I haven't been able to solve.

In my React native application, I would like to display a welcome screen at the start. Then 5 seconds later just close it, and display another one. Both are 2 entirely different screens, no need to keep the "come back" arrow.

I have been searching for hours, but I haven't found out how to do it.

Here is my code for now:

import Defis from './components/defis'
import Quote from './components/quote'

export default class Betty extends Component {
    componentDidMount(){
        // Start counting when the page is loaded
        this.timeoutHandle = setTimeout(()=>{
            // Add your logic for the transition
            this.props.navigation.navigate('Defis') // what to push here?
        }, 5000);
    }

    componentWillUnmount(){
        clearTimeout(this.timeoutHandle);
    }

    render() {
        return (
            <Quote/>
        );
    }
}

Does anybody know how to do it?

I'm not able to use Navigator.push, moreover Navigator seems deprecated.

Body:
I have done this to show login screen after the splash screen in react-native as follows:

import Login from './Login'; // My next screen
....
....
const {navigate} = this.props.navigation;
setTimeout(() => {
    navigate('Login'); //this.props.navigation.navigate('Login')
}, 5000);  //5000 milliseconds

I have used react-navigation for the navigation purpose.


问:
SQL join with selecting previous matching value with group by
I have 2 tables that I want to join on a key that matches with the first previous record.

I have a query that does this. However I also want to include a column in the results from each of the table. This forces me to include those 2 columns in the Group By attribute which is returning duplicate results.

The query I am using is similar to this (courtesy: stackoverflow):

```<code>SELECT t1.frame as frame1,
    t1.string as string1,
    max(t2.frame) as frame2,
    t2.string as string2
    FROM t1
    JOIN t2
    ON t2.frame < t1.frame and
    t1.key=t2.key
    GROUP BY t1.frame, t2.frame, t1.string, t2.string
    ORDER BY t2.frame
</code>```

The (problem) output I see is:

```<code>frame1, string1, frame2, string2
51      text1     6       text2
107253  text3     6       text2
</code>```

How can I include string2 in my results such that I don't want to group by it but only include its value for corresponding frame2?

I tried setting this up on sqlfiddle.com to make it easy to try. I populated with some dummy data but here along with this problem, I also see another problem which is it is also returning results where frame2=2. This is not expected, since it should always match frame=6. I suppose this may be side effect of grouping by string2?

Link to sqlfiddle example

Here I expect the output should only be 1 record which is:

```<code>frame1,string1,frame2,string2
51      text1    6     text2
</code>```

I am doing this on Spark SQL but this should be a generic SQL question.
Thanks.

Edit:
My data consists of incoming packets and I want to match a packet to the most recent one that came before it which has the matching ID. For e.g.

```<code>Table t2:
    frame#1:Key=a,Text=abc
    frame#2:Key=a,Text=def
    frame#3:Key=b,Text=efg
    frame#5:Key=c,Text=xyz

Table t1:
    frame#4:Key=a,Text=pqr
    frame#6:Key=c,Text=mno
</code>```

So here, for frame#4 from t1, I want to match it with frame from t2 that has come before it and has the same key. So it should match with frame#2 (not frame#3 coz key is different and not frame#1 coz frame#2 is more recent). Similarly, frame#6 should match with frame#5.

Hope it is clear now.

答:
```<code>SELECT A.*, t1.string AS string1, t2.string AS string2
FROM
(SELECT t1.frame AS frame1, MAX(t2.frame) AS frame2
FROM t1
INNER JOIN t2 ON t1.key=t2.key AND t2.frame< t1.frame
GROUP BY t1.frame
) A
INNER JOIN t1 ON A.frame1=t1.frame
INNER JOIN t2 ON A.frame2=t2.frame;
</code>```

Output:

```<code>    frame1  frame2  string1 string2
1   51      6       text13  text17
2   107253  106999  text25  text39
</code>```

Body:
I have 2 tables that I want to join on a key that matches with the first previous record.

I have a query that does this. However I also want to include a column in the results from each of the table. This forces me to include those 2 columns in the Group By attribute which is returning duplicate results.

The query I am using is similar to this (courtesy: stackoverflow):

SELECT t1.frame as frame1,
    t1.string as string1,
    max(t2.frame) as frame2,
    t2.string as string2
    FROM t1
    JOIN t2
    ON t2.frame < t1.frame and
    t1.key=t2.key
    GROUP BY t1.frame, t2.frame, t1.string, t2.string
    ORDER BY t2.frame

The (problem) output I see is:

frame1, string1, frame2, string2
51      text1     6       text2
107253  text3     6       text2

How can I include string2 in my results such that I don't want to group by it but only include its value for corresponding frame2?

I tried setting this up on sqlfiddle.com to make it easy to try. I populated with some dummy data but here along with this problem, I also see another problem which is it is also returning results where frame2=2. This is not expected, since it should always match frame=6. I suppose this may be side effect of grouping by string2?

Link to sqlfiddle example

Here I expect the output should only be 1 record which is:

frame1,string1,frame2,string2
51      text1    6     text2

I am doing this on Spark SQL but this should be a generic SQL question.
Thanks.

Edit:
My data consists of incoming packets and I want to match a packet to the most recent one that came before it which has the matching ID. For e.g.

Table t2:
    frame#1:Key=a,Text=abc
    frame#2:Key=a,Text=def
    frame#3:Key=b,Text=efg
    frame#5:Key=c,Text=xyz

Table t1:
    frame#4:Key=a,Text=pqr
    frame#6:Key=c,Text=mno

So here, for frame#4 from t1, I want to match it with frame from t2 that has come before it and has the same key. So it should match with frame#2 (not frame#3 coz key is different and not frame#1 coz frame#2 is more recent). Similarly, frame#6 should match with frame#5.

Hope it is clear now.

Body:
SELECT A.*, t1.string AS string1, t2.string AS string2
FROM
(SELECT t1.frame AS frame1, MAX(t2.frame) AS frame2
FROM t1
INNER JOIN t2 ON t1.key=t2.key AND t2.frame< t1.frame
GROUP BY t1.frame
) A
INNER JOIN t1 ON A.frame1=t1.frame
INNER JOIN t2 ON A.frame2=t2.frame;

Output:

    frame1  frame2  string1 string2
1   51      6       text13  text17
2   107253  106999  text25  text39


问:
How to fix GNUPLOT replot issue
I set-up a multiplot like this:

```<code>set terminal wxt size 1500,900
set format x "%d%m%y %H:%M:%S"
set xdata time
set timefmt x "%Y%m%dT%H%M%S"
set key font ",6"
set lmargin 10
set rmargin 10
set multiplot layout 2,1
plot "output.txt" u 1:2 w lines axes x1y1, \
"output.txt" u 1:3 w lines axes x1y2
plot "output.txt" u 1:40 w lines axes x1y1, \
"output.txt" u 1:39 w lines axes x1y2
set y2tics border
unset multiplot
</code>```

Which works, and gives me 2 plots, one above the other.

But pressing the "replot" button (or using zoom) causes the second plot to fill the window - completely hiding the first plot.

答:
Here is another workaround. It does not answer the question directly, but it could give idea to other similar issues. Put header, and a footer 'reread', then two context could be choosen for a similar multiplot (done twice)</p>

```<code>if (exists("rehearse")) rehearse=1+rehearse; set term x11
if (!exists("rehearse")) rehearse=0; set term png; set output sprintf("test_palette_%s.png", system("date +\"%F\""))

pr "rehearse=".rehearse; show term #<= comment printing
set samples 100;  set isosample 100,100
set xrange [0:1]; set yrange [0:1]
set palette defined (0 "white", 1 "red")
set autoscale cbfix; unset colorbox; unset key

set multiplot layout 2,2
plot '++' using 1:2:1 with image
plot '++' using 1:2:2 with image
plot '++' using 1:2:(-$1) with image
plot '++' using 1:2:(-$2) with image
unset multiplot

if(rehearse <  1) reread
</code>```

Title: How to fix GNUPLOT replot issue

Body:
I set-up a multiplot like this:

set terminal wxt size 1500,900
set format x "%d%m%y %H:%M:%S"
set xdata time
set timefmt x "%Y%m%dT%H%M%S"
set key font ",6"
set lmargin 10
set rmargin 10
set multiplot layout 2,1
plot "output.txt" u 1:2 w lines axes x1y1, \
"output.txt" u 1:3 w lines axes x1y2
plot "output.txt" u 1:40 w lines axes x1y1, \
"output.txt" u 1:39 w lines axes x1y2
set y2tics border
unset multiplot

Which works, and gives me 2 plots, one above the other.

But pressing the "replot" button (or using zoom) causes the second plot to fill the window - completely hiding the first plot.

Body:
Here is another workaround. It does not answer the question directly, but it could give idea to other similar issues. Put header, and a footer 'reread', then two context could be choosen for a similar multiplot (done twice)

if (exists("rehearse")) rehearse=1+rehearse; set term x11
if (!exists("rehearse")) rehearse=0; set term png; set output sprintf("test_palette_%s.png", system("date +\"%F\""))

pr "rehearse=".rehearse; show term #<= comment printing
set samples 100;  set isosample 100,100
set xrange [0:1]; set yrange [0:1]
set palette defined (0 "white", 1 "red")
set autoscale cbfix; unset colorbox; unset key

set multiplot layout 2,2
plot '++' using 1:2:1 with image
plot '++' using 1:2:2 with image
plot '++' using 1:2:(-$1) with image
plot '++' using 1:2:(-$2) with image
unset multiplot

if(rehearse <  1) reread


问:
Google maps - get nearest location given thousand of addresses array of strings - haversine formula
My requirement is to show the nearest location on google map given thousands of addresses array of strings.

My research from stack overflow and Google web search lead to this simple solution which is as follows -

Get the Geo-coordinates of addresses using maps API

Find the nearest point to point distance (crow flying distance) using haversine formula (here)

In this solution I have to hit google maps API n , O(n) , times where n is the length of the array of addresses strings - this is my concern .

Is there any other efficient solution for the problem as this sounds very common problem.

答:
As this question is too broad , it needs further discussion on my side with the client .I am quoting @John's comment -

say you have 10000 addresses now, but after the system is live new
  addresses will be added at say 10 per week, you can just batch run the
  address you currently have, and store their information in a database
  and geolocate the new ones when they are added via google locate and
  the requirement is met


问:
Page turn empty when POST
I have 2 php files:

index.php

```<code><?php
@ini_set('default_charset', 'ISO-8859-1');
echo '<form method=post action="aplicacao.php">';
echo '<input type="hidden" name="username" value="Joaquim"/>';
echo '<input type="hidden" name="permissoes" value="administrador"/>';
echo '<input style="margin-left: 1150px; cursor=pointer;" type="submit" name="autorizado" value="Aplicação - Administração"></form>';
echo '<hr>';
echo '<form method=post action="aplicacao.php">';
echo '<input type="hidden" name="username" value="Joaquim"/>';
echo '<input type="hidden" name="permissoes" value="vendedor"/>';
echo '<input style="margin-left: 1150px; cursor=pointer;" type="submit" name="autorizado" value="Aplicação - Vendedor"></form>';
?>
</code>```

aplicacao.php

```<code><?php
if(isset($_POST['autorizado']))
{
    if($_POST['permissoes'] == 'administrador')
    {
        //something here
    }
    if($_POST['permissoes'] == 'vendedor')
    {
        //and something here
    }
}
?>
</code>```

Then, when I submit POST, aplicacao.php turns white.

I know why, but I don't know how to solve.

Some help would be appreciated.

Greetings!

答:
If you want to return to your index.php page, use the php header function to redirect:</p>

```<code>    <?php
if(isset($_POST['autorizado']))
{
    if($_POST['permissoes'] == 'administrador')
    {
        //something here
    }
    if($_POST['permissoes'] == 'vendedor')
    {
        //and something here
    }
}

header('Location: index.php');
?>
</code>```

Title: Page turn empty when POST

Body:
I have 2 php files:

index.php

<?php
@ini_set('default_charset', 'ISO-8859-1');
echo '<form method=post action="aplicacao.php">';
echo '<input type="hidden" name="username" value="Joaquim"/>';
echo '<input type="hidden" name="permissoes" value="administrador"/>';
echo '<input style="margin-left: 1150px; cursor=pointer;" type="submit" name="autorizado" value="Aplicação - Administração"></form>';
echo '
';
echo '<form method=post action="aplicacao.php">';
echo '<input type="hidden" name="username" value="Joaquim"/>';
echo '<input type="hidden" name="permissoes" value="vendedor"/>';
echo '<input style="margin-left: 1150px; cursor=pointer;" type="submit" name="autorizado" value="Aplicação - Vendedor"></form>';
?>

aplicacao.php

<?php
if(isset($_POST['autorizado']))
{
    if($_POST['permissoes'] == 'administrador')
    {
        //something here
    }
    if($_POST['permissoes'] == 'vendedor')
    {
        //and something here
    }
}
?>

Then, when I submit POST, aplicacao.php turns white.

I know why, but I don't know how to solve.

Some help would be appreciated.

Greetings!

Body:
If you want to return to your index.php page, use the php header function to redirect:

    <?php
if(isset($_POST['autorizado']))
{
    if($_POST['permissoes'] == 'administrador')
    {
        //something here
    }
    if($_POST['permissoes'] == 'vendedor')
    {
        //and something here
    }
}

header('Location: index.php');
?>


问:
nginx plus with proxy_next_upstream directive doesnt work
Problem Statement:
I want to setup a active failover using nginx plus ( i subscribed for 30 day trial).
All servers should go to primary server, if that goes down(404) only then the requests should go to second server. Once the primary is up the requests should go back to the original server. Is it possible?
With the help of other threads i was able to create the following config file. Almost all the error codes i could find, I tried that with proxy_next_upstream, but i am still not able to achieve the intended results.

I brought down the primary server manually to return 404. It briefly return 503 when its going down. But still no luck with redirecting the traffic.
Both the servers are hosted on IBM Bluemix as nodejs apps. I can share more details if needed.

```<code>upstream up1 {
   server up_server1;
}

upstream up2 {

server up_server2;

}

server {
   listen 80;

   location / {

 proxy_pass http://up1;
         proxy_next_upstream non_idempotent invalid_header error timeout http_500 http_502 http_504 http_403 http_404;
   }
}
</code>```

This is governed by another config file which looks like. Just to give more info

```<code>    user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
#    geoip_city         /etc/nginx/geoip/GeoLiteCity.dat;
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

# TCP/UDP proxy and load balancing block
#
#stream {
    # Example configuration for TCP load balancing

    #upstream stream_backend {
    #    zone tcp_servers 64k;
    #    server backend1.example.com:12345;
    #    server backend2.example.com:12345;
    #}

    #server {
    #    listen 12345;
    #    status_zone tcp_server;
    #    proxy_pass stream_backend;
    #}
#}
</code>```

答:
Your problem is that you do not in any way use the upstream up2. proxy_next_upstream mean next server in your current upstream - which is defined as "up1" in proxy_pass http://up1, not magically pick any other upstream.

So what you want is to delete upstream up2 and only leave:

```<code>upstream up1 {
   server up_server1;
   server up_server2;
}
</code>```

Body:
Problem Statement:
I want to setup a active failover using nginx plus ( i subscribed for 30 day trial).
All servers should go to primary server, if that goes down(404) only then the requests should go to second server. Once the primary is up the requests should go back to the original server. Is it possible?
With the help of other threads i was able to create the following config file. Almost all the error codes i could find, I tried that with proxy_next_upstream, but i am still not able to achieve the intended results.

I brought down the primary server manually to return 404. It briefly return 503 when its going down. But still no luck with redirecting the traffic.
Both the servers are hosted on IBM Bluemix as nodejs apps. I can share more details if needed.

upstream up1 {
   server up_server1;
}

upstream up2 {

server up_server2;

}

server {
   listen 80;

   location / {

 proxy_pass http://up1;
         proxy_next_upstream non_idempotent invalid_header error timeout http_500 http_502 http_504 http_403 http_404;
   }
}

This is governed by another config file which looks like. Just to give more info

    user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
#    geoip_city         /etc/nginx/geoip/GeoLiteCity.dat;
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

# TCP/UDP proxy and load balancing block
#
#stream {
    # Example configuration for TCP load balancing

    #upstream stream_backend {
    #    zone tcp_servers 64k;
    #    server backend1.example.com:12345;
    #    server backend2.example.com:12345;
    #}

    #server {
    #    listen 12345;
    #    status_zone tcp_server;
    #    proxy_pass stream_backend;
    #}
#}

Body:
Your problem is that you do not in any way use the upstream up2. proxy_next_upstream mean next server in your current upstream - which is defined as "up1" in proxy_pass http://up1, not magically pick any other upstream.

So what you want is to delete upstream up2 and only leave:

upstream up1 {
   server up_server1;
   server up_server2;
}


问:
java.io.IOException: Server returned HTTP response code: 521 for URL:
I want to crawl the data of a URL "http://www.gc-zb.com/index/index.html"
but When I operate like this I got the error:

```<code>public class InvitedBids {

    public static void main(String[] args) throws IOException {

        InputStream inputStream=null;
        HttpURLConnection httpConn=null;
        InputStreamReader inputStreamReader=null;
        BufferedReader bufferedReader=null;
        StringBuilder contentBuf=null;
        String myURL="http://www.gc-zb.com/index/index.html";
        URL url= null;
        try {
            url = new URL(myURL);
            System.out.println(url);
            httpConn= (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");

            inputStream=httpConn.getInputStream();  //error occurs
            inputStreamReader=new InputStreamReader(inputStream,"utf-8");
            bufferedReader=new BufferedReader(inputStreamReader);
            String line="";
            contentBuf=new StringBuilder();
            while ((line = bufferedReader.readLine())!= null) {
                contentBuf.append(line);
            }
            String buf=contentBuf.toString();
            System.out.println(buf);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
           //close I/O and HTTP
        }

    }
}
</code>```

the console says:

```<code>http://www.gc-zb.com/index/index.html
java.io.IOException: Server returned HTTP response code: 521 for URL: http://www.gc-zb.com/index/index.html
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at com.feilong.bid.InvitedBids.main(InvitedBids.java:43)
</code>```

Anybody who knows how to solve it .Thank you!

答:
Recommended Use
      org.apache.commons.httpclient.HttpClient

To solve the problem

Body:
I want to crawl the data of a URL "http://www.gc-zb.com/index/index.html"
but When I operate like this I got the error:

public class InvitedBids {

    public static void main(String[] args) throws IOException {

        InputStream inputStream=null;
        HttpURLConnection httpConn=null;
        InputStreamReader inputStreamReader=null;
        BufferedReader bufferedReader=null;
        StringBuilder contentBuf=null;
        String myURL="http://www.gc-zb.com/index/index.html";
        URL url= null;
        try {
            url = new URL(myURL);
            System.out.println(url);
            httpConn= (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");

            inputStream=httpConn.getInputStream();  //error occurs
            inputStreamReader=new InputStreamReader(inputStream,"utf-8");
            bufferedReader=new BufferedReader(inputStreamReader);
            String line="";
            contentBuf=new StringBuilder();
            while ((line = bufferedReader.readLine())!= null) {
                contentBuf.append(line);
            }
            String buf=contentBuf.toString();
            System.out.println(buf);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
           //close I/O and HTTP
        }

    }
}

the console says:

http://www.gc-zb.com/index/index.html
java.io.IOException: Server returned HTTP response code: 521 for URL: http://www.gc-zb.com/index/index.html
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at com.feilong.bid.InvitedBids.main(InvitedBids.java:43)

Anybody who knows how to solve it .Thank you!


问:
Placement of bufferedreader.close()
I am having some trouble in the placement of sections of my code. I am a high school student, and for a project I am making a flashcards app. I am using read/write to store the user's data. I am having trouble on where to close my buffered reader.

This is some of my code:

```<code>try {
        FileReader file_to_read = new FileReader(path);
        BufferedReader br1 = new BufferedReader(file_to_read);
    for (int row=0; row < lineNumber; row++) {
        try {
        //Reads the set and the subject in the text file
        String strSetSubjectLine = br1.readLine();

        //Splits the string of set and subject by using the comma
        String [] names = strSetSubjectLine.split(",");
        strSetName = names[0];
        strSubjectName = names[1];

        //Finds the line number to see the number of cards in each set
        lnr2= new LineNumberReader(new FileReader(new File("C:\\Users\\priceadria\\Desktop\\Words_" + strSetName + ".txt")));
        lnr2.skip(Long.MAX_VALUE);
        strLineNumber2 = String.valueOf(lnr2.getLineNumber());
        lineNumber2 = Integer.parseInt(strLineNumber2);

    } catch (IOException | NumberFormatException e) {
        strLineNumber2 = "0";
    }
        //Adds the set name to the set name array
        lblDeckName[row] = new JLabel (strSetName);

        //Adds all buttons that will be used in the layout into a button array
        JButton aryOptions [][] = new JButton [3][lineNumber];

        //Defines and formats the Add Words button
        JButton btnAddWords = new JButton("Add Words");
        btnAddWords.setOpaque(false);
        btnAddWords.setContentAreaFilled(false);
        btnAddWords.setBorder(null);
        btnAddWords.setBorderPainted(false);

        //Defines and formats the Play button
        JButton btnPlay = new JButton("Play");
        btnPlay.setOpaque(false);
        btnPlay.setContentAreaFilled(false);
        btnPlay.setBorder(null);
        btnPlay.setBorderPainted(false);

        //Defines and formats the Delete Set button
        JButton btnDelete = new JButton("Delete Set");
        btnDelete.setOpaque(false);
        btnDelete.setContentAreaFilled(false);
        btnDelete.setBorder(null);
        btnDelete.setBorderPainted(false);

        //Adds each button to the array based on the number of sets
        aryOptions [0][row] = btnAddWords;
        aryOptions [1][row] = btnPlay;
        aryOptions [2][row] = btnDelete;

        //Formats the GridBagLayout (Spaces are for formatting purposes)
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 0;
        gbc.gridy = row;
        layoutBackground.add(lblDeckName[row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 1;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("      "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx =2;
        gbc.gridy = row;
        layoutBackground.add(new JLabel (strSubjectName),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 3;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("                   "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 4;
        gbc.gridy = row;
        layoutBackground.add(new JLabel(strLineNumber2),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 5;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("             |  "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 6;
        gbc.gridy = row;
        layoutBackground.add(aryOptions[0][row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 7;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("  |  "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 8;
        gbc.gridy = row;
        layoutBackground.add(aryOptions[1][row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 9;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("  |  "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 10;
        gbc.gridy = row;
        layoutBackground.add(aryOptions[2][row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 11;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("  |"),gbc);

        //Creates an action event for the delete set button
        btnDelete.addActionListener((ActionEvent a) -> {
            //Finds the source of the button that was clicked
            String strSource = String.valueOf(a.getSource());
            String strSourceCut1 = strSource.substring(25,30);

            //Finds the index of the button that was clicked
            String [] aryIndex = strSourceCut1.split(",");
            String strIndex = aryIndex[0];

            try {
                //Defines new file reader and buffered reader
                FileReader file_to_read2 = new FileReader(path);
                BufferedReader br2 = new BufferedReader(file_to_read2);

                //Finds the numerical index of the button that was clicked
                int intIndex = Integer.parseInt(strIndex)/16;

                //Creates a counter to count line numbers
                int counter = 0;

                while((br2.readLine()) != null) {

                    counter ++;
                    if(intIndex == 0) { //If the index is the first option the normal try/catch returns null pointer, so a new try/catch had to be created
                        try {
                            //Finds the name of the set based on what button was clicked
                            String chosenDeck2 = br2.readLine();
                            String [] aryDeleteDeck = chosenDeck2.split(",");
                            deleteDeck = aryDeleteDeck[0];

                            //Creates the path to the file that needs to be deleted
                            Path p2 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
                            Files.delete(p2);

                        } catch (IOException e) {
                            JOptionPane.showMessageDialog(null, e);
                        }

                    } else if ( counter == intIndex) {
                        //Reads the deck name based on the button that was clicked
                        String chosenDeck2 = br2.readLine();

                        //Splits the deck name from the subject
                        String [] aryDeleteDeck = chosenDeck2.split(",");
                        deleteDeck = aryDeleteDeck[0];

                        //Closes the buffered reader and file reader

                        //Gets the file that needs to be deleted
                        Path p1 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
                        Files.delete(p1);

                    }
                }
                br2.close();
                file_to_read2.close();
            }
            catch (HeadlessException | IOException | NumberFormatException e) {
                JOptionPane.showMessageDialog(null, e);
            }
        });

        //Creates an action event for the add words button
        btnAddWords.addActionListener((ActionEvent a) -> {
            //Finds the source of the button that was clicked
            String strSource = String.valueOf(a.getSource());
            String strSourceCut1 = strSource.substring(25,30);

            //Finds the index of the button that was clicked
            String [] aryIndex = strSourceCut1.split(",");
            String strIndex = aryIndex[0];

            try {
                //Creates a new file reader and buffered reader
                FileReader file_to_read3 = new FileReader(path);
                BufferedReader br3 = new BufferedReader(file_to_read3);

                //Finds the index value
                int intIndex = Integer.parseInt(strIndex)/16;

                //Creates a counter to count line numbers
                int counter = 0;

                while((br3.readLine()) != null) {
                    //Increases counter value by 1
                    counter ++;
                    if(intIndex == 0)
                    {
                        try {
                            //Reads the set and subject for the
                            String chosenDeck2 = br3.readLine();

                            //Splits the subject from the set
                            String [] aryDeck = chosenDeck2.split(",");
                            chosenDeck = aryDeck[0];

                        } catch (Exception e) {
                            JOptionPane.showMessageDialog(null, e);
                        }

                    } else if ( counter == intIndex) {
                        String chosenDeck2 = br3.readLine();

                        String [] aryDeck = chosenDeck2.split(",");
                        chosenDeck = aryDeck[0];

                    }

                }
                br3.close();
                file_to_read3.close();
            }
            catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);
            }
            //Opens the new words frame
            frmWords s = new frmWords(deckName, newXPoint, newYPoint, chosenDeck);
            s.setVisible(true);
        });

}
} catch (Exception e ) {
        JOptionPane.showMessageDialog(null, e);

    }

}
</code>```

The problem I am facing is when I close my buffered reader "br1". If I close it in the for loop, I get a stream closed error, if I close it after the for loop, my other readers will not work. If I move the declaration of the reader into the for loop and try a try with resources statement, it will read the same line over and over again. If I try to make them all work off 1 buffered reader I get a stream closed error as well.

I am really stuck, and would really appreciate some help.

Thanks :)

答:
You may rearrange your exception handling to use this properly.

```<code>try
{
    //trying something
}
catch(SomeException e)
{
    //we failed
    e.printStackTrace();
}
finally
{
    //called when we failed or when we succeeded, even after a return; statement
}
</code>```

EDIT

This will pre-read the file and store the data in an ArrayList. Afterwards it closes the stream.

```<code>try {
    FileReader file_to_read = new FileReader(path);
    BufferedReader br1 = new BufferedReader(file_to_read);

    ArrayList<String> linesRead = new ArrayList<String>();

    String line = br1.readLine();

    while(line != null)
    {
        linesRead.add(line);
        line = br1.readLine();
    }

    br1.close();

for (int row=0; row < lineNumber; row++) {
    try {
    //Reads the set and the subject in the text file
    String strSetSubjectLine = linesRead.get(row);
</code>```

Title: Placement of bufferedreader.close()

Body:
I am having some trouble in the placement of sections of my code. I am a high school student, and for a project I am making a flashcards app. I am using read/write to store the user's data. I am having trouble on where to close my buffered reader.

This is some of my code:

try {
        FileReader file_to_read = new FileReader(path);
        BufferedReader br1 = new BufferedReader(file_to_read);
    for (int row=0; row < lineNumber; row++) {
        try {
        //Reads the set and the subject in the text file
        String strSetSubjectLine = br1.readLine();

        //Splits the string of set and subject by using the comma
        String [] names = strSetSubjectLine.split(",");
        strSetName = names[0];
        strSubjectName = names[1];

        //Finds the line number to see the number of cards in each set
        lnr2= new LineNumberReader(new FileReader(new File("C:\\Users\\priceadria\\Desktop\\Words_" + strSetName + ".txt")));
        lnr2.skip(Long.MAX_VALUE);
        strLineNumber2 = String.valueOf(lnr2.getLineNumber());
        lineNumber2 = Integer.parseInt(strLineNumber2);

    } catch (IOException | NumberFormatException e) {
        strLineNumber2 = "0";
    }
        //Adds the set name to the set name array
        lblDeckName[row] = new JLabel (strSetName);

        //Adds all buttons that will be used in the layout into a button array
        JButton aryOptions [][] = new JButton [3][lineNumber];

        //Defines and formats the Add Words button
        JButton btnAddWords = new JButton("Add Words");
        btnAddWords.setOpaque(false);
        btnAddWords.setContentAreaFilled(false);
        btnAddWords.setBorder(null);
        btnAddWords.setBorderPainted(false);

        //Defines and formats the Play button
        JButton btnPlay = new JButton("Play");
        btnPlay.setOpaque(false);
        btnPlay.setContentAreaFilled(false);
        btnPlay.setBorder(null);
        btnPlay.setBorderPainted(false);

        //Defines and formats the Delete Set button
        JButton btnDelete = new JButton("Delete Set");
        btnDelete.setOpaque(false);
        btnDelete.setContentAreaFilled(false);
        btnDelete.setBorder(null);
        btnDelete.setBorderPainted(false);

        //Adds each button to the array based on the number of sets
        aryOptions [0][row] = btnAddWords;
        aryOptions [1][row] = btnPlay;
        aryOptions [2][row] = btnDelete;

        //Formats the GridBagLayout (Spaces are for formatting purposes)
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 0;
        gbc.gridy = row;
        layoutBackground.add(lblDeckName[row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 1;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("      "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx =2;
        gbc.gridy = row;
        layoutBackground.add(new JLabel (strSubjectName),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 3;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("                   "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 4;
        gbc.gridy = row;
        layoutBackground.add(new JLabel(strLineNumber2),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 5;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("             |  "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 6;
        gbc.gridy = row;
        layoutBackground.add(aryOptions[0][row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 7;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("  |  "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 8;
        gbc.gridy = row;
        layoutBackground.add(aryOptions[1][row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 9;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("  |  "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 10;
        gbc.gridy = row;
        layoutBackground.add(aryOptions[2][row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 11;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("  |"),gbc);

        //Creates an action event for the delete set button
        btnDelete.addActionListener((ActionEvent a) -> {
            //Finds the source of the button that was clicked
            String strSource = String.valueOf(a.getSource());
            String strSourceCut1 = strSource.substring(25,30);

            //Finds the index of the button that was clicked
            String [] aryIndex = strSourceCut1.split(",");
            String strIndex = aryIndex[0];

            try {
                //Defines new file reader and buffered reader
                FileReader file_to_read2 = new FileReader(path);
                BufferedReader br2 = new BufferedReader(file_to_read2);

                //Finds the numerical index of the button that was clicked
                int intIndex = Integer.parseInt(strIndex)/16;

                //Creates a counter to count line numbers
                int counter = 0;

                while((br2.readLine()) != null) {

                    counter ++;
                    if(intIndex == 0) { //If the index is the first option the normal try/catch returns null pointer, so a new try/catch had to be created
                        try {
                            //Finds the name of the set based on what button was clicked
                            String chosenDeck2 = br2.readLine();
                            String [] aryDeleteDeck = chosenDeck2.split(",");
                            deleteDeck = aryDeleteDeck[0];

                            //Creates the path to the file that needs to be deleted
                            Path p2 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
                            Files.delete(p2);

                        } catch (IOException e) {
                            JOptionPane.showMessageDialog(null, e);
                        }

                    } else if ( counter == intIndex) {
                        //Reads the deck name based on the button that was clicked
                        String chosenDeck2 = br2.readLine();

                        //Splits the deck name from the subject
                        String [] aryDeleteDeck = chosenDeck2.split(",");
                        deleteDeck = aryDeleteDeck[0];

                        //Closes the buffered reader and file reader

                        //Gets the file that needs to be deleted
                        Path p1 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
                        Files.delete(p1);

                    }
                }
                br2.close();
                file_to_read2.close();
            }
            catch (HeadlessException | IOException | NumberFormatException e) {
                JOptionPane.showMessageDialog(null, e);
            }
        });

        //Creates an action event for the add words button
        btnAddWords.addActionListener((ActionEvent a) -> {
            //Finds the source of the button that was clicked
            String strSource = String.valueOf(a.getSource());
            String strSourceCut1 = strSource.substring(25,30);

            //Finds the index of the button that was clicked
            String [] aryIndex = strSourceCut1.split(",");
            String strIndex = aryIndex[0];

            try {
                //Creates a new file reader and buffered reader
                FileReader file_to_read3 = new FileReader(path);
                BufferedReader br3 = new BufferedReader(file_to_read3);

                //Finds the index value
                int intIndex = Integer.parseInt(strIndex)/16;

                //Creates a counter to count line numbers
                int counter = 0;

                while((br3.readLine()) != null) {
                    //Increases counter value by 1
                    counter ++;
                    if(intIndex == 0)
                    {
                        try {
                            //Reads the set and subject for the
                            String chosenDeck2 = br3.readLine();

                            //Splits the subject from the set
                            String [] aryDeck = chosenDeck2.split(",");
                            chosenDeck = aryDeck[0];

                        } catch (Exception e) {
                            JOptionPane.showMessageDialog(null, e);
                        }

                    } else if ( counter == intIndex) {
                        String chosenDeck2 = br3.readLine();

                        String [] aryDeck = chosenDeck2.split(",");
                        chosenDeck = aryDeck[0];

                    }

                }
                br3.close();
                file_to_read3.close();
            }
            catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);
            }
            //Opens the new words frame
            frmWords s = new frmWords(deckName, newXPoint, newYPoint, chosenDeck);
            s.setVisible(true);
        });

}
} catch (Exception e ) {
        JOptionPane.showMessageDialog(null, e);

    }

}

The problem I am facing is when I close my buffered reader "br1". If I close it in the for loop, I get a stream closed error, if I close it after the for loop, my other readers will not work. If I move the declaration of the reader into the for loop and try a try with resources statement, it will read the same line over and over again. If I try to make them all work off 1 buffered reader I get a stream closed error as well.

I am really stuck, and would really appreciate some help.

Thanks :)

Body:
You may rearrange your exception handling to use this properly.

try
{
    //trying something
}
catch(SomeException e)
{
    //we failed
    e.printStackTrace();
}
finally
{
    //called when we failed or when we succeeded, even after a return; statement
}

EDIT

This will pre-read the file and store the data in an ArrayList. Afterwards it closes the stream.

try {
    FileReader file_to_read = new FileReader(path);
    BufferedReader br1 = new BufferedReader(file_to_read);

    ArrayList<String> linesRead = new ArrayList<String>();

    String line = br1.readLine();

    while(line != null)
    {
        linesRead.add(line);
        line = br1.readLine();
    }

    br1.close();

for (int row=0; row < lineNumber; row++) {
    try {
    //Reads the set and the subject in the text file
    String strSetSubjectLine = linesRead.get(row);


问:
When to call SetProcessWorkingSetSize? (Convincing the memory manager to release the memory)
In a previous post ( My program never releases the memory back. Why? ) I show that FastMM can cache (read as hold for itself) pretty large amounts of memory. If your application just loaded a large data set in RAM, after releasing the data, you will see that impressive amounts of RAM are not released back to the memory pool.

I looked around and it seems that calling the SetProcessWorkingSetSize API function will "flush" the cache to disk. However, I cannot decide when to call this function. I wanted to call it at the end of the OnClick event on the button that is performing the RAM intensive operation. However, some people are saying that this may cause AV.

If anybody used this function successfully, please let me (us) know.

Many thanks.

Edit:

1. After releasing the data set, the program still takes large amounts of RAM. After calling SetProcessWorkingSetSize the size returns to few MB. Some argue that nothing was released back. I agree. But the memory foot print is now small AND it is NOT increasing back after using the program normally (for example when performing normal operation that does not involves loading large data sets). Unfortunately, there is no way to demonstrate that the memory swapped to disk is ever loaded back into memory, but I think it is not.
2. I have already demonstrated (I hope) this is not a memory leak:

My program never releases the memory back. Why?

How to convince the memory manager to release unused memory

答:
If SetProcessWorkingSetSize would solve your problem, then your problem is not that FastMM is keeping hold of memory. Since this function will just trim the workingset of your application by writing the memory in RAM to the page file. Nothing is released back to Windows.

In fact you only have made accessing the memory again slower, since it now has to be read from disc. This method has the same effect as minimising your application. Then Windows presumes you are not going to use the application again soon and also writes the workingset in RAM to the pagefile. Windows does a good job of deciding when to write RAM to the pagefile and tries to keep the most used memory in RAM as long as it can. It will make the workinset size smaller (write to pagefile) when there is little RAM left. I would not mess with it just to give the illusion that you program is using less memory while in fact it is using just as much as before, only now it is slower to access. Memory that is accessed again will be loaded into RAM again and make the workinset size grow again. Touching less memory keeps the workingset size smaller.

So no, this will not help you forcing FastMM to release the memory. If your goal is for your application to use less memory you should look elsewhere. Look for leaks, look for heap fragmentations look for optimisations and if you think FastMM is keeping you from doing so you should try to find facts to support it. If your goal is to keep your workinset size small you could try to keep your memory access local. Maybe FastMM or another memory manager could help you with it, but it is a very different problem compared to using to much memory. And maybe this function does help you solve the problem you are having, but I would use it with care and certainly not use it just to keep the illusion that your program has a low memory usage.


问:
Aligning images in the center with text next to them
I´m just working on my first website. It´s a onepager about Halo just to mess around a bit and learn HTML, CSS and Javascript. I want to create a section, listing all the boxes of the games with a little text next to them. I got two boxes in one picture. That´s what I got now:

    #historyBackground {
    background: url(../images/uff.jpg);
    background-size: cover;
    background-position: 50% 50%;
    background-repeat: none;
    position: absolute;
    }

    #halo-1-2-box {
    height: 50%;
    width: 30%;
    opacity: 0;
    transition: all ease .5s;
    }

    #centerImage {
    vertical-align: middle;
    text-align:center;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <section id="historyBackground">
    <div id="centerImage">
    <img src="images/history/halo1&2_box.png" alt="Halo Combat Evolved and
    Halo 2 Box" id="halo-1-2-box">
    <p id="halo-1">Insert Lorem Ipsum here</p>
    <p id="halo-2">Insert Lorem Ipsum here</p>
    </div>
    </section></code>```

(if you wonder what's the opacity 0 and transition doing in the box-id, that's for an animation to just show the image when scrolling down)

Of course there is some style to the text as well, but I don't think it's important for the question since it's just the color, font-family etc.

As you can see, I've added a div in order to center the image without turning it into a block element. However, if I add float left to the first p-element and float right to the second one, they don´t align next to the text, but under it.

Does anyone know how to align the image in the middle of the window and the first text element left to it and the second one right to it? (I know I could just set the margin-top of the text-elements to minus whatever, but that's not that good for responsiveness)

答:
I m not sure this is what you are asking for, but still there is a display property called flex, you can use that.

#centerImage {
  display: flex;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="historyBackground">
  <div id="centerImage">
    <p id="halo-1">Insert Lorem Ipsum here</p>
    <img src="http://www.haloforever.com/images/halo_3_dlc_legendary_small.gif" alt="Halo Combat Evolved and
Halo 2 Box" id="halo-1-2-box">
    <p id="halo-2">Insert Lorem Ipsum here</p>
  </div>
</section></code>```

Body:
I´m just working on my first website. It´s a onepager about Halo just to mess around a bit and learn HTML, CSS and Javascript. I want to create a section, listing all the boxes of the games with a little text next to them. I got two boxes in one picture. That´s what I got now:

    #historyBackground {
    background: url(../images/uff.jpg);
    background-size: cover;
    background-position: 50% 50%;
    background-repeat: none;
    position: absolute;
    }

    #halo-1-2-box {
    height: 50%;
    width: 30%;
    opacity: 0;
    transition: all ease .5s;
    }

    #centerImage {
    vertical-align: middle;
    text-align:center;
    }

Insert Lorem Ipsum here

Insert Lorem Ipsum here

(if you wonder what's the opacity 0 and transition doing in the box-id, that's for an animation to just show the image when scrolling down)

Of course there is some style to the text as well, but I don't think it's important for the question since it's just the color, font-family etc.

As you can see, I've added a div in order to center the image without turning it into a block element. However, if I add float left to the first p-element and float right to the second one, they don´t align next to the text, but under it.

Does anyone know how to align the image in the middle of the window and the first text element left to it and the second one right to it? (I know I could just set the margin-top of the text-elements to minus whatever, but that's not that good for responsiveness)

Body:
I m not sure this is what you are asking for, but still there is a display property called flex, you can use that.

#centerImage {
  display: flex;
  align-items: center;
}

<section id="historyBackground">
  <div id="centerImage">
    <p id="halo-1">Insert Lorem Ipsum here</p>
    <img src="http://www.haloforever.com/images/halo_3_dlc_legendary_small.gif" alt="Halo Combat Evolved and
Halo 2 Box" id="halo-1-2-box">
    <p id="halo-2">Insert Lorem Ipsum here</p>
  </div>
</section>


问:
Sending hyper link as attachment in javamail using smtp
I am using javamail api to send email using smtp.

i have tried a typical example from tutorial point.

But when i try to give a hyper link(https://www.antennahouse.com/XSLsample/pdf/sample-link_1.pdf) as attachment, i get the following error.

Caused by: java.io.FileNotFoundException: https:\www.antennahouse.com\XSLsample\pdf\sample-link_1.pdf (The filename, directory name, or volume label syntax is incorrect)

is there a different method for hyper link as attachment?

答:
Resolved.

I downloaded the file using http request and the attached it.


问:
Specifying Room dimensions in networked-a-frame
I am new to a-frame and have followed the examples of haydenjameslee networked-aframe. I was wondering if there is a way to specify the room size when defining the a-scene in it's tag</p>

```<code><a-scene networked-scene="app: myApp; room: room1;">
</code>```

答:
As far as I know this is not possible in A-Frame.
What do you need it for?</p>