问:
Sql query to eliminate min and max
Lets assume a table to be like

```<code>Acc_nbr  sal1 sal2 sal3 sal4
123          10    20     30   40
124           10   30      40   15
126           16    20      25    16
</code>```

So in the above table i wanted to eliminate the min & max sal columns and only remaining sal columns need to be taken!

Eg: for acc_nbr 123 min sal =10 & max sal = 40
So as per my requirement i need to eliminate both 10 & 40, & need to take only 20&30.
Likewise the same to other acc_nbr's .
Please help.. thanks in advance!

答:
Kind of merge sort

```<code>select Acc_nbr,  greatest(sal1,sal2) salA, least(sal3,sal4) salB
from (
    select Acc_nbr, sal1, least(sal2,sal3) sal2, greatest(sal2,sal3) sal3, sal4
    from (
        select Acc_nbr, least(sal1,sal2) sal1, greatest(sal1,sal2) sal2, least(sal3,sal4) sal3, greatest(sal3,sal4) sal4
        from tbl
        ) t1
   ) t2;
</code>```

Can be wrapped into single select, it just will be a bit more verbose.

Title: Sql query to eliminate min and max

Body:
Lets assume a table to be like

Acc_nbr  sal1 sal2 sal3 sal4
123          10    20     30   40
124           10   30      40   15
126           16    20      25    16

So in the above table i wanted to eliminate the min & max sal columns and only remaining sal columns need to be taken!

Eg: for acc_nbr 123 min sal =10 & max sal = 40
So as per my requirement i need to eliminate both 10 & 40, & need to take only 20&30.
Likewise the same to other acc_nbr's .
Please help.. thanks in advance!

Body:
Kind of merge sort

select Acc_nbr,  greatest(sal1,sal2) salA, least(sal3,sal4) salB
from (
    select Acc_nbr, sal1, least(sal2,sal3) sal2, greatest(sal2,sal3) sal3, sal4
    from (
        select Acc_nbr, least(sal1,sal2) sal1, greatest(sal1,sal2) sal2, least(sal3,sal4) sal3, greatest(sal3,sal4) sal4
        from tbl
        ) t1
   ) t2;

Can be wrapped into single select, it just will be a bit more verbose.


来源: stackexchange

问:
How to extract portion of a line in ruby?
I have a line say

line = "start running at Sat April 1 07:30:37 2017"

and I want to extract

"Sat April 1 07:30:37 2017"

I tried this...

```<code>line = "start running at Sat April 1 07:30:37 2017"
if (line =~ /start running at/)
   line.split("start running at ").last
end
</code>```

... but is there any other way of doing this?

答:
And yet another alternative:</p>

```<code>puts $1 if line =~ /start running at (.*)/
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a line say

line = "start running at Sat April 1 07:30:37 2017"

and I want to extract

"Sat April 1 07:30:37 2017"

I tried this...

line = "start running at Sat April 1 07:30:37 2017"
if (line =~ /start running at/)
   line.split("start running at ").last
end

... but is there any other way of doing this?

Body:
And yet another alternative:

puts $1 if line =~ /start running at (.*)/


问:
How to regenerate latex fragments in org-mode?
I have latex fragments in org-mode that were generated with my previous emacs theme and now that I switched my theme, the old latex fragments still have my old background color instead of the new one. How can I clear them and regenerate them (linux)?</p>

答: The latex fragments are stored in a folder named "ltximg" in the same folder as where the org file is located. To recreate the fragments, delete that folder, restart emacs and do org-toggle-latex-fragment again.</p>


问:
While automating script using selenium webdriver ,`.isDisplayed()` command is not working in `if else` statement
While automating script using selenium webdriver ,.isDisplayed() command is not working in if else statement.
If the condition is true under if statement, then it is working fine. But if the condition is not true, the code is not moving to else statement.

```<code>package module17;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Dice {
static WebDriver driver = null;
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "D:\\Automation Software\\chromedriver_win32\\chromedriver_update.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        //driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
        driver.get("http://www.dice.com/");
        Thread.sleep(15000);
        driver.findElement(By.xpath("//*[@alt='Close']")).click();
        driver.findElement(By.xpath("//*[@id='search-field-keyword']")).sendKeys("Selenium WebDriver");
        WebElement Place =driver.findElement(By.xpath("//input[@placeholder='Location']"));
        Place.clear();
        driver.findElement(By.xpath("//button[contains(text(),'Find Tech Jobs')]")).click();
        WebElement PageNumber = driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'2')]"));
        int i=2;
        while(i<=44)
        {
            try
                {
                    if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).isDisplayed()  )
                        {
                            driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).click();
                            Thread.sleep(5000);
                            i= i+5;
                        }
                    else if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).isDisplayed() )
                        {
                            driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).click();
                        }
                    else
                        {
                            driver.quit();
                        }
                }
            catch (Exception e)
                {
                    System.out.println("Exception");
                }

        }
    }
}
</code>```

答:
Actually isDisplayed()is working fine. Issue is in your looping. In first if condition you have incremented value with i+5 So the value 7 not matched in xpath in next iteration that's why it was moving in Exception.

You need to manage your if else conditions in try catch block . Replace below looping code and try

```<code>int i=5;
while(i<=44)
{
    try
    {
        if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).isDisplayed()  )
        {
            driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).click();
            Thread.sleep(5000);
            i+=5;
        }

     }catch(Exception e)
       {
            try
            {
                 if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).isDisplayed() )
                 {
                     driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).click();
                 }
            }
            catch(Exception e2)
            {
                driver.quit();
           }
     }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
While automating script using selenium webdriver ,.isDisplayed() command is not working in if else statement.
If the condition is true under if statement, then it is working fine. But if the condition is not true, the code is not moving to else statement.

package module17;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Dice {
static WebDriver driver = null;
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "D:\\Automation Software\\chromedriver_win32\\chromedriver_update.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        //driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
        driver.get("http://www.dice.com/");
        Thread.sleep(15000);
        driver.findElement(By.xpath("//*[@alt='Close']")).click();
        driver.findElement(By.xpath("//*[@id='search-field-keyword']")).sendKeys("Selenium WebDriver");
        WebElement Place =driver.findElement(By.xpath("//input[@placeholder='Location']"));
        Place.clear();
        driver.findElement(By.xpath("//button[contains(text(),'Find Tech Jobs')]")).click();
        WebElement PageNumber = driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'2')]"));
        int i=2;
        while(i<=44)
        {
            try
                {
                    if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).isDisplayed()  )
                        {
                            driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).click();
                            Thread.sleep(5000);
                            i= i+5;
                        }
                    else if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).isDisplayed() )
                        {
                            driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).click();
                        }
                    else
                        {
                            driver.quit();
                        }
                }
            catch (Exception e)
                {
                    System.out.println("Exception");
                }

        }
    }
}

Body:
Actually isDisplayed()is working fine. Issue is in your looping. In first if condition you have incremented value with i+5 So the value 7 not matched in xpath in next iteration that's why it was moving in Exception.

You need to manage your if else conditions in try catch block . Replace below looping code and try

int i=5;
while(i<=44)
{
    try
    {
        if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).isDisplayed()  )
        {
            driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).click();
            Thread.sleep(5000);
            i+=5;
        }

     }catch(Exception e)
       {
            try
            {
                 if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).isDisplayed() )
                 {
                     driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).click();
                 }
            }
            catch(Exception e2)
            {
                driver.quit();
           }
     }
}


问:
Elasticsearch: How to ignore/disable special characters in a search query?
I'm using Elasticsearch with fairly default settings, I think pretty much the only thing I changed was setting 'analyzer' => 'english'

If a user enters a [ character (or some of the other Elasticsearch special chars) into the text in their search query, ES throws an exception (I'm using elasticsearch-php). Is there a simple way (without writing my own pre-ES filtering) to simply have ES ignore known special characters? My users are never going to use them.

I thought it was kind of strange that this is default behaviour (to give an error), considering 99% of end users would never know about about using special chars.

I tried the "lenient" option, but that didn't help.

Thanks.

答: Look at Query string, search for the word reverse, you need to put \ before (</p>


问:
Java class method defines String type, takes int as param and returns null
Just getting into some Java for now. Saw this extended class in the OCA 7 book and just wondered how it's possible that class Baz uses the go method and expects return type String but the argument takes an int. The return is then null.

Is Baz a legal construction or will this return compile error? I mean it returns type String, but takes an int argument and then returns null. How is that possible?

```<code>public class Foo {
    void go() {}
}

public class Baz extends Foo {
    String go(int x) {
        return null;
    }
}
</code>```

答:
Since Baz extends Foo it will inherit Foo's go() method.

Additionally Baz declares its own method called go(int x) with a return type of String. These are two different methods and the compiler treats them as such, since they have a different signature (= name + parameter types). If the only difference was the return type then you'd get a compilation error.

Because the signature is different the compiler can always tell which method you want to call - in this case depending on whether you pass an int as a parameter when calling go or not.

This is why Baz is a fully valid Java class.

Edit: go(int x) can return null because String is a class. You can always pass/return null when a reference to an instance of a class is expected. (The method parameter doesn't matter at all for why this is possible)

Body:
Just getting into some Java for now. Saw this extended class in the OCA 7 book and just wondered how it's possible that class Baz uses the go method and expects return type String but the argument takes an int. The return is then null.

Is Baz a legal construction or will this return compile error? I mean it returns type String, but takes an int argument and then returns null. How is that possible?

public class Foo {
    void go() {}
}

public class Baz extends Foo {
    String go(int x) {
        return null;
    }
}


问:
Domain classes and slick generated case classes conversion with Shapeless
Slick codegen generates an handy Tables.scala with all the classes for the rows and the tables. We like this approach because we can use relational design and exploit the full power of the SQL dialect we choose.

However, we are writing a lot of boiler plate code to convert from our REST API Model / Domain API Model to slick XYZ row for the following reasons:

There are additional parameters in the Slick case class than in the domain case class (these additional parameters are extracted, for example, from the path of the REST resource)

We would not like to expose path-dependent types to other layers / microservices. They only need to know the REST API model

We typically convert date and time classes from java.sql to java.time equivalent

Can we automatize the conversion so we do not have to write explicitely every time two conversion functions, from domain model to slick case classes and viceversa. In particular:

How do write a generic function that provides an implicit conversion between two equivalent case classes with the same HLIST representation?

How do we write a generic implicit conversion between two case classes with a different HLIST representation, provided a set of implicit conversions in scope for the different members (java.sql.Timestamp -> java.time.ZonedDateTime)

How do we write a function to convert between two case classes where the output one has a Repr = HList1 :: HList2 and the first one has a Repr = HList2 (i.e. how do we prepend / append to HList2 the parameters extracted from the request?)

答: There are a handful of libraries that do this which you could use or read the source to learn from. For example https://index.scala-lang.org/davegurnell/bulletin/bulletin/0.7.0</p>


问:
C++ - removal of a node in an AVL Tree
I'm currently trying to implement an AVL tree in C++, so far I've done pretty much everything except a node removal.

1) Can someone confirm that my algorithm for removing a node is correct?

Find the node to delete in the tree

if the node has 0 child : delete the node

else, if the node has 1 child: delete the node, and re-link his child

else (2 children): find its successor, and swap the node to delete with its successor. then repeat the steps to delete the node (which is now where its successor was).

Rebalance the tree after the insertion (it'll rebalance the tree recursively...)

I've done this, but the part where I'm not sure, is the step where I delete the node. Do I have to delete the reference to the node also, or it'll be managed? (Because I've passed in parameter a Node*&, but the successor is only a Node* in the function...)

I'm not sure I'm being super clear, let me know if you need more details.

(I would post some code, but unfortunately I speak french, so you won't understand much from it, I guess)

答:
The tricky part with your question is that "deleting the reference to the node" is actually rather vague: depending on what you consider "deleting the reference", the answer can be 'yes' or 'no'.

As I see it, you are going to "delete the reference to the node" as part of relinking the tree. The crucial part is the fact that your method receives the node pointer as Node *&: with this, your method doesn't just get the pointer to the node under scrutiny, it receives a reference to where this pointer is stored in the parent node. You have to modify this reference in order to keep the tree linkage intact.

So if your method does something like this:

```<code>void deleteNode (Node*& node) {
    if (node is the right one to delete) {
        Node * tmp = node;
        node = node->successor;
        delete node;
    }
    else
        deleteNode(node->successor);
}
</code>```

the assignment node = node->successor actually modifies the previous nodes' successor field. Without this assignment, your tree structure would be damaged, as the previous nodes' successor field would point to a now-deallocated Node.

ContentLicense: CC BY-SA 2.5

Title: C++ - removal of a node in an AVL Tree

Body:
The tricky part with your question is that "deleting the reference to the node" is actually rather vague: depending on what you consider "deleting the reference", the answer can be 'yes' or 'no'.

As I see it, you are going to "delete the reference to the node" as part of relinking the tree. The crucial part is the fact that your method receives the node pointer as Node *&: with this, your method doesn't just get the pointer to the node under scrutiny, it receives a reference to where this pointer is stored in the parent node. You have to modify this reference in order to keep the tree linkage intact.

So if your method does something like this:

void deleteNode (Node*& node) {
    if (node is the right one to delete) {
        Node * tmp = node;
        node = node->successor;
        delete node;
    }
    else
        deleteNode(node->successor);
}

the assignment node = node->successor actually modifies the previous nodes' successor field. Without this assignment, your tree structure would be damaged, as the previous nodes' successor field would point to a now-deallocated Node.


问:
dynamically generate html checkbox using php
dI have a very small script that I am using to create dynamic content from a MySQL table. When I insert php into my code, it seems to overwrite the values.

My script is the following:

```<code>   <?php
    include 'auto_loader.php';
    include 'db.php';
    $database = new Database();
    $database->query('Select * FROM barber_dev.services');
    $rows = $database->resultset();
    foreach ($rows as $key => $value) {

      echo '
      <div class="label-container">
          <input type="checkbox" name="services[]" id="'+$value['services']+'" value="HairCut">
          <label for="Haircut">Haircut</label>
      </div>
              ';
 }

     ?>
</code>```

I would except to see about 10 checkboxes with the php rendering valid id values. What I get instead is 0 checkboxes and the actual values. I am probably missing something extremely basic, but any help would greatly be appreciated.

Thanks.

答:
You are using wrong concatenation operator.

You should use . in PHP for concat not +.

Try below code

```<code>echo '
  <div class="label-container">
      <input type="checkbox" name="services[]" id="services" value="' . $rows['services'] . '">
      <label for="' . $rows['services'] . '">' . $rows['services'] . '</label>
  </div>
';
</code>```

Body:
dI have a very small script that I am using to create dynamic content from a MySQL table. When I insert php into my code, it seems to overwrite the values.

My script is the following:

   <?php
    include 'auto_loader.php';
    include 'db.php';
    $database = new Database();
    $database->query('Select * FROM barber_dev.services');
    $rows = $database->resultset();
    foreach ($rows as $key => $value) {

      echo '

          <input type="checkbox" name="services[]" id="'+$value['services']+'" value="HairCut">
          Haircut

              ';
 }

     ?>

I would except to see about 10 checkboxes with the php rendering valid id values. What I get instead is 0 checkboxes and the actual values. I am probably missing something extremely basic, but any help would greatly be appreciated.

Thanks.

Body:
You are using wrong concatenation operator.

You should use . in PHP for concat not +.

Try below code

echo '
  <div class="label-container">
      <input type="checkbox" name="services[]" id="services" value="' . $rows['services'] . '">
      <label for="' . $rows['services'] . '">' . $rows['services'] . '</label>
  </div>
';


问:
Exception of a method not handled and code compiles successfully
```<code>public class ExceptionDemo {

    public static void main(String...args) {
        try {
            bar();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        foo();
    }

    public static void bar() {

    }

    public static void foo() throws NullPointerException {

    }
}
</code>```

Please explain me why this code compiles successfully even though we didn't handle foo() method exception.

答:
In Java, Exception and Error classes are inherited from Throwable class. Exception and Error classes has subclasses.

If your code throw an Exception (except RunTimeException) you must catch this exception. But If your code throw a RunTimeException or Error you doesn't have to catch RunTimeException or Error but you can.

Throwable, Exception and Exception subclasses (except RunTimeException) are checked Exception, so you have to catch this exceptions.

But RunTimeException and Error classes are unchecked Exceptions, so you doesn't have to catch. You should try that your code doesn't throw unchecked Exceptions in runtime.

Body:
public class ExceptionDemo {

    public static void main(String...args) {
        try {
            bar();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        foo();
    }

    public static void bar() {

    }

    public static void foo() throws NullPointerException {

    }
}

Please explain me why this code compiles successfully even though we didn't handle foo() method exception.


答: NullPointerException in Java is a RuntimeException and so the compiler does not force you to use a try-catch block to handle it appropriately. We need not handle Runtime Exceptions using try catch block, but if it is a Compile Time Exception like FileNotFoundException then you need to add the try catch Block.</p>

Title: Exception of a method not handled and code compiles successfully


问:
Instructions on Supervisor queue installation on Godaddy shared hosting server(Linux)
Can somebody share step by step instructions on Supervisor queue installation on Godaddy shared hosting server? I tried to search and alot but could not find one.</p>

答:
The process to install supervisor will depend on the OS version your server is running. You can find out your OS by following advice on this page.

In any case you will need SSH access to run commands in terminal and sudo / root privileges.

Here's an outline for Debian / Ubuntu OS.

1/ Install beanstalkd

Install beanstalkd (the daemon that will handle queues):

(note: you can skip this step, if you are going to use some simple queue driver instead, like "sync" or "database" - in this case, be sure to replace "beanstalkd" further along this guide, namely in supervisor config file section)

```<code>sudo apt-get install beanstalkd
sudo nano /etc/default/beanstalkd
</code>```

uncomment this line:

```<code>START=yes
</code>```

start the service:

```<code>sudo service beanstalkd start
</code>```

2/ Add Pheanstalk package

In your Laravel app, add Pheanstalk package to talk to beanstalkd:

(skip this step if you are not using beanstalkd driver)

```<code>cd /my/laravel/app/dir
composer require pda/pheanstalk
</code>```

3/ Install supervisor

```<code>sudo apt-get install supervisor
</code>```

make sure it starts with the server

```<code>sudo service supervisor restart
</code>```

Create a supervisor configuration file for your laravel app

```<code>sudo nano /etc/supervisor/conf.d/myapp.conf
</code>```

Here's a sample file, it will start 2 threads listening to your queue. Each job will be tried maximum 3 times before failing eventually. Make sure to change user and paths to match your laravel directory and server user.

```<code>[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /my/laravel/app/dir/artisan queue:work beanstalkd --tries=3
autostart=true
autorestart=true
user=forge
numprocs=2
redirect_stderr=true
stdout_logfile=/my/laravel/app/dir/storage/logs/worker.log
</code>```

Consult https://laravel.com/docs/master/queues#running-the-queue-worker for details on other options that can be configured here.

4/ Make supervisor pick up the changes

```<code>sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl restart laravel-worker:*
</code>```

5/ That's all, try dispatching a job to the default queue, check your laravel log for any errors.

Body:
The process to install supervisor will depend on the OS version your server is running. You can find out your OS by following advice on this page.

In any case you will need SSH access to run commands in terminal and sudo / root privileges.

Here's an outline for Debian / Ubuntu OS.

1/ Install beanstalkd

Install beanstalkd (the daemon that will handle queues):

(note: you can skip this step, if you are going to use some simple queue driver instead, like "sync" or "database" - in this case, be sure to replace "beanstalkd" further along this guide, namely in supervisor config file section)

sudo apt-get install beanstalkd
sudo nano /etc/default/beanstalkd

uncomment this line:

START=yes

start the service:

sudo service beanstalkd start

2/ Add Pheanstalk package

In your Laravel app, add Pheanstalk package to talk to beanstalkd:

(skip this step if you are not using beanstalkd driver)

cd /my/laravel/app/dir
composer require pda/pheanstalk

3/ Install supervisor

sudo apt-get install supervisor

make sure it starts with the server

sudo service supervisor restart

Create a supervisor configuration file for your laravel app

sudo nano /etc/supervisor/conf.d/myapp.conf

Here's a sample file, it will start 2 threads listening to your queue. Each job will be tried maximum 3 times before failing eventually. Make sure to change user and paths to match your laravel directory and server user.

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /my/laravel/app/dir/artisan queue:work beanstalkd --tries=3
autostart=true
autorestart=true
user=forge
numprocs=2
redirect_stderr=true
stdout_logfile=/my/laravel/app/dir/storage/logs/worker.log

Consult https://laravel.com/docs/master/queues#running-the-queue-worker for details on other options that can be configured here.

4/ Make supervisor pick up the changes

sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl restart laravel-worker:*

5/ That's all, try dispatching a job to the default queue, check your laravel log for any errors.


问:
Why am I getting so many br tags
I started writing html code and when I view it on chrome, the table is displayed after a long white space. When I inspect the element, on chrome, I get a lot of br tags but I have not given any br tags in the code

How come?

<!DOCTYPE html>

  <title> Practice </title>

 <big><big> Registration Form <big><big>

<form name="My Form" action="" method="">

 Username
 <input type="text" name="t1" size="6"/>

 Password
 <input type="password" name="t2" size="6"/>

 Name
 <input type="text" name="t3" size="30"/>

 Address
 <input type="text" name="t4" size="30"/>

 Country
<select name="s1">
<option> Select Your Country </option>
<option> Afghanistan </option>
<option> Bangladesh </option>
<option> China </option>
<option> India </option>
<option> Russia </option>
</select>

 Zip Code
 <input type="text" name="t5" size="6"/>

 Email
 <input type="text" name="t6" size="30"/>

Sex
<input type="radio" name="r1" value="100" checked/>Male
<input type="radio" name="r1" value="102"/>Female

Language
<input type="checkbox" name="r1" value="100" checked/>English
<input type="checkbox" name="r2" value="102"/>Non English

 About
<textarea name="a1" rows="5" cols="32"> </textarea>

<input type="submit" name="b2" value="submit here"/>

</form>

```

答: You have a lot of unnecessary "br" tags in your code, inside your table. Remove them all and all will be fine! Cheers. </p>

Title: Why am I getting so many br tags


问:
I'm trying to insert data into the database through php
```<code><?php
<form name "fav_button" action="" method="post">
<input type="submit" name="fav_button"  value="Add to Favorite" />
</form>

if(isset($_POST['fav_button']) ){
        $conn=mysqli_connect("localhost","root","alaa","registration_database");
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);

            }
          $query= ("INSERT INTO favs (uId, itemId) VALUES ('1','2'); ");
        }
 ?>
</code>```

I'm trying to add data into the table favs after clicking the button "fav_button" the page refreshes and no errors show up, but the table is not updated, can anyone explain what I'm doing wrong exactly?

I'm running the query i'm using in the phpmyadmin and it's working fine.

答:
You missed $conn->query($query); and it is important to run the query.. this line actually executes your query

```<code>    <form name="fav_button" action="" method="post">
    <input type="submit" name="fav_button"  value="Add to Favorite" />
    </form>

    if(isset($_POST['fav_button']) ){
            $conn=mysqli_connect("localhost","root","alaa","registration_database");
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);

                }
              $query= ("INSERT INTO favs (uId, itemId) VALUES ('1','2'); ");
              $conn->query($query);//this is the line which actually executes your query
            }
     ?>
</code>```

Body:
<?php
<form name "fav_button" action="" method="post">
<input type="submit" name="fav_button"  value="Add to Favorite" />
</form>

if(isset($_POST['fav_button']) ){
        $conn=mysqli_connect("localhost","root","alaa","registration_database");
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);

            }
          $query= ("INSERT INTO favs (uId, itemId) VALUES ('1','2'); ");
        }
 ?>

I'm trying to add data into the table favs after clicking the button "fav_button" the page refreshes and no errors show up, but the table is not updated, can anyone explain what I'm doing wrong exactly?

I'm running the query i'm using in the phpmyadmin and it's working fine.

Body:
You missed $conn->query($query); and it is important to run the query.. this line actually executes your query

    <form name="fav_button" action="" method="post">
    <input type="submit" name="fav_button"  value="Add to Favorite" />
    </form>

    if(isset($_POST['fav_button']) ){
            $conn=mysqli_connect("localhost","root","alaa","registration_database");
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);

                }
              $query= ("INSERT INTO favs (uId, itemId) VALUES ('1','2'); ");
              $conn->query($query);//this is the line which actually executes your query
            }
     ?>


问:
Open Skype or Gtalk in iPhone
I want to open Skype or Gtalk in iPhone's webview by just using a URL.
Similar to something like the URL Scheme's provided by Apple for opening Apple Mail mailTo:// , messaging API sms://, telephone tel:// and so on.</p>

答:
```<code>NSString *URLString = [NSString stringWithFormat:@"skype:%@?call",userSkype];
NSURL *URL          = [NSURL URLWithString:URLString];
</code>```

URL will be nil if your userSkype is not valid -
extra spaces, etc.

Title: Open Skype or Gtalk in iPhone

Body:
NSString *URLString = [NSString stringWithFormat:@"skype:%@?call",userSkype];
NSURL *URL          = [NSURL URLWithString:URLString];

URL will be nil if your userSkype is not valid -
extra spaces, etc.


问:
Plotly - starting X axis from first data point
In this plotly example,

The first date is on the first of January,

```<code>var trace1 = {
  x: ['2000-01-01',
</code>```

However, the first label shown on the graph is Jan 2.

Is there a way to force the graph to start from the 1st of January?

Body:
In this plotly example,

The first date is on the first of January,

var trace1 = {
  x: ['2000-01-01',

However, the first label shown on the graph is Jan 2.

Is there a way to force the graph to start from the 1st of January?

Body:
You have several possibilities to specify the first tick value of your x-axis.

Use tick0 together with dticks

var layout = {
  xaxis: {
    tick0: '2000-01-01',
    dtick: 7*24*60*60*1000 // 7 days
  };

or completely set the tickvals yourself

var layout = {
  xaxis: {
    tickvals: ['2000-01-01', '2000-01-15', '2000-01-31']
  };

var trace1 = {
  x: ['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07', '2000-01-08', '2000-01-09', '2000-01-10', '2000-01-11', '2000-01-12', '2000-01-13', '2000-01-14', '2000-01-15', '2000-01-16', '2000-01-17', '2000-01-18', '2000-01-19', '2000-01-20', '2000-01-21', '2000-01-22', '2000-01-23', '2000-01-24', '2000-01-25', '2000-01-26', '2000-01-27', '2000-01-28', '2000-01-29', '2000-01-30', '2000-01-31'],
  y: [4.3, 8.2, 4.1, 5.6, -3, -0.2, 0.3, 0.4, 4.1, 5, 4.6, -0.2, -8.5, -9.1, -2.7, -2.7, -17, -11.3, -5.5, -6.5, -16.9, -12, -6.1, -6.6, -7.9, -10.8, -14.8, -11, -4.4, -1.3, -1.1],
  mode: 'lines',
  type: 'scatter',
  name: '2000'
};

var data = [trace1];

var layout = {
  xaxis: {
    type: 'date',
    title: 'January Weather',
    tick0: '2000-01-01',
    dtick: 7 * 24 * 60 * 60 * 1000
  },
  yaxis: {
    title: 'Daily Mean Temperature'
  },
  title:'2000 Toronto January Weather'
};

Plotly.plot('myDiv', data, layout);

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv" style="width:100%;height:400px;"></div>


问:
How does Validate method of EPPlus work?
I'm using EPPlus as a calculations server. Here is my code:

```<code>using (var xlp = new ExcelPackage(stream))
{
OfficeOpenXml.ExcelWorksheet Sheet = xlp.Workbook.Worksheets["sheet1"];
//Some code for feeding user data to excel sheet
//...

//We first invoke calculate method to let contraints of data validation get updated.
xlp.Workbook.Calculate();

var v = Sheet.DataValidations["A1"];
if (v != null)
{
    switch (v.ValidationType.Type)
    {
        case OfficeOpenXml.DataValidation.eDataValidationType.DateTime:
            OfficeOpenXml.DataValidation.ExcelDataValidationDateTime V1 = (OfficeOpenXml.DataValidation.ExcelDataValidationDateTime)v;
            try
            {
                //this line doesn't do any thing
                V1.Validate();
            }
            catch
            {
            }
        break;
        case ...
    }
}
}
</code>```

I had read somewhere that Validate() method throws exception for invalid data. It doesn't.
My question: How to use the Validate() method?

答:
That would depend on what the content of the cell and the settings of the validator's Operator:

http://epplus.codeplex.com/SourceControl/latest#EPPlus/DataValidation/ExcelDataValidationOperator.cs

```<code>/// <summary>
/// Operator for comparison between Formula and Formula2 in a validation.
/// </summary>
public enum ExcelDataValidationOperator
{
    any,
    equal,
    notEqual,
    lessThan,
    lessThanOrEqual,
    greaterThan,
    greaterThanOrEqual,
    between,
    notBetween
}
</code>```

The ExcelDataValidationDateTime (eventually) derives from ExcelDataValidationWithFormula<IExcelDataValidationFormulaDateTime> which contains the implemenation of Validate():

http://epplus.codeplex.com/SourceControl/latest#EPPlus/DataValidation/ExcelDataValidationWithFormula.cs

```<code>public override void Validate()
{
    base.Validate();
    if (Operator == ExcelDataValidationOperator.between || Operator == ExcelDataValidationOperator.notBetween)
    {
        if (string.IsNullOrEmpty(Formula2Internal))
        {
            throw new InvalidOperationException("Validation of " + Address.Address + " failed: Formula2 must be set if operator is 'between' or 'notBetween'");
        }
    }
}
</code>```

So it will throw an exception (invalidate) when the validation operation is either ExcelDataValidationOperator.between or ExcelDataValidationOperator.notBetween and Forumla2 is not set (not to be confused with the primary Formula).  In other words, it considers the validator invalid when you are using an operation which requires TWO values/formulas to compare but only one is set.

Body:
I'm using EPPlus as a calculations server. Here is my code:

using (var xlp = new ExcelPackage(stream))
{
OfficeOpenXml.ExcelWorksheet Sheet = xlp.Workbook.Worksheets["sheet1"];
//Some code for feeding user data to excel sheet
//...

//We first invoke calculate method to let contraints of data validation get updated.
xlp.Workbook.Calculate();

var v = Sheet.DataValidations["A1"];
if (v != null)
{
    switch (v.ValidationType.Type)
    {
        case OfficeOpenXml.DataValidation.eDataValidationType.DateTime:
            OfficeOpenXml.DataValidation.ExcelDataValidationDateTime V1 = (OfficeOpenXml.DataValidation.ExcelDataValidationDateTime)v;
            try
            {
                //this line doesn't do any thing
                V1.Validate();
            }
            catch
            {
            }
        break;
        case ...
    }
}
}

I had read somewhere that Validate() method throws exception for invalid data. It doesn't.
My question: How to use the Validate() method?

Body:
That would depend on what the content of the cell and the settings of the validator's Operator:

http://epplus.codeplex.com/SourceControl/latest#EPPlus/DataValidation/ExcelDataValidationOperator.cs

/// <summary>
/// Operator for comparison between Formula and Formula2 in a validation.
/// </summary>
public enum ExcelDataValidationOperator
{
    any,
    equal,
    notEqual,
    lessThan,
    lessThanOrEqual,
    greaterThan,
    greaterThanOrEqual,
    between,
    notBetween
}

The ExcelDataValidationDateTime (eventually) derives from ExcelDataValidationWithFormula<IExcelDataValidationFormulaDateTime> which contains the implemenation of Validate():

http://epplus.codeplex.com/SourceControl/latest#EPPlus/DataValidation/ExcelDataValidationWithFormula.cs

public override void Validate()
{
    base.Validate();
    if (Operator == ExcelDataValidationOperator.between || Operator == ExcelDataValidationOperator.notBetween)
    {
        if (string.IsNullOrEmpty(Formula2Internal))
        {
            throw new InvalidOperationException("Validation of " + Address.Address + " failed: Formula2 must be set if operator is 'between' or 'notBetween'");
        }
    }
}

So it will throw an exception (invalidate) when the validation operation is either ExcelDataValidationOperator.between or ExcelDataValidationOperator.notBetween and Forumla2 is not set (not to be confused with the primary Formula).  In other words, it considers the validator invalid when you are using an operation which requires TWO values/formulas to compare but only one is set.


答:
You need to use . for concatenation in php, not + so try something like

```<code> echo '
  <div class="label-container">
      <input type="checkbox" name="services[]" id="'.$value['services'].'" value="HairCut">
      <label for="Haircut">Haircut</label>
  </div>
          ';
</code>```

hope that helps

Title: dynamically generate html checkbox using php

Body:
You need to use . for concatenation in php, not + so try something like

 echo '
  <div class="label-container">
      <input type="checkbox" name="services[]" id="'.$value['services'].'" value="HairCut">
      <label for="Haircut">Haircut</label>
  </div>
          ';

hope that helps


问:
Xamarin iOS EventArgs missing first property
When using EventArgs attribute on delegate method it generates event handler class with properties based on method parameters except the first one.

The first parameter is missing in generated event args class.

For example:

```<code>[Protocol, Model]
[BaseType(typeof(NSObject))]
public interface TestDelegate
{
    // @required -(void)DidReceiveFrom:(NSString * _Nonnull)p1 withP2:(NSString * _Nonnull)p2 withP3:(NSString * _Nonnull)p3 withP4:(NSString * _Nonnull)p4;
    [Abstract]
    [Export("DidReceiveFrom:withP2:withP3:withP4:")]
    [EventArgs("DidReceiveFrom")]
    void DidReceiveFrom(string p1, string p2, string p3, string p4);
</code>```

Then generated EventArgs class becomes:

```<code>//
// EventArgs classes
//
public partial class DidReceiveFromEventArgs : EventArgs {
    public DidReceiveFromEventArgs (string p2, string p3, string p4)
    {
        this.p2 = p2;
        this.p3 = p3;
        this.p4 = p4;
    }
    public string p2 { get; set; }
    public string p3 { get; set; }
    public string p4 { get; set; }
}
</code>```

So it definitely missing p1 property. How to avoid this behavior?

答:
I guess you're using objective sharpie tool to generate C# code for the Objective C API.

If so, then, basically you need to remember that it is a helper tool but not a 100% guarantee it will get correct C# code for you.

Regardless of that, easiest way to fix that is to edit the C# code manually and add this parameter if you miss it.

You're not showing your C# code for the TestDelegate. Might be that you have a first parameter as a sender and then all 3 other parameters as event args?

If that's the case, comment [EventArgs("DidReceiveFrom")] attribute in the C# API and re-compile bindings.

Body:
When using EventArgs attribute on delegate method it generates event handler class with properties based on method parameters except the first one.

The first parameter is missing in generated event args class.

For example:

[Protocol, Model]
[BaseType(typeof(NSObject))]
public interface TestDelegate
{
    // @required -(void)DidReceiveFrom:(NSString * _Nonnull)p1 withP2:(NSString * _Nonnull)p2 withP3:(NSString * _Nonnull)p3 withP4:(NSString * _Nonnull)p4;
    [Abstract]
    [Export("DidReceiveFrom:withP2:withP3:withP4:")]
    [EventArgs("DidReceiveFrom")]
    void DidReceiveFrom(string p1, string p2, string p3, string p4);

Then generated EventArgs class becomes:

//
// EventArgs classes
//
public partial class DidReceiveFromEventArgs : EventArgs {
    public DidReceiveFromEventArgs (string p2, string p3, string p4)
    {
        this.p2 = p2;
        this.p3 = p3;
        this.p4 = p4;
    }
    public string p2 { get; set; }
    public string p3 { get; set; }
    public string p4 { get; set; }
}

So it definitely missing p1 property. How to avoid this behavior?


问:
Java Quiz classes issue
I am new with Java. I am trying to create a project Quiz.
My Main class, makes user to choose between 4 categories. He has to enter a number.

```<code>public class Quizeto {

    public static void main(String[] args) {
        System.out.println("1. Αθλητικά\t 2. Μουσική\n3. Ταινίες\t 4. Διάφορα\n");
        System.out.println("Διάλεξε κατηγορία: ");
</code>```

After he enters his choice and then I call if statement.

```<code>Scanner reader = new Scanner(System.in);
        int n = reader.nextInt();
        if (n==1) {
</code>```

And now, I saw a guy making java android game, he created a new class with the questions. I did the same thing here about each category. How I can write the code, so if the user types "1" the "Αθλητικα" class opens? I know I can just type each question and with "if statement" to check if the option is correct or not, but I want to know if I can do this, with class function. Sorry for my bad english. Thanks for your time.

答:
Have a look at the java.lang.Class class. For examplet the following outputs 'foo':</p>

```<code>public static void main(String[] args) throws Throwable {
    Class clazz = Class.forName("java.lang.String");
    String str = (String) clazz.getConstructor(String.class).newInstance("foo");
    System.out.println(str);
}
</code>```

Title: Java Quiz classes issue

Body:
I am new with Java. I am trying to create a project Quiz.
My Main class, makes user to choose between 4 categories. He has to enter a number.

public class Quizeto {

    public static void main(String[] args) {
        System.out.println("1. Αθλητικά\t 2. Μουσική\n3. Ταινίες\t 4. Διάφορα\n");
        System.out.println("Διάλεξε κατηγορία: ");

After he enters his choice and then I call if statement.

Scanner reader = new Scanner(System.in);
        int n = reader.nextInt();
        if (n==1) {

And now, I saw a guy making java android game, he created a new class with the questions. I did the same thing here about each category. How I can write the code, so if the user types "1" the "Αθλητικα" class opens? I know I can just type each question and with "if statement" to check if the option is correct or not, but I want to know if I can do this, with class function. Sorry for my bad english. Thanks for your time.

Body:
Have a look at the java.lang.Class class. For examplet the following outputs 'foo':

public static void main(String[] args) throws Throwable {
    Class clazz = Class.forName("java.lang.String");
    String str = (String) clazz.getConstructor(String.class).newInstance("foo");
    System.out.println(str);
}


问:
Ruby on Rails: Array to Hash with (key, array of values)
Lets say I have an Array of content_categories (content_categories = user.content_categories)

I now want to add every element belonging to a certain categorie to content_categories with the category as a key and the the content-item IDs as elements of a set

In PHP something like this is possible:

```<code>foreach ($content_categories as $key => $category) {
  $contentsByCategoryIDArray = Category.getContents($category[id])
  $content_categories[$key][$contentsByCategoryIDArray]
}
</code>```

Is there an easy way in rails to do this?

Greets,

Nico

答:
```<code>Hash[content_categories.map{|cat|
  [cat, Category.get_contents(cat)]
}]
</code>```

Body:
Lets say I have an Array of content_categories (content_categories = user.content_categories)

I now want to add every element belonging to a certain categorie to content_categories with the category as a key and the the content-item IDs as elements of a set

In PHP something like this is possible:

foreach ($content_categories as $key => $category) {
  $contentsByCategoryIDArray = Category.getContents($category[id])
  $content_categories[$key][$contentsByCategoryIDArray]
}

Is there an easy way in rails to do this?

Greets,

Nico


问:
Scrapy yield response object in start_request method
I have a simple code in Scrapy -

```<code>def start_requests(self):
    response = scrapy.Request(url,callback=self.parse_response)
    response.meta['some_useful_params'] = some_useful_params
    yield response

def parse_respone(self,resposne):
    some_useful_params = response.meta['some_useful_params']
    do_parsing_stuff()
    if some_conditon==True:
        presponse = scrapy.Request(otherurl,callback=self.parse_response)
        presponse.meta['some_useful_params'] = some_useful_params
        yield presponse
    else:
        yield items
</code>```

The above program works fine for me, but I need to change it to something that will check if the html already exists for that page, then take that as html rather than making request to the website.

Now the code for that -

```<code>def start_requests(self):
    if html_exist:
        request = scrapy.Request(url)
        request.meta['some_useful_params'] = some_useful_params
        response = scrapy.http.Response(url,body=cached_html,request=request)
        #the below line doesn't call the method parse_response
        self.parse_response(response)
    else:
        response = scrapy.Request(url,callback=self.parse_response)
        response.meta['some_useful_params'] = some_useful_params
        yield response

def parse_respone(self,resposne):
    some_useful_params = response.meta['some_useful_params']
    do_parsing_stuff()
    if some_conditon==True:
        if html_exist:
            request = scrapy.Request(url)
            request.meta['some_useful_params'] = some_useful_params
            presponse = scrapy.http.Response(url,body=cached_html,request=request)
            #the below line doesn't call the method parse_response
            self.parse_response(presponse)
        else:
            presponse = scrapy.Request(otherurl,callback=self.parse_response)
            presponse.meta['some_useful_params'] = some_useful_params
            yield presponse
    else:
        yield items
</code>```

The problem I am facing is in the second code, if html exits, call to parse_response method does not happen.

Although I don't understand the reason completely but I think it is something related to Python generators, how can I resolve this issue.?

答:
you have to yield the items or requests, not just call the method:

```<code>for item_or_request in self.parse_response(response):
    yield item_or_request
</code>```

Body:
I have a simple code in Scrapy -

def start_requests(self):
    response = scrapy.Request(url,callback=self.parse_response)
    response.meta['some_useful_params'] = some_useful_params
    yield response

def parse_respone(self,resposne):
    some_useful_params = response.meta['some_useful_params']
    do_parsing_stuff()
    if some_conditon==True:
        presponse = scrapy.Request(otherurl,callback=self.parse_response)
        presponse.meta['some_useful_params'] = some_useful_params
        yield presponse
    else:
        yield items

The above program works fine for me, but I need to change it to something that will check if the html already exists for that page, then take that as html rather than making request to the website.

Now the code for that -

def start_requests(self):
    if html_exist:
        request = scrapy.Request(url)
        request.meta['some_useful_params'] = some_useful_params
        response = scrapy.http.Response(url,body=cached_html,request=request)
        #the below line doesn't call the method parse_response
        self.parse_response(response)
    else:
        response = scrapy.Request(url,callback=self.parse_response)
        response.meta['some_useful_params'] = some_useful_params
        yield response

def parse_respone(self,resposne):
    some_useful_params = response.meta['some_useful_params']
    do_parsing_stuff()
    if some_conditon==True:
        if html_exist:
            request = scrapy.Request(url)
            request.meta['some_useful_params'] = some_useful_params
            presponse = scrapy.http.Response(url,body=cached_html,request=request)
            #the below line doesn't call the method parse_response
            self.parse_response(presponse)
        else:
            presponse = scrapy.Request(otherurl,callback=self.parse_response)
            presponse.meta['some_useful_params'] = some_useful_params
            yield presponse
    else:
        yield items

The problem I am facing is in the second code, if html exits, call to parse_response method does not happen.

Although I don't understand the reason completely but I think it is something related to Python generators, how can I resolve this issue.?

Body:
you have to yield the items or requests, not just call the method:

for item_or_request in self.parse_response(response):
    yield item_or_request


问:
Exception in thread "main" org.hibernate.HibernateException:
Hi i am trying simple hibernate program but not able to fix this issue can anyone help

UserDetails.class

```<code>package org.pavan.dto;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class UserDetails {
@Id
private int userId;
private String userName;
public int getUserId() {
    return userId;
}
public void setUserId(int userId) {
    this.userId = userId;
}
public String getUserName() {
    return userName;
}
public void setUserName(String userName) {
    this.userName = userName;
}
</code>```

}

HibernateTest.java

package org.pavan.hibernate;

```<code>import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.pavan.dto.UserDetails;

public class HibernateTest {

public static void main(String[] args) {
    UserDetails user =new UserDetails();
    user.setUserId(1);
    user.setUserName("First User");
    SessionFactory sessionFactory = new Configuration().configure("C:\\Users\\pavan\\workspace\\FirstHibernateProject\\src\\hibernate.cfg.xml").buildSessionFactory();
    Session session=sessionFactory.openSession();
    session.beginTransaction();
    session.save(user);
    session.getTransaction().commit();

    }

}
</code>```

hibernate.cfg.xml

```<code><?xml version='1.0' encoding='utf-8'?>
<!--
</code>```

~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html.
  -->

```<code><session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/hibernatedb</property>
    <property name="connection.username">root</property>
    <property name="connection.password">admin</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <!-- Disable the second-level cache  -->
    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>

    <!-- Names the annotated entity class -->
    <mapping class="org.pavan.dto.UserDetails"/>

</session-factory>
</code>```

Error:

INFO: Configuration resource: C:\Users\pavan\workspace\FirstHibernateProject\src\hibernate.cfg.xml
Exception in thread "main" org.hibernate.HibernateException: C:\Users\pavan\workspace\FirstHibernateProject\src\hibernate.cfg.xml not found
    at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
    at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1405)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1427)
    at org.pavan.hibernate.HibernateTest.main(HibernateTest.java:14)

Can anyone help please

thanks in advance

答:
Some how it's not getting the hibernate.cfg.xml in your path,

```<code>String path = String.format("%s/%s",System.getProperty("user.dir"), "src/hibernate.cfg.xml");

SessionFactory sessionFactory = new Configuration().configure(path).buildSessionFactory();
</code>```

or you can try it -> add a resources folder inside src and

marked as resources directory

add move your hibernate.cfg.xml inside it,

```<code> SessionFactory sessionFactory =   return new Configuration().configure().buildSessionFactory();
</code>```

Body:
Hi i am trying simple hibernate program but not able to fix this issue can anyone help

UserDetails.class

package org.pavan.dto;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class UserDetails {
@Id
private int userId;
private String userName;
public int getUserId() {
    return userId;
}
public void setUserId(int userId) {
    this.userId = userId;
}
public String getUserName() {
    return userName;
}
public void setUserName(String userName) {
    this.userName = userName;
}

}

HibernateTest.java

package org.pavan.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.pavan.dto.UserDetails;

public class HibernateTest {

public static void main(String[] args) {
    UserDetails user =new UserDetails();
    user.setUserId(1);
    user.setUserName("First User");
    SessionFactory sessionFactory = new Configuration().configure("C:\\Users\\pavan\\workspace\\FirstHibernateProject\\src\\hibernate.cfg.xml").buildSessionFactory();
    Session session=sessionFactory.openSession();
    session.beginTransaction();
    session.save(user);
    session.getTransaction().commit();

    }

}

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>

<session-factory>

    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/hibernatedb</property>
    <property name="connection.username">root</property>
    <property name="connection.password">admin</property>

    <property name="connection.pool_size">1</property>

    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <property name="show_sql">true</property>

    <property name="hbm2ddl.auto">create</property>

    <mapping class="org.pavan.dto.UserDetails"/>

</session-factory>

Error:

INFO: Configuration resource: C:\Users\pavan\workspace\FirstHibernateProject\src\hibernate.cfg.xml
Exception in thread "main" org.hibernate.HibernateException: C:\Users\pavan\workspace\FirstHibernateProject\src\hibernate.cfg.xml not found
    at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
    at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1405)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1427)
    at org.pavan.hibernate.HibernateTest.main(HibernateTest.java:14)

Can anyone help please

thanks in advance

Body:
Some how it's not getting the hibernate.cfg.xml in your path,

String path = String.format("%s/%s",System.getProperty("user.dir"), "src/hibernate.cfg.xml");

SessionFactory sessionFactory = new Configuration().configure(path).buildSessionFactory();

or you can try it -> add a resources folder inside src and

marked as resources directory

add move your hibernate.cfg.xml inside it,

 SessionFactory sessionFactory =   return new Configuration().configure().buildSessionFactory();


问:
Client certificate: Could not establish secure channel for SSL/TLS with authority (Again!)
Sorry for asking this question, but I couldn't find any answer for my case on Stack.

I developed a client application that talks to an external SOAP api using WCF. To authenticate, the application uses a client certificate. (The client certificate as been installed on the server). When I test on my local machine everything works fine.

The problems occurs when I deploy the application on IIS (on a EC2). The apps cannot communicate with the SOAP api anymore. This is the error:

```<code>"Could not establish secure channel for SSL/TLS with authority".
</code>```

I installed the certificate in Personnal store of both Current User and Local Computer location. When I try to hit the SOAP api with the browser it works (get on wsdl file which also need the client certificate).

Note: the certificate is not self signed. It was created by an authorized CA.

Thanks for the help

答: I changed the Identity of the application pool of IIS to LocalSystem and restarted the app. I think it was a permission problem. If someone can explain me why it fixed the problem I would accept her/his answer.</p>

Body:
Sorry for asking this question, but I couldn't find any answer for my case on Stack.

I developed a client application that talks to an external SOAP api using WCF. To authenticate, the application uses a client certificate. (The client certificate as been installed on the server). When I test on my local machine everything works fine.

The problems occurs when I deploy the application on IIS (on a EC2). The apps cannot communicate with the SOAP api anymore. This is the error:

"Could not establish secure channel for SSL/TLS with authority".

I installed the certificate in Personnal store of both Current User and Local Computer location. When I try to hit the SOAP api with the browser it works (get on wsdl file which also need the client certificate).

Note: the certificate is not self signed. It was created by an authorized CA.

Thanks for the help


问:
Convert text Amount to decimal - ssis
In my source file I have amount column with values

eg:

```<code>Amount
380.00
2,435.00
</code>```

So when I try to load this in to the destination, I wish to convert the value in to int(12).

How to do this conversion by removing . and , from the text and load in to the destination.

答:
You can achieve this using a script component

Add a Script Component

Mark amount as input column

Add an output column of type integer (ex outAmount)

Add the following code: (using vb.net) and asuming that amount column is string

```<code>If Not Row.Amount_IsNull AndAlso
   Not String.IsNullOrEmpty(Row.Amount) Then

    Row.outAmount = CInt(Row.amount.Replace(".","").Replace(",",""))

Else

    Row.outAmount _IsNull = True

End If
</code>```

Title: Convert text Amount to decimal - ssis

Body:
In my source file I have amount column with values

eg:

Amount
380.00
2,435.00

So when I try to load this in to the destination, I wish to convert the value in to int(12).

How to do this conversion by removing . and , from the text and load in to the destination.

Body:
You can achieve this using a script component

Add a Script Component

Mark amount as input column

Add an output column of type integer (ex outAmount)

Add the following code: (using vb.net) and asuming that amount column is string

If Not Row.Amount_IsNull AndAlso
   Not String.IsNullOrEmpty(Row.Amount) Then

    Row.outAmount = CInt(Row.amount.Replace(".","").Replace(",",""))

Else

    Row.outAmount _IsNull = True

End If


问:
aligned_alloc memory block in a copy assignment constructor crashes while being freed
I am maintaining some legacy code which was missing a copy assignment constructor in a managed Aligned Pointer class. I added one as follows (simplified view):

```<code>#include <iostream>
#include <cstring>
#include <stdlib.h>

template <class T, unsigned AlignB>
class AlignedPtr {
private:
    T *mpBlock;
    unsigned mBlkSize;
public:
    // Size specific Ctor
    AlignedPtr(unsigned uNum) :
    mpBlock(static_cast<T*>  (aligned_alloc(uNum*sizeof(T),  AlignB))),
    mBlkSize(uNum) {}
    // Default, empty Ctor
    AlignedPtr(void) : mpBlock(nullptr), mBlkSize(0) {}
    // Copy Assignment Ctor
    AlignedPtr& operator=(const AlignedPtr& x)
    {
        T *mpNewBlock(static_cast<T*>(aligned_alloc(x.mBlkSize*sizeof(T), AlignB)));
        for (size_t index=0; index < x.mBlkSize; index++) {
            mpNewBlock[index] = x.mpBlock[index];
        }
        free(mpBlock);
        mpBlock  = mpNewBlock;
        mBlkSize = x.mBlkSize;
        return *this;
    }
    // Destroy managed pointer
    ~AlignedPtr() {
        free(mpBlock);
    }
};

int main(int argc, char *argv[])
{

    AlignedPtr<float, 16> first_ptr;
    std::cout << "Pointer Initialized" << std::endl;

    first_ptr = AlignedPtr<float, 16>(8);
    std::cout << "Pointer Re-initialized" << std::endl;

    return 0;
}
</code>```

My expectation was that the program will terminate normally, however I saw AlignedPtr Dtor fail when first_ptr goes out of scope (main termination).
I compile above without any optimizations as:

```<code>g++ -std=c++11 -g aligned_alloc_bug.cpp -o aab
</code>```

On a Ubuntu 14.04 with g++ 4.8.2 and get the following run-time error:

```<code>Pointer Initialized
Pointer Re-initialized
*** Error in `./aab': free(): invalid next size (fast): 0x0000000001cf9080 ***
Aborted (core dumped)
</code>```

Interestingly when I replace aligned_alloc with malloc or posix_memalign for that matter program terminates correctly. Is this a bug in aligned_alloc or am I missing something basic?

P.S: 1) I did a brief search for a gcc bug which returned false. 2) Advise to avoid managing raw pointers is acknowledged in advance but I would appreciate any help for the problem at hand.

答: The problem is you have two objects pointing to the same memory: the anonymous object and the first_ptr after the assignment operator completed have the same address. When their respective destructors get called..... you can probably guess what is going to happen.</p>

Body:
I am maintaining some legacy code which was missing a copy assignment constructor in a managed Aligned Pointer class. I added one as follows (simplified view):

#include <iostream>
#include <cstring>
#include <stdlib.h>

template <class T, unsigned AlignB>
class AlignedPtr {
private:
    T *mpBlock;
    unsigned mBlkSize;
public:
    // Size specific Ctor
    AlignedPtr(unsigned uNum) :
    mpBlock(static_cast<T*>  (aligned_alloc(uNum*sizeof(T),  AlignB))),
    mBlkSize(uNum) {}
    // Default, empty Ctor
    AlignedPtr(void) : mpBlock(nullptr), mBlkSize(0) {}
    // Copy Assignment Ctor
    AlignedPtr& operator=(const AlignedPtr& x)
    {
        T *mpNewBlock(static_cast<T*>(aligned_alloc(x.mBlkSize*sizeof(T), AlignB)));
        for (size_t index=0; index < x.mBlkSize; index++) {
            mpNewBlock[index] = x.mpBlock[index];
        }
        free(mpBlock);
        mpBlock  = mpNewBlock;
        mBlkSize = x.mBlkSize;
        return *this;
    }
    // Destroy managed pointer
    ~AlignedPtr() {
        free(mpBlock);
    }
};

int main(int argc, char *argv[])
{

    AlignedPtr<float, 16> first_ptr;
    std::cout << "Pointer Initialized" << std::endl;

    first_ptr = AlignedPtr<float, 16>(8);
    std::cout << "Pointer Re-initialized" << std::endl;

    return 0;
}

My expectation was that the program will terminate normally, however I saw AlignedPtr Dtor fail when first_ptr goes out of scope (main termination).
I compile above without any optimizations as:

g++ -std=c++11 -g aligned_alloc_bug.cpp -o aab

On a Ubuntu 14.04 with g++ 4.8.2 and get the following run-time error:

Pointer Initialized
Pointer Re-initialized
*** Error in `./aab': free(): invalid next size (fast): 0x0000000001cf9080 ***
Aborted (core dumped)

Interestingly when I replace aligned_alloc with malloc or posix_memalign for that matter program terminates correctly. Is this a bug in aligned_alloc or am I missing something basic?

P.S: 1) I did a brief search for a gcc bug which returned false. 2) Advise to avoid managing raw pointers is acknowledged in advance but I would appreciate any help for the problem at hand.


问:
What's The Best Way To Write Multi-Line Code Snippets In VS-Code?
In Sublime Text, multi-line code snippets can be defined with white-spaces in a snippet file.

But as far as I know, VS-Code needs a JSON entry. These require either:

Hard-breaks into a list of double-quoted strings, or

Soft-break a long string using line-breaks \n

This is inconvenient compared to the WYSIWYG approaches other IDEs provide out of the box.

Are there better ways for defining long-blocks of code?

答:
You can define the body of your snippet as an array of strings, each beginning on a new line.

Like this:

```<code>  "Create for loop":{
    "prefix": "mkfor",
    "body":[
      "for(int i = 0; i < 3; i++)",
      "{",
      "   //code goes here",
      "}"
    ],
   "description": "Creates a for loop"
  }
</code>```

or if you install Easy Snippet Maker extension, you can create your snippets by highlighting texts.

Body:
You can define the body of your snippet as an array of strings, each beginning on a new line.

Like this:

  "Create for loop":{
    "prefix": "mkfor",
    "body":[
      "for(int i = 0; i < 3; i++)",
      "{",
      "   //code goes here",
      "}"
    ],
   "description": "Creates a for loop"
  }

or if you install Easy Snippet Maker extension, you can create your snippets by highlighting texts.


问:
Flask "Error: The file/path provided does not appear to exist" although the file does exist
I use export FLASK_APP=flask_app and then do flask run but I get the error:

Error: The file/path provided (flask_app) does not appear to exist.  Please verify the path is correct.  If app is not on PYTHONPATH, ensure the extension is .py

However, the file does exist and is even in the present working directory. Using the complete path to the file does not work either.

答:
I see this error when I'm missing an import statement somewhere in my code. The fact that the actual import error isn't shown, in my view, is a bug, as described in @PDiracDelta's answer. (Update: It seems it will be fixed in Flask 0.13.)

A workaround that works for me is specifying the app at the command line. From the error message you've quoted, it looks like your app is called 'flask_app', so just type this:

```<code>python flask_app.py
</code>```

This won't actually run the app (unless it checks if __name__ == '__main__' or something), but it will show the import errors.

Body:
I see this error when I'm missing an import statement somewhere in my code. The fact that the actual import error isn't shown, in my view, is a bug, as described in @PDiracDelta's answer. (Update: It seems it will be fixed in Flask 0.13.)

A workaround that works for me is specifying the app at the command line. From the error message you've quoted, it looks like your app is called 'flask_app', so just type this:

python flask_app.py

This won't actually run the app (unless it checks if __name__ == '__main__' or something), but it will show the import errors.


问:
Manually handling auto increment in MySQL?
We have a products database that contains our inventory, that will be merging with a new (growing) catalog from another product source. Products from source 1 currently have IDs from 0 - 50k (every month 10-15 new products are added). Products from source 2 that hasn't been added to our inventory yet start at ID: 1000000+ on their side. I was thinking to maintain ease of integration and recognition of which product is coming from which catalog, that we manually handle auto incrementing the product id in our products table.

In our  before insert trigger, we would check for the following:

pseudocode:

```<code>if (product_source = 'internal_catalog') {
 new.id = SELECT max(id) + 1 FROM products where product_source = 'internal_catalog';
} else {
 new.id = new.original_product_id; -- original_product_id will always be unique and > 1000000;
}
</code>```

To me, this theoretically should work but obviously I'm worried about concurrency errors and collisions. From what I can see, the above trigger will lock the table so there shouldn't be any collisions. Are there any issues with the above approach?

答:
The pseudocode you showed will not lock the table, and will be susceptible to race conditions during concurrent inserts.

There is, in general, no way to do custom auto-increment behavior without locking the whole table, because to avoid those race conditions you have to block concurrent inserts.

The alternative is to use some external increment mechanism to generate new id values. For example, create a key in a memcached instance and use the atomic increment-and-get call to get new unique id values. Don't do this in your trigger, do it the application before you execute your INSERT.

But the best practice to forget about using the auto-increment as some kind of enumerated type. It's required to be unique—that's all. Not sequential or consecutive.

Body:
We have a products database that contains our inventory, that will be merging with a new (growing) catalog from another product source. Products from source 1 currently have IDs from 0 - 50k (every month 10-15 new products are added). Products from source 2 that hasn't been added to our inventory yet start at ID: 1000000+ on their side. I was thinking to maintain ease of integration and recognition of which product is coming from which catalog, that we manually handle auto incrementing the product id in our products table.

In our  before insert trigger, we would check for the following:

pseudocode:

if (product_source = 'internal_catalog') {
 new.id = SELECT max(id) + 1 FROM products where product_source = 'internal_catalog';
} else {
 new.id = new.original_product_id; -- original_product_id will always be unique and > 1000000;
}

To me, this theoretically should work but obviously I'm worried about concurrency errors and collisions. From what I can see, the above trigger will lock the table so there shouldn't be any collisions. Are there any issues with the above approach?


问:
Ubercart 1.0 add product kit to order without checkout
I want to give access to certain product kits during sign up process. I don't want user to go through checkout process. How it can be done?</p>

答:
This answer answers here might help.

You might want to look at something like

```<code>$order = uc_order_new($uid, 'post_checkout');
</code>```

Body:
This answer answers here might help.

You might want to look at something like

$order = uc_order_new($uid, 'post_checkout');


问:
How to correctly setup redirection with Python Requests for some corner-cases
Consider the following code snippet:

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import requests
from requests import exceptions

try:
    url=sys.argv[1]
except IndexError:
    print('No URL provided.')
    sys.exit(1)

print('\n--- {}\n'.format(url))

try:
    s = requests.Session()
    r = s.get(url)
except exceptions.TooManyRedirects as t:
    print('ERROR: {}'.format(t))
    r = s.get(url, allow_redirects=False)

print('-----------------------------')
print(r.status_code)
print(r.headers)
</code>```

The code takes a URL as input and tries to run a GET request on it.
I use the session object to manage Cookies over multiple requests etc.

Now my problem is, that I have a couple of URLs (mostly Tumblr), that will run in a infinite redirection loop and break after 30 attempts.

Example: http://ansgar-skoda.tumblr.com/post/96703389502

When I request this page with a browser or with

```<code>curl -v -L http://ansgar-skoda.tumblr.com/post/96703389502
</code>```

the redirection works and I'll receive the correct webpage.
It seems I am not setting up this correctly. When studying the Requests docu, I saw that the option allow_redirects is True by default. The user-agent doesn't seem to affect the result in this case.

Any hints how to proceed here?
Thanks in advance.

答:
As of today, this is a bug in Requests
https://github.com/kennethreitz/requests/issues/3949</p>

Body:
Consider the following code snippet:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import requests
from requests import exceptions

try:
    url=sys.argv[1]
except IndexError:
    print('No URL provided.')
    sys.exit(1)

print('\n--- {}\n'.format(url))

try:
    s = requests.Session()
    r = s.get(url)
except exceptions.TooManyRedirects as t:
    print('ERROR: {}'.format(t))
    r = s.get(url, allow_redirects=False)

print('-----------------------------')
print(r.status_code)
print(r.headers)

The code takes a URL as input and tries to run a GET request on it.
I use the session object to manage Cookies over multiple requests etc.

Now my problem is, that I have a couple of URLs (mostly Tumblr), that will run in a infinite redirection loop and break after 30 attempts.

Example: http://ansgar-skoda.tumblr.com/post/96703389502

When I request this page with a browser or with

curl -v -L http://ansgar-skoda.tumblr.com/post/96703389502

the redirection works and I'll receive the correct webpage.
It seems I am not setting up this correctly. When studying the Requests docu, I saw that the option allow_redirects is True by default. The user-agent doesn't seem to affect the result in this case.

Any hints how to proceed here?
Thanks in advance.


问:
Simple file writing with ostream_iterator creates file, but doesn't write
I have a really simple code to create a text file called "Input.txt", and write to it using ostream_iterator:

```<code>using namespace std;

int main()
{
    ofstream os{ "Input.txt" };
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++)
    {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);

    system("PAUSE");
    return 0;
}
</code>```

The code above creates a "Input.txt", but there is nothing written to it. Am I missing something really obvious and fundamental?

答:
You are not flushing the stream to disk before calling system().

You can explicitly flush() or close() the stream:

```<code>int main() {
    ofstream os{ "Input.txt" };
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++) {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);

    os.close();

    system("PAUSE");
    return 0;
}
</code>```

Or you can put scoping braces around the stream so it goes out of scope sooner.

```<code>int main() {
    {
    ofstream os{ "Input.txt" };
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++) {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);
    }

    system("PAUSE");
    return 0;
}
</code>```

Body:
I have a really simple code to create a text file called "Input.txt", and write to it using ostream_iterator:

using namespace std;

int main()
{
    ofstream os{ "Input.txt" };
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++)
    {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);

    system("PAUSE");
    return 0;
}

The code above creates a "Input.txt", but there is nothing written to it. Am I missing something really obvious and fundamental?

Body:
You are not flushing the stream to disk before calling system().

You can explicitly flush() or close() the stream:

int main() {
    ofstream os{ "Input.txt" };
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++) {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);

    os.close();

    system("PAUSE");
    return 0;
}

Or you can put scoping braces around the stream so it goes out of scope sooner.

int main() {
    {
    ofstream os{ "Input.txt" };
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++) {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);
    }

    system("PAUSE");
    return 0;
}


问: Are

Title: Are <script>'s not in <head> ok?

Body:
I have had this question niggling at the curious bit of my mind for a while now and I thought I'd ask your collective expertise for an answer to this question.

To elaborate on the title, say I have this:

alert("Some JS outside ");

Outside the  tags of my HTML file. My question is whether it's ok to do this or not, and how much it is used like this.

My instincts tell me it's ok - I reckon browsers look through all HTML for

Body: Yes. Its OK. Infact, very often it is necessary. In many cases, you may have some long-loading (read: large download) javascript that is not critical to the page, so you want the rest of your page content to load first, so you put the <script> for that javascript at the bottom of the <body> section.


问:
Pause Azure Function until 12am next day
I know you can add spending limit for your azure functions per month, But I need to find a way to limit number of executions for an Azure function per day. The Function I am developing is calling a 3rd party API where we have a limit of 25,000 calls per day. When we reach that limit we get a response "LIMIT_REACH". I want to be able to pause the azure function execution until 12AM the next day. I am using a storage Queue to trigger the Azure Function. I know an option is in the function.json. I can update ["disabled": false] But i will need to set it through programatically. Then I will have to trigger a process to turn on the function again. </p>

答:
Unfortunately there are not any apis to programmatically enable/disable an Azure function at present.

However, you could achieve this in a few ways:

First, upon receiving LIMIT_REACH, have the queue function modify its own function.json to set disabled true - this will trigger a restart after all currently executing functions finish.

Then, at the time you wish to re-enable processing, run a different function to update disabled: true to false:

Use a timer trigger with a schedule to run at midnight daily (0 0 0 * * *)

or

Use another queue and set the visibility time to schedule when the message becomes visible, upon which time you re-enable the function.


问:
Cmd batch file executes only partly when using task scheduler
I have task scheduled a batch file to run at midnight.

It has highest privileges,

It is ran as administrator with a stored password, independent of whether the user is logged in or not

The environment is set to windows 2012

The batch file's folder is used when launching.

Batch file location and start folder respectively:

```<code>c:\ip\ip1.bat
c:\ip\
</code>```

Batch file contents:

```<code>taskkill /im python.exe /f >nul 2>&1
taskkill /im chrome.exe /f >nul 2>&1

timeout 5
netsh interface ipv4 add address "Ethernet" 104.122.112.106 255.255.255.0

timeout 5
::netsh interface ipv4 delete address "Ethernet" 104.122.112.106
netsh interface ipv4 delete address "Ethernet" 104.122.112.107
netsh interface ipv4 delete address "Ethernet" 104.122.112.108

timeout 40
start /min "" python.exe C:\Users\Administrator\Desktop\host\server2.py

timeout 10
start /min "" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="D:\chrome1" --js-flags="--expose-gc"
</code>```

The above batch works perfectly if launched manually.

However, whenever the above file is launched by the task scheduler, it is being executed only partially.

What happens is that both python and chrome processes are killed but not restarted.

Nevertheless, the task scheduler reports that last run result was successful (0x0).

I highly appreciate your help and suggestions.

EDIT:

ACTUALLY, both processes are launched!

However they are ran in the background, that is, I see them in task manager but I cannot interact with them in any way.

答:
Setting option "Run only when user is logged on" actually solved the problem.

I've been trying to avoid using this option because I use RDP to connect to the server and it's not possible to stay connected 24/7. Nevertheless, when disconnecting my RDP session, the "administrator" user still remains logged and the task scheduler executes the program regardless.

Yet another problem remains, the start command ignores the /min switch, and the launched processes are not minimized to taskbar.

I have posted another question: Cmd start command ignores /min switch

Body:
I have task scheduled a batch file to run at midnight.

It has highest privileges,

It is ran as administrator with a stored password, independent of whether the user is logged in or not

The environment is set to windows 2012

The batch file's folder is used when launching.

Batch file location and start folder respectively:

c:\ip\ip1.bat
c:\ip\

Batch file contents:

taskkill /im python.exe /f >nul 2>&1
taskkill /im chrome.exe /f >nul 2>&1

timeout 5
netsh interface ipv4 add address "Ethernet" 104.122.112.106 255.255.255.0

timeout 5
::netsh interface ipv4 delete address "Ethernet" 104.122.112.106
netsh interface ipv4 delete address "Ethernet" 104.122.112.107
netsh interface ipv4 delete address "Ethernet" 104.122.112.108

timeout 40
start /min "" python.exe C:\Users\Administrator\Desktop\host\server2.py

timeout 10
start /min "" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="D:\chrome1" --js-flags="--expose-gc"

The above batch works perfectly if launched manually.

However, whenever the above file is launched by the task scheduler, it is being executed only partially.

What happens is that both python and chrome processes are killed but not restarted.

Nevertheless, the task scheduler reports that last run result was successful (0x0).

I highly appreciate your help and suggestions.

EDIT:

ACTUALLY, both processes are launched!

However they are ran in the background, that is, I see them in task manager but I cannot interact with them in any way.


问:
UML Activity Diagram :loop on decision node
I am learning UML and I would like to know if it is possible to loop on the decision node.
Because in my cockburn I have :

3-Enter with ticket

3a1-Enter with card
3a2-Failure: return to 1

If it is possible, how can I do it with Visual Paradigm?
Thanks!

答:
You can't do that in UML. A decision node is just for evaluation of a condition previously set in an action. </p>

<p>From your scenario it's not obvious how you want to establish a loop anyway. I would guess that the case "none selected" needs to be modeled. Just make your action above not deliver anything else but the ticket/card conditions. </p>

Body:
You can't do that in UML. A decision node is just for evaluation of a condition previously set in an action.

From your scenario it's not obvious how you want to establish a loop anyway. I would guess that the case "none selected" needs to be modeled. Just make your action above not deliver anything else but the ticket/card conditions.


问:
ORACLE SQL PASSWORD FUNCTION
Need to create a function that verifies a password (more than 5 characters, different from the previous one, it isn't neither "password" nor "123456")
I tried this but i get errors</p>

```<code>CREATE OR REPLACE FUNCTION my_verification_function (
    username VARCHAR2,
    password VARCHAR2,
    old_password VARCHAR2)
RETURN BOOLEAN IS
BEGIN
    IF LENGTH(password) < 6 THEN RETURN FALSE;
    ELSE IF (password = "password" OR password = '123' OR password = old_password) THEN RETURN FALSE
    ELSE RETURN TRUE;
    END IF;
END my_verification_function;$
</code>```

答:
It should be done like this:

```<code>CREATE OR REPLACE FUNCTION my_verification_function (
   username VARCHAR2, password VARCHAR2, old_password VARCHAR2)
RETURN BOOLEAN AS
BEGIN

   IF LENGTH(password) < 6 THEN
      RETURN FALSE;
   ELSIF (password = "password" OR password = '123' OR password = old_password) THEN
      RETURN FALSE
   ELSE
      RETURN TRUE;
   END IF;
END my_verification_function;
/

alter profile default limit password_verify_function my_verification_function;
</code>```

Parameter name USERNAEM and PASSWORD seems to be no problem, since Oracle  provided default function (located in ORACLE_BASE/ORACLE_HOME/RDBMS/ADMIN/UTLPWDMG.SQL) uses them also.

Title: ORACLE SQL PASSWORD FUNCTION

Body:
Need to create a function that verifies a password (more than 5 characters, different from the previous one, it isn't neither "password" nor "123456")
I tried this but i get errors

CREATE OR REPLACE FUNCTION my_verification_function (
    username VARCHAR2,
    password VARCHAR2,
    old_password VARCHAR2)
RETURN BOOLEAN IS
BEGIN
    IF LENGTH(password) < 6 THEN RETURN FALSE;
    ELSE IF (password = "password" OR password = '123' OR password = old_password) THEN RETURN FALSE
    ELSE RETURN TRUE;
    END IF;
END my_verification_function;$

Body:
It should be done like this:

CREATE OR REPLACE FUNCTION my_verification_function (
   username VARCHAR2, password VARCHAR2, old_password VARCHAR2)
RETURN BOOLEAN AS
BEGIN

   IF LENGTH(password) < 6 THEN
      RETURN FALSE;
   ELSIF (password = "password" OR password = '123' OR password = old_password) THEN
      RETURN FALSE
   ELSE
      RETURN TRUE;
   END IF;
END my_verification_function;
/

alter profile default limit password_verify_function my_verification_function;

Parameter name USERNAEM and PASSWORD seems to be no problem, since Oracle  provided default function (located in ORACLE_BASE/ORACLE_HOME/RDBMS/ADMIN/UTLPWDMG.SQL) uses them also.


问:
How to filter data in firebase?
I'm newbie in firebase database.

I make some relations key in firebase like this:

chats/conversation_key

members/conversation_key/array_of_user_uid

messages/conversation_key/array_of_messages

The question is: How to find members key if i already know user uid?

IE: I want to find -KgePX_tcbDz9fU-kAZT in members if i already have user uid jEIAfqDpJjWWUUXaecSmMk3U7vu1

答:
```<code>var firebaseRef = firebase.database().ref("members");
firebaseRef.orderByChild(userKey).equalTo(true/false).on("child_added", function(Data){
console.log(Data.val(), Data.key);
}
</code>```

i am assuming that you are already aware of on or once method and child events also, if not then read them(documentation), will help you a lot, otherwise above code will do your job

Title: How to filter data in firebase?

Body:
var firebaseRef = firebase.database().ref("members");
firebaseRef.orderByChild(userKey).equalTo(true/false).on("child_added", function(Data){
console.log(Data.val(), Data.key);
}

i am assuming that you are already aware of on or once method and child events also, if not then read them(documentation), will help you a lot, otherwise above code will do your job


问:
Bobril framework with different router
I try to use bobril with no hash router, with fully history, for example /about, not #/about. Bobril do not know it, but should be possible use different route, for example from Reactjs or the others.
For compilation I'm using Bobril build.

Can you help me, how to do it? Thank you for your time.

答:
It will need some nontrivial amount of changes in bobril-build to add feature that it will respond with index.html instead of 404 and also all generated links inside index.html will have to be absolute. I don't have time to add this feature myself atleast next 2 weeks.
Than any history based router independent of view library will work. Actual code to route to specific "page" could look like this:

```<code>b.init(() => <AboutPage />);
</code>```

or without TSX:

```<code>b.init(() => AboutPage());
</code>```

Title: Bobril framework with different router

Body:
It will need some nontrivial amount of changes in bobril-build to add feature that it will respond with index.html instead of 404 and also all generated links inside index.html will have to be absolute. I don't have time to add this feature myself atleast next 2 weeks.
Than any history based router independent of view library will work. Actual code to route to specific "page" could look like this:

b.init(() => <AboutPage />);

or without TSX:

b.init(() => AboutPage());


问:
Templating language for both Ruby and client-side JS
Is there a templating language that has both server-side ruby (pref. rails) and JS renderer?

Here is why this would be useful: Consider you want to display a big list of songs. You render the first 50 and a "show more" button.

"Show more" would link to the next 50 songs or would load those with AJAX if JavaScript is enabled.

The simple solution is to return a rendered piece of HTML from the server, but consider how nice would it be songs were returned as JSON and then were rendered using the same template on the client side.

答:
Node.js offers the appeal of using javascript on both the server and client side.  If you are looking for something more ruby-on-rails like, then check out express.js which is a web-framework built on Node.js. Both of these are server-side frameworks but they offer libraries which can be used on the client side.

Something to keep in mind is that if you are rendering views from JSON data on the client side then you will need to have the client load the javascript libraries to perform these operations and then render the views - which may be a costlier operation.  That said, if your view is simple enough, you can always write a simple javascript function of your own to render your JSON data rather than relying on an entirely new framework and view renderer.