问:
How to deploy React/Laravel project?
I use Laravel framework as Restful API server, and React as SPA client render and for routing i have used react create app kit, I build React project. I get app.js and app.css files by type npm run build.

How to use this file with Laravel?

How use react routing?

How to deploy it correctly?

答:
I can answer your questions and have an example.

Basically, to use Laravel as an API backend for a React (or JS) Single-Page application:

setup a Laravel project - it's the backend, so setup it and the routes you want

1.a Suggestion Make your URLs for the SPI separate/distinct from normal URLs your Laravel app itself might use for page requests or other things (such as "/api/...").

1.b Laravel (5+ or so, my example is 5.1) comes packaged with a Gulp/build tool called "Elixir". It's setup to look for things like scripts files and views in the resources/... directory, so I suggest putting your scripts in some place like resources/assets/scripts/app.js or something.

1.c (Build Process) Assuming you put your React scripts in resources/assets/script, then when you run "gulp" and the Elixir task runs for building the app, it will put the bundled, app.js file into public/js/app.js -- Laravel views by default think of the public/ directory as their root directory, so you can reference that built file in your index page as "js/app.js".

1.d If Gulp or Elixir are unfamiliar to you, I encourage you to give this page a read for an overview:

https://laravel.com/docs/5.1/elixir

setup the Routes for Laravel, your Index page and the API stuff. I suggest routing '/' and all NON-API (or known) routes to just make the Index page View, where we'll load the app.js ReactJS application file.

2.a It's worth noting that in my example, currently, I have not implemented the React Router, so I'm leaving all React routes alone for the moment. I'm assuming this is something you know since your questions seems to be "how to make the Backend be Laravel".

```<code>Route::get('/', function () { return View::make('pages.index'); });

Route::group(['prefix' => 'api'], function () {
    Route::get('tasks', 'TodosController@index');
});
</code>```

2.b Setup the Routes to map requests to controller actions, where you can customize your response. For example, you can respond with JSON for a JSON API:

TodosController@index

```<code>$current_tasks = array(
  array("id" => "00001", "task" => "Wake up", "complete" => true),
  array("id" => "00002", "task" => "Eat breakfast with coffee power", "complete" => true),
  array("id" => "00003", "task" => "Go to laptop", "complete" => true),
  array("id" => "00004", "task" => "Finish React + Laravel Example app", "complete" => false),
  array("id" => "00005", "task" => "Respond on StackOverflow", "complete" => false)
);

return response()->json($current_tasks);
</code>```

As far as deployment goes, you'll probably need to build the code (my example does) and load the built version of the code into your production Index page or wherever. You'll also deploy it overall as a laravel app -- you want Laravel seeing the Routes first externally and want React to handle it's own URLs and routes. This way, say you expand the SPA but want the same backend, you just add routes to your Laravel app as exceptions/overrides in the routes file.

resources/pages/index.blade.php

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>BLaravel 5.1 + ReactJS Single-Page App</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
    <link rel="stylesheet" href="css/app.css" />

    <!-- BACKUP SCRIPT CNDS, for React -->
    <!-- <script src="https://unpkg.com/react@15/dist/react.js"></script> -->
    <!-- <script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script> -->

  </head>
  <body>

    <!-- Container for React App -->
    <div class="container" id="react-app-container"></div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

    <script src="js/app.js"></script>

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

Because there's (as far as I know) no Plnkr for this sort of thing, I made a local development version of Laravel + React to illustrate my way of making the kind of app you seem to be asking for. It's currently hosted on my GitHub account, so feel free to clone it and follow the README and use it if it helps, or ask for edits/help/clarification.

https://github.com/b-malone/Laravel5-ReactJS-Boilerplate.git

Build/Setup Commands (Reference)

```<code>git clone ... [TEST/] && cd into [TEST/]
composer install
npm install
cp .env.example .env
gulp
php artisan serve
visit http://localhost:8000
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to deploy React/Laravel project?

Body:
I can answer your questions and have an example.

Basically, to use Laravel as an API backend for a React (or JS) Single-Page application:

setup a Laravel project - it's the backend, so setup it and the routes you want

1.a Suggestion Make your URLs for the SPI separate/distinct from normal URLs your Laravel app itself might use for page requests or other things (such as "/api/...").

1.b Laravel (5+ or so, my example is 5.1) comes packaged with a Gulp/build tool called "Elixir". It's setup to look for things like scripts files and views in the resources/... directory, so I suggest putting your scripts in some place like resources/assets/scripts/app.js or something.

1.c (Build Process) Assuming you put your React scripts in resources/assets/script, then when you run "gulp" and the Elixir task runs for building the app, it will put the bundled, app.js file into public/js/app.js -- Laravel views by default think of the public/ directory as their root directory, so you can reference that built file in your index page as "js/app.js".

1.d If Gulp or Elixir are unfamiliar to you, I encourage you to give this page a read for an overview:

https://laravel.com/docs/5.1/elixir

setup the Routes for Laravel, your Index page and the API stuff. I suggest routing '/' and all NON-API (or known) routes to just make the Index page View, where we'll load the app.js ReactJS application file.

2.a It's worth noting that in my example, currently, I have not implemented the React Router, so I'm leaving all React routes alone for the moment. I'm assuming this is something you know since your questions seems to be "how to make the Backend be Laravel".

Route::get('/', function () { return View::make('pages.index'); });

Route::group(['prefix' => 'api'], function () {
    Route::get('tasks', 'TodosController@index');
});

2.b Setup the Routes to map requests to controller actions, where you can customize your response. For example, you can respond with JSON for a JSON API:

TodosController@index

$current_tasks = array(
  array("id" => "00001", "task" => "Wake up", "complete" => true),
  array("id" => "00002", "task" => "Eat breakfast with coffee power", "complete" => true),
  array("id" => "00003", "task" => "Go to laptop", "complete" => true),
  array("id" => "00004", "task" => "Finish React + Laravel Example app", "complete" => false),
  array("id" => "00005", "task" => "Respond on StackOverflow", "complete" => false)
);

return response()->json($current_tasks);

As far as deployment goes, you'll probably need to build the code (my example does) and load the built version of the code into your production Index page or wherever. You'll also deploy it overall as a laravel app -- you want Laravel seeing the Routes first externally and want React to handle it's own URLs and routes. This way, say you expand the SPA but want the same backend, you just add routes to your Laravel app as exceptions/overrides in the routes file.

resources/pages/index.blade.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>BLaravel 5.1 + ReactJS Single-Page App</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
    <link rel="stylesheet" href="css/app.css" />

    <!-- BACKUP SCRIPT CNDS, for React -->
    <!-- <script src="https://unpkg.com/react@15/dist/react.js"></script> -->
    <!-- <script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script> -->

  </head>
  <body>

    <!-- Container for React App -->
    <div class="container" id="react-app-container"></div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

    <script src="js/app.js"></script>

  </body>
</html>

Because there's (as far as I know) no Plnkr for this sort of thing, I made a local development version of Laravel + React to illustrate my way of making the kind of app you seem to be asking for. It's currently hosted on my GitHub account, so feel free to clone it and follow the README and use it if it helps, or ask for edits/help/clarification.

https://github.com/b-malone/Laravel5-ReactJS-Boilerplate.git

Build/Setup Commands (Reference)

git clone ... [TEST/] && cd into [TEST/]
composer install
npm install
cp .env.example .env
gulp
php artisan serve
visit http://localhost:8000


来源: stackexchange

问:
Office-js getFileAsync Support in Excel for Mac
Edit: Support appears to be added now. It is working in Excel for Mac.

I've implemented a function for Excel Online using Office.context.document.getFileAsync(...) and it works perfectly fine. Unfortunately, it appears that document.getFileAsync() is not supported in Excel for Mac. I missed this in my initial research into whether or not this approach would work.

I'm hoping I'm just doing something wrong. Would anyone be able to confirm that it is not supported in Excel for Mac 2016? And, if it isn't supported, give an idea of when or if it will ever be supported?

答: getFileAsync is being added to Mac right now and it should be available soon in the coming weeks. I don't have a definite timeline yet. I can update this thread once it makes it to the release candidate. </p>

ContentLicense: CC BY-SA 3.0


问:
How to populate a 2d array?
I have the following code that (nearly) populates a list of lists (I will call it a 2d array) in Python.

Instead of going up from 0-6 and repeating this 3 times, I want it to populate the array with numbers 0 - 20. Please see code below:

```<code>#matrix=[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
#print(matrix[1][2])

rows=3
columns=7

for i in range(rows):
  for j in range(columns):
    matrix=[j]
    i=i+1
    print(matrix,end="")
</code>```

The erroneous output is:

```<code>[0][1][2][3][4][5][6][0][1][2][3][4][5][6][0][1][2][3][4][5][6]
</code>```

I want the output to be:

```<code>[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
</code>```

答:
Use list comprehension. You want 3 rows so the base of the list comprehension is: [for y in range(rows)]. You want to have incrementing numbers starting with a number divisible by columns but starting from 1 so: range(columns*y+1,...) and you want to have columns range (7) so range(columns*y+1,columns+(columns*y+1)) and then turn that into a list.

```<code>rows=3
columns=7

matrix=[list(range(columns*y+1,columns+(columns*y+1))) for y in range(rows)]

print(matrix)
#outputs: [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 21]]
</code>```

Title: How to populate a 2d array?

Body:
I have the following code that (nearly) populates a list of lists (I will call it a 2d array) in Python.

Instead of going up from 0-6 and repeating this 3 times, I want it to populate the array with numbers 0 - 20. Please see code below:

#matrix=[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
#print(matrix[1][2])

rows=3
columns=7

for i in range(rows):
  for j in range(columns):
    matrix=[j]
    i=i+1
    print(matrix,end="")

The erroneous output is:

[0][1][2][3][4][5][6][0][1][2][3][4][5][6][0][1][2][3][4][5][6]

I want the output to be:

[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]

Body:
Use list comprehension. You want 3 rows so the base of the list comprehension is: [for y in range(rows)]. You want to have incrementing numbers starting with a number divisible by columns but starting from 1 so: range(columns*y+1,...) and you want to have columns range (7) so range(columns*y+1,columns+(columns*y+1)) and then turn that into a list.

rows=3
columns=7

matrix=[list(range(columns*y+1,columns+(columns*y+1))) for y in range(rows)]

print(matrix)
#outputs: [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 21]]


问:
What is proper syntax for mysqldb to avoid sql-injection?
I'm building a web application via the Flask framework, and am trying to use html forms to retrieve user data which will ultimately be stored in a mysqldb database.

I initially was passing my python variables into the sql command with a "%" instead of a "," like so:

```<code>    cursor.execute('INSERT INTO %s (column1,column2,column3,column4,column5) VALUES ("%s","%s","%s","%s","%s")' % (value1,value2,value3,value4,value5,value6)
</code>```

This method worked flawlessly, but then I wised up and realized while debugging my application that this is extremely susceptible to sql-injection and that I needed to use the "," instead.  So I changed the code to this:

```<code>    cursor.execute("INSERT INTO %s (column1,column2,column3,column4,column5) VALUES (%s,%s,%s,%s,%s)", (value1,value2,value3,value4,value5,value6)
</code>```

According to everything I've read on here, google, youtube, etc., this would've been a fix all method to my problem, which I'm sure it is, but a new sql syntax problem arises which I can't seem to fix no matter what I try to do.

My html form that this is all related to looks like this:

```<code>    <form method="post" enctype="multipart/form-data">
    <ul>
    <li><input type="text" name="title" placeholder="Title" required></li>
    <li><input type="text" name="location" placeholder="Location" required></li>
    <li><select name="activity" required>
                    <option value="Active">Active</option>
                    <option value="Food/Drink">Food/Drink</option>
                    <option value="Liesure">Liesure</option>
                    <option value="Night Life">Night Life</option>
                    <option value="Scenic">Scenic</option>
                    <option value="Other">Other</option>
                </select></li>
    <li><textarea id="post" name="content" placeholder="Write post here..." required></textarea></li>
    <li><input type="file" name="image" accept="image/*"></li>
</code>```

I'm using request.form["html_name"] in my python code to assign the user inputs to variables for all of the user inputs except for the image one, which I use request.files['image'] for instead. I'm not actually inserting the image into the database though,  only the route to where the image will be stored, in case that helps...

After all this is said and done, I attempt to input "test" for the title, "Pittsburgh" for the location, "Active" for activity, "test" for the content, and nothing for the image which defaults to "img/".  The error that is returned is as follows:

```<code>    "You have an error in your SQL syntax; check the manual that corresponds
    to your MySQL server version for the right syntax to use near
    ''TheTableName' (title,location,activity,content,photo) VALUES
    ('test','Pittsburgh','A' at line 1")
</code>```

As you can see, the content and photo seem to be completely ignored, and the activity only shows up as an "A".  Keep in mind that this all worked fine when I was using "%" instead of ",". I don't know exactly what changes between using one or the other, but apparently it's something cause now it's not working.  I'm wondering if it has something to do with the fact that the html input types are different throughout the form, but that might just be a coincidence. I'm not sure. All help is much appreciated, thanks.

答:
I figured out the problem.  Parameters cannot be passed for the table name in an sql statement when using the "," syntax. Therefore I had to break up the statements anywhere there was a table name and hard-code the table name variable into the statement like so:

```<code>    cursor.execute('INSERT INTO '+theTableName+' (column1,column2,column3,column4,column5) VALUES (%s,%s,%s,%s,%s)', (value1,value2,value3,value4,value5))
</code>```

To stay safe from sql injection attacks, it's now necessary to secure the user input for the table name... but that's another story and outside the scope of this question.

Body:
I'm building a web application via the Flask framework, and am trying to use html forms to retrieve user data which will ultimately be stored in a mysqldb database.

I initially was passing my python variables into the sql command with a "%" instead of a "," like so:

    cursor.execute('INSERT INTO %s (column1,column2,column3,column4,column5) VALUES ("%s","%s","%s","%s","%s")' % (value1,value2,value3,value4,value5,value6)

This method worked flawlessly, but then I wised up and realized while debugging my application that this is extremely susceptible to sql-injection and that I needed to use the "," instead.  So I changed the code to this:

    cursor.execute("INSERT INTO %s (column1,column2,column3,column4,column5) VALUES (%s,%s,%s,%s,%s)", (value1,value2,value3,value4,value5,value6)

According to everything I've read on here, google, youtube, etc., this would've been a fix all method to my problem, which I'm sure it is, but a new sql syntax problem arises which I can't seem to fix no matter what I try to do.

My html form that this is all related to looks like this:

    <form method="post" enctype="multipart/form-data">

<input type="text" name="title" placeholder="Title" required>

<input type="text" name="location" placeholder="Location" required>

<select name="activity" required>
                    <option value="Active">Active</option>
                    <option value="Food/Drink">Food/Drink</option>
                    <option value="Liesure">Liesure</option>
                    <option value="Night Life">Night Life</option>
                    <option value="Scenic">Scenic</option>
                    <option value="Other">Other</option>
                </select>

<textarea id="post" name="content" placeholder="Write post here..." required></textarea>

<input type="file" name="image" accept="image/*">

I'm using request.form["html_name"] in my python code to assign the user inputs to variables for all of the user inputs except for the image one, which I use request.files['image'] for instead. I'm not actually inserting the image into the database though,  only the route to where the image will be stored, in case that helps...

After all this is said and done, I attempt to input "test" for the title, "Pittsburgh" for the location, "Active" for activity, "test" for the content, and nothing for the image which defaults to "img/".  The error that is returned is as follows:

    "You have an error in your SQL syntax; check the manual that corresponds
    to your MySQL server version for the right syntax to use near
    ''TheTableName' (title,location,activity,content,photo) VALUES
    ('test','Pittsburgh','A' at line 1")

As you can see, the content and photo seem to be completely ignored, and the activity only shows up as an "A".  Keep in mind that this all worked fine when I was using "%" instead of ",". I don't know exactly what changes between using one or the other, but apparently it's something cause now it's not working.  I'm wondering if it has something to do with the fact that the html input types are different throughout the form, but that might just be a coincidence. I'm not sure. All help is much appreciated, thanks.

Body:
I figured out the problem.  Parameters cannot be passed for the table name in an sql statement when using the "," syntax. Therefore I had to break up the statements anywhere there was a table name and hard-code the table name variable into the statement like so:

    cursor.execute('INSERT INTO '+theTableName+' (column1,column2,column3,column4,column5) VALUES (%s,%s,%s,%s,%s)', (value1,value2,value3,value4,value5))

To stay safe from sql injection attacks, it's now necessary to secure the user input for the table name... but that's another story and outside the scope of this question.


问:
Python iteration on list
I've got this example

```<code>a='Datenfernübertragung remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission   Preferred|Forbidden|Forbidden|'
b = a.split('\t')
for item in b[1].split('|'):
  indeks=b[1].split('|').index(item)
  print(indeks)
</code>```

and it returns at this moment 0, 1, 2, 0 which are indexes of remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission but why it return to index 0, instead of printing index 3?

Thanks

答:
```<code>Python 3.4.3 (default, Nov 17 2016, 01:11:57)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a='Datenfernübertragung remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission   Preferred|Forbidden|Forbidden|'
>>> b = a.split('\t')
>>> b
['Datenfernübertragung remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission   Preferred|Forbidden|Forbidden|']
>>> b[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
</code>```

There is no any \t in your string, b is a single-item list and its index is zero. Thus your code snippet is completely wrong.

As I could understand you've took an attempt to derive indexes for vertical bar separated values in the string. Hope this snippet should do it in a much neat way:

```<code>>>> for i, j in enumerate(a.split('|')):
...     print(i, j)
...
0 Datenfernübertragung remote data transmission
1 long-distance data transmission
2 long-distance data transfer
3 remote data transmission   Preferred
4 Forbidden
5 Forbidden
6
</code>```

Title: Python iteration on list

Body:
I've got this example

a='Datenfernübertragung remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission   Preferred|Forbidden|Forbidden|'
b = a.split('\t')
for item in b[1].split('|'):
  indeks=b[1].split('|').index(item)
  print(indeks)

and it returns at this moment 0, 1, 2, 0 which are indexes of remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission but why it return to index 0, instead of printing index 3?

Thanks

Body:
Python 3.4.3 (default, Nov 17 2016, 01:11:57)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a='Datenfernübertragung remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission   Preferred|Forbidden|Forbidden|'
>>> b = a.split('\t')
>>> b
['Datenfernübertragung remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission   Preferred|Forbidden|Forbidden|']
>>> b[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

There is no any \t in your string, b is a single-item list and its index is zero. Thus your code snippet is completely wrong.

As I could understand you've took an attempt to derive indexes for vertical bar separated values in the string. Hope this snippet should do it in a much neat way:

>>> for i, j in enumerate(a.split('|')):
...     print(i, j)
...
0 Datenfernübertragung remote data transmission
1 long-distance data transmission
2 long-distance data transfer
3 remote data transmission   Preferred
4 Forbidden
5 Forbidden
6


问:
How do I use CREATE OR REPLACE?
Am I correct in understanding that CREATE OR REPLACE basically means "if the object exists, drop it, then create it either way?"

If so, what am I doing wrong?  This works:

```<code>CREATE TABLE foo (id NUMBER,
title VARCHAR2(4000) DEFAULT 'Default Title')
</code>```

And this doesn't (ORA-00922: missing or invalid option):

```<code>CREATE OR REPLACE TABLE foo (id NUMBER,
title VARCHAR2(4000) DEFAULT 'Default Title')
</code>```

Am I doing something stupid?  I don't seem to be able to find much documentation about this syntax.

答:
So I've been using this and it has worked very well: - it works more like a DROP IF EXISTS but gets the job done

```<code>DECLARE
       VE_TABLENOTEXISTS EXCEPTION;
PRAGMA EXCEPTION_INIT(VE_TABLENOTEXISTS, -942);

    PROCEDURE DROPTABLE(PIS_TABLENAME IN VARCHAR2) IS
              VS_DYNAMICDROPTABLESQL VARCHAR2(1024);
                    BEGIN
                       VS_DYNAMICDROPTABLESQL := 'DROP TABLE ' || PIS_TABLENAME;
                    EXECUTE IMMEDIATE VS_DYNAMICDROPTABLESQL;

                    EXCEPTION
                        WHEN VE_TABLENOTEXISTS THEN
                             DBMS_OUTPUT.PUT_LINE(PIS_TABLENAME || ' NOT EXIST, SKIPPING....');
                        WHEN OTHERS THEN
                             DBMS_OUTPUT.PUT_LINE(SQLERRM);
                    RAISE;
                    END DROPTABLE;

    BEGIN
      DROPTABLE('YOUR_TABLE_HERE');
END DROPTABLE;
/
</code>```

Hope this helps
Also reference:
PLS-00103 Error in PL/SQL Developer

ContentLicense: CC BY-SA 2.5

Title: How do I use CREATE OR REPLACE?

Body:
Am I correct in understanding that CREATE OR REPLACE basically means "if the object exists, drop it, then create it either way?"

If so, what am I doing wrong?  This works:

CREATE TABLE foo (id NUMBER,
title VARCHAR2(4000) DEFAULT 'Default Title')

And this doesn't (ORA-00922: missing or invalid option):

CREATE OR REPLACE TABLE foo (id NUMBER,
title VARCHAR2(4000) DEFAULT 'Default Title')

Am I doing something stupid?  I don't seem to be able to find much documentation about this syntax.

Body:
So I've been using this and it has worked very well: - it works more like a DROP IF EXISTS but gets the job done

DECLARE
       VE_TABLENOTEXISTS EXCEPTION;
PRAGMA EXCEPTION_INIT(VE_TABLENOTEXISTS, -942);

    PROCEDURE DROPTABLE(PIS_TABLENAME IN VARCHAR2) IS
              VS_DYNAMICDROPTABLESQL VARCHAR2(1024);
                    BEGIN
                       VS_DYNAMICDROPTABLESQL := 'DROP TABLE ' || PIS_TABLENAME;
                    EXECUTE IMMEDIATE VS_DYNAMICDROPTABLESQL;

                    EXCEPTION
                        WHEN VE_TABLENOTEXISTS THEN
                             DBMS_OUTPUT.PUT_LINE(PIS_TABLENAME || ' NOT EXIST, SKIPPING....');
                        WHEN OTHERS THEN
                             DBMS_OUTPUT.PUT_LINE(SQLERRM);
                    RAISE;
                    END DROPTABLE;

    BEGIN
      DROPTABLE('YOUR_TABLE_HERE');
END DROPTABLE;
/

Hope this helps
Also reference:
PLS-00103 Error in PL/SQL Developer


问:
How to pass function in Queue in Laravel 5.4?
I am using Laravel 5.4 queue. I would like to read Excel and make DB entry of that records after a few seconds.

```<code>$queue = Queue::later(10,'LogMsg', app('App\Http\Controllers\getFileController')->myfunc($name));
 return $queue;
</code>```

This is my calling function, firstly can I pass like this?

```<code>public function myfunc($name)  {
    $f_data = Excel::load('public/invoices/'.$name, function($reader) {
        })->get();
    if(!empty($f_data) && $f_data->count()){
           foreach ($f_data as $key => $row){
                  $inv = new final_tables;
                  foreach ($row as $key1 => $col){
                        $inv->$key1 = $row->$key1;
                  }
                  $inv->save();
           }
      }
     return 'done';
}
</code>```

答:
I think what you really want to do is process an excel asynchronously and you can write a job class to do the same. The job class can be dispatched from the controller function and will run in the background.

An example job of the same functionality would look like:

```<code>class ReadExcelAndSaveRecordsToDB implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $filePath;

    /**
    * Create a new job instance.
    *
    * @return void
    */
   public function __construct(string $filePath)
   {
       $this->filePath = $filePath;
   }

   /**
    * Execute the job.
    *
    * @return void
    */
    public function handle()
    {
        $fileData = Excel::load($this->filePath, function($reader) {
        })->get();

        //Whatever you want to do with the file here, for eg. create a DB entry
        return 'done';
    }
}
</code>```

Now you can dispatch the same job from your controller function like so:

```<code>use Carbon\Carbon;

public function someControllerAction(Request $request)
{
    $filePath = //Save file and obtain filepath

    $job = (new ReadExcelAndSaveRecordsToDB($filePath))
                ->delay(Carbon::now()->addMinutes(10));

    dispatch($job);
}
</code>```

And that should do it for you.

Body:
I am using Laravel 5.4 queue. I would like to read Excel and make DB entry of that records after a few seconds.

$queue = Queue::later(10,'LogMsg', app('App\Http\Controllers\getFileController')->myfunc($name));
 return $queue;

This is my calling function, firstly can I pass like this?

public function myfunc($name)  {
    $f_data = Excel::load('public/invoices/'.$name, function($reader) {
        })->get();
    if(!empty($f_data) && $f_data->count()){
           foreach ($f_data as $key => $row){
                  $inv = new final_tables;
                  foreach ($row as $key1 => $col){
                        $inv->$key1 = $row->$key1;
                  }
                  $inv->save();
           }
      }
     return 'done';
}

Body:
I think what you really want to do is process an excel asynchronously and you can write a job class to do the same. The job class can be dispatched from the controller function and will run in the background.

An example job of the same functionality would look like:

class ReadExcelAndSaveRecordsToDB implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $filePath;

    /**
    * Create a new job instance.
    *
    * @return void
    */
   public function __construct(string $filePath)
   {
       $this->filePath = $filePath;
   }

   /**
    * Execute the job.
    *
    * @return void
    */
    public function handle()
    {
        $fileData = Excel::load($this->filePath, function($reader) {
        })->get();

        //Whatever you want to do with the file here, for eg. create a DB entry
        return 'done';
    }
}

Now you can dispatch the same job from your controller function like so:

use Carbon\Carbon;

public function someControllerAction(Request $request)
{
    $filePath = //Save file and obtain filepath

    $job = (new ReadExcelAndSaveRecordsToDB($filePath))
                ->delay(Carbon::now()->addMinutes(10));

    dispatch($job);
}

And that should do it for you.


问:
CMake with IBMs mpixlf2008
I am trying to compile a Fortran program using CMake on an IBM BlueGene machine. This is my source:

```<code> > tree
.
├── CMakeLists.txt
└── src
    └── test1.f90
</code>```

where test1.f90 simply is:

```<code>program main
    use mpi
    integer   :: me, ierr

    call MPI_Init(ierr)
    call MPI_Comm_rank(MPI_COMM_WORLD, me, ierr)
    write (*,"(I4,A)") me, ": hello"
    call MPI_Finalize(ierr)
end program main
</code>```

I would like to create a static executable. Therefore I created this CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 2.5)
project(STB)

file(GLOB_RECURSE sources  src/*.f90)

SET(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
SET(BUILD_SHARED_LIBRARIES OFF)
SET(CMAKE_EXE_LINKER_FLAGS "-static")
add_executable(test.x ${sources})

enable_language(Fortran)
set(CMAKE_Fortran_COMPILER_ID "IBM")

if(CMAKE_Fortran_COMPILER_ID MATCHES "IBM")
    MESSAGE(STATUS "IBM")
    set(CMAKE_Fortran_COMPILER mpixlf2008)
    set(dialect "-O2 -qarch=qp -qtune=qp -ufmt_littleendian={23}")
    set(debug "-C")
endif()

set(CMAKE_Fortran_FLAGS_DEBUG "${CMAKE_Fortran_FLAGS_DEBUG} ${bounds}")
set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} ${dialect}")

set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/Modules/")
MESSAGE( STATUS "cmake_module_path:    " ${CMAKE_MODULE_PATH})
</code>```

this results in:

```<code>make VERBOSE=1
/usr/bin/cmake -H/work/jias12/jias1217/test -B/work/jias12/jias1217/test --check-build-system CMakeFiles/Makefile.cmake 0
/usr/bin/cmake -E cmake_progress_start /work/jias12/jias1217/test/CMakeFiles /work/jias12/jias1217/test/CMakeFiles/progress.marks
make -f CMakeFiles/Makefile2 all
make[1]: Entering directory `/work/jias12/jias1217/test'
make -f CMakeFiles/test.x.dir/build.make CMakeFiles/test.x.dir/depend
make[2]: Entering directory `/work/jias12/jias1217/test'
cd /work/jias12/jias1217/test && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /work/jias12/jias1217/test /work/jias12/jias1217/test /work/jias12/jias1217/test /work/jias12/jias1217/test /work/jias12/jias1217/test/CMakeFiles/test.x.dir/DependInfo.cmake --color=
make[2]: Leaving directory `/work/jias12/jias1217/test'
make -f CMakeFiles/test.x.dir/build.make CMakeFiles/test.x.dir/requires
make[2]: Entering directory `/work/jias12/jias1217/test'
make[2]: Nothing to be done for `CMakeFiles/test.x.dir/requires'.
make[2]: Leaving directory `/work/jias12/jias1217/test'
make -f CMakeFiles/test.x.dir/build.make CMakeFiles/test.x.dir/build
make[2]: Entering directory `/work/jias12/jias1217/test'
/usr/bin/cmake -E cmake_progress_report /work/jias12/jias1217/test/CMakeFiles 1
[100%] Building Fortran object CMakeFiles/test.x.dir/src/test1.o
mpixlf2008   -O2 -qarch=qp -qtune=qp -ufmt_littleendian={23}   -c /work/jias12/jias1217/test/src/test1.f90 -o CMakeFiles/test.x.dir/src/test1.o
** main   === End of Compilation 1 ===
1501-510  Compilation successful for file test1.f90.
Linking Fortran executable test.x
/usr/bin/cmake -E cmake_link_script CMakeFiles/test.x.dir/link.txt --verbose=1
mpixlf2008   -static  -O2 -qarch=qp -qtune=qp -ufmt_littleendian={23} CMakeFiles/test.x.dir/src/test1.o  -o test.x -rdynamic
/opt/ibmcmp/xlf/bg/14.1/bin/.orig/bgxlf2008: 1501-210 (S) command option ynamic contains an incorrect subargument
make[2]: *** [test.x] Error 40
make[2]: Leaving directory `/work/jias12/jias1217/test'
make[1]: *** [CMakeFiles/test.x.dir/all] Error 2
make[1]: Leaving directory `/work/jias12/jias1217/test'
make: *** [all] Error 2
</code>```

If I rerun the last argument without the -rdynamic

```<code>mpixlf2008   -static  -O2 -qarch=qp -qtune=qp -ufmt_littleendian={23} CMakeFiles/test.x.dir/src/test1.o  -o test.x
</code>```

I get the error:

```<code>/bgsys/drivers/ppcfloor/gnu-linux/powerpc64-bgq-linux/bin/ld: -f may not be used without -shared
</code>```

How can I compile my program using statically using CMake? If I simply run:

```<code>mpixlf2008 -c src/test1.f90
mpixlf2008 test1.o -o bla.x
</code>```

The compilation works fine and the size(45M) suggest, that it's compiled statically.

Edit:

If I remove the little endian flag:

```<code>set(dialect "-O2 -qarch=qp -qtune=qp")
</code>```

I can run the cmake created makefile and  then manually remove the -rdynamic

mpixlf2008   -static  -O2 -qarch=qp -qtune=qp  CMakeFiles/test.x.dir/src/test1.o  -o test.x

Which then successfully compiles. How can I remove the -rdynamic from the CMake Makefile?

答:
Try adding -qstaticlink to your link line instead of adding -static / -rdynamic directly.  When you use the mpixlf2008 command, the compiler inserts its own -static / -rdynamic options to link in its own libraries, so the options you added are probably interfering with the ones the compiler is using.  The -qstaticlink option tells the compiler you want a completely static binary.  The option also has suboptions that would allow you to only statically link the gcc libraries.

Also, the specific error you're getting is because you specified "-rdynamic".  XLF doesn't know this option, so it assumes it's a grouping of smaller options.  So it parses it as: "-r -d -ynamic".  -r is for creating a nonexecutable output file, -d is for saving preprocessed output, -y is for specifying compile-time rounding mode.  The -y option takes a suboption for the rounding mode, e.g. -yn for nearest.  The error you're getting is that namic is not a known suboption of -y.  To pass -rdynamic to the linker, put -Wl, before it.  i.e. "-Wl,-rdynamic".

Title: CMake with IBMs mpixlf2008

Body:
I am trying to compile a Fortran program using CMake on an IBM BlueGene machine. This is my source:

 > tree
.
├── CMakeLists.txt
└── src
    └── test1.f90

where test1.f90 simply is:

program main
    use mpi
    integer   :: me, ierr

    call MPI_Init(ierr)
    call MPI_Comm_rank(MPI_COMM_WORLD, me, ierr)
    write (*,"(I4,A)") me, ": hello"
    call MPI_Finalize(ierr)
end program main

I would like to create a static executable. Therefore I created this CMakeLists.txt:

cmake_minimum_required(VERSION 2.5)
project(STB)

file(GLOB_RECURSE sources  src/*.f90)

SET(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
SET(BUILD_SHARED_LIBRARIES OFF)
SET(CMAKE_EXE_LINKER_FLAGS "-static")
add_executable(test.x ${sources})

enable_language(Fortran)
set(CMAKE_Fortran_COMPILER_ID "IBM")

if(CMAKE_Fortran_COMPILER_ID MATCHES "IBM")
    MESSAGE(STATUS "IBM")
    set(CMAKE_Fortran_COMPILER mpixlf2008)
    set(dialect "-O2 -qarch=qp -qtune=qp -ufmt_littleendian={23}")
    set(debug "-C")
endif()

set(CMAKE_Fortran_FLAGS_DEBUG "${CMAKE_Fortran_FLAGS_DEBUG} ${bounds}")
set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} ${dialect}")

set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/Modules/")
MESSAGE( STATUS "cmake_module_path:    " ${CMAKE_MODULE_PATH})

this results in:

make VERBOSE=1
/usr/bin/cmake -H/work/jias12/jias1217/test -B/work/jias12/jias1217/test --check-build-system CMakeFiles/Makefile.cmake 0
/usr/bin/cmake -E cmake_progress_start /work/jias12/jias1217/test/CMakeFiles /work/jias12/jias1217/test/CMakeFiles/progress.marks
make -f CMakeFiles/Makefile2 all
make[1]: Entering directory `/work/jias12/jias1217/test'
make -f CMakeFiles/test.x.dir/build.make CMakeFiles/test.x.dir/depend
make[2]: Entering directory `/work/jias12/jias1217/test'
cd /work/jias12/jias1217/test && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /work/jias12/jias1217/test /work/jias12/jias1217/test /work/jias12/jias1217/test /work/jias12/jias1217/test /work/jias12/jias1217/test/CMakeFiles/test.x.dir/DependInfo.cmake --color=
make[2]: Leaving directory `/work/jias12/jias1217/test'
make -f CMakeFiles/test.x.dir/build.make CMakeFiles/test.x.dir/requires
make[2]: Entering directory `/work/jias12/jias1217/test'
make[2]: Nothing to be done for `CMakeFiles/test.x.dir/requires'.
make[2]: Leaving directory `/work/jias12/jias1217/test'
make -f CMakeFiles/test.x.dir/build.make CMakeFiles/test.x.dir/build
make[2]: Entering directory `/work/jias12/jias1217/test'
/usr/bin/cmake -E cmake_progress_report /work/jias12/jias1217/test/CMakeFiles 1
[100%] Building Fortran object CMakeFiles/test.x.dir/src/test1.o
mpixlf2008   -O2 -qarch=qp -qtune=qp -ufmt_littleendian={23}   -c /work/jias12/jias1217/test/src/test1.f90 -o CMakeFiles/test.x.dir/src/test1.o
** main   === End of Compilation 1 ===
1501-510  Compilation successful for file test1.f90.
Linking Fortran executable test.x
/usr/bin/cmake -E cmake_link_script CMakeFiles/test.x.dir/link.txt --verbose=1
mpixlf2008   -static  -O2 -qarch=qp -qtune=qp -ufmt_littleendian={23} CMakeFiles/test.x.dir/src/test1.o  -o test.x -rdynamic
/opt/ibmcmp/xlf/bg/14.1/bin/.orig/bgxlf2008: 1501-210 (S) command option ynamic contains an incorrect subargument
make[2]: *** [test.x] Error 40
make[2]: Leaving directory `/work/jias12/jias1217/test'
make[1]: *** [CMakeFiles/test.x.dir/all] Error 2
make[1]: Leaving directory `/work/jias12/jias1217/test'
make: *** [all] Error 2

If I rerun the last argument without the -rdynamic

mpixlf2008   -static  -O2 -qarch=qp -qtune=qp -ufmt_littleendian={23} CMakeFiles/test.x.dir/src/test1.o  -o test.x

I get the error:

/bgsys/drivers/ppcfloor/gnu-linux/powerpc64-bgq-linux/bin/ld: -f may not be used without -shared

How can I compile my program using statically using CMake? If I simply run:

mpixlf2008 -c src/test1.f90
mpixlf2008 test1.o -o bla.x

The compilation works fine and the size(45M) suggest, that it's compiled statically.

Edit:

If I remove the little endian flag:

set(dialect "-O2 -qarch=qp -qtune=qp")

I can run the cmake created makefile and  then manually remove the -rdynamic

mpixlf2008   -static  -O2 -qarch=qp -qtune=qp  CMakeFiles/test.x.dir/src/test1.o  -o test.x

Which then successfully compiles. How can I remove the -rdynamic from the CMake Makefile?


问:
convert factor levels back into original character values
i built a predictive model classifying persons into two categories having <=50k  and >50k  income

but as i open my file in excel or r to see final predictions i see in place of my values only the levels ( 1 and 2 ) which i assigned in first place to simplify process

please tell me how to retain my original values represented by  levels rather than the levels

Here is the  outline i followed

this is my target variable  income.group
here it is the initial state

str   (train_gbW7HTd $Income.Group)

chr [1:32561] "<=50K" "<=50K" "<=50K" "<=50K" "<=50K" "<=50K" "<=50K" ...

now to apply decision trees i encoded my target variable into levels 1 and 2
i used the following code
train$Income.Group <- match(train$Income.Group,unique(train$Income.Group))
i got

table(train$Income.Group)

```<code>1     2
</code>```

24720  7841

i build decision tree like this
set.seed(333)

fit <- rpart (Income.Group ~.,data = train, method = "class", control =  rpart. control( minsplit = 20, minbucket  = 100, maxdepth = 10, xval = 5)
       + )

make predictions
pred <- predict(fit,test,type = "class")

pred_train <- predict(fit,train,type = "class")

confusionMatrix (pred_train,train$Income.Group)

saved my file
solution.frame <- data.frame(ID = test$ID, Income.Group = pred)

write.csv(solution.frame,file = "final_solution.csv")

but my final csv file has levels 1 and 2 representing final predictions and not <=50k and >50k which i actually want.
please tell me how to proceed .
thanks in advance
 i already used
 solution.frame$Income.Group <- ifelse(solution.frame$Income.Group =="1","<=50k",">50k")

but it gave single value >50k to entire column of Income.Group

Please tell me what to do as i m stuck at this step and unable to complete my model submission.

答:
You could use ifelse:</p>

```<code>train$Income.Group<-ifelse(train$Income.Group=="1","<=50K",">50K")
</code>```

Body:
i built a predictive model classifying persons into two categories having <=50k  and >50k  income

but as i open my file in excel or r to see final predictions i see in place of my values only the levels ( 1 and 2 ) which i assigned in first place to simplify process

please tell me how to retain my original values represented by  levels rather than the levels

Here is the  outline i followed

this is my target variable  income.group
here it is the initial state

str   (train_gbW7HTd $Income.Group)

chr [1:32561] "<=50K" "<=50K" "<=50K" "<=50K" "<=50K" "<=50K" "<=50K" ...

now to apply decision trees i encoded my target variable into levels 1 and 2
i used the following code
train$Income.Group <- match(train$Income.Group,unique(train$Income.Group))
i got

table(train$Income.Group)

1     2

24720  7841

i build decision tree like this
set.seed(333)

fit <- rpart (Income.Group ~.,data = train, method = "class", control =  rpart. control( minsplit = 20, minbucket  = 100, maxdepth = 10, xval = 5)
       + )

make predictions
pred <- predict(fit,test,type = "class")

pred_train <- predict(fit,train,type = "class")

confusionMatrix (pred_train,train$Income.Group)

saved my file
solution.frame <- data.frame(ID = test$ID, Income.Group = pred)

write.csv(solution.frame,file = "final_solution.csv")

but my final csv file has levels 1 and 2 representing final predictions and not <=50k and >50k which i actually want.
please tell me how to proceed .
thanks in advance
 i already used
 solution.frame$Income.Group <- ifelse(solution.frame$Income.Group =="1","<=50k",">50k")

but it gave single value >50k to entire column of Income.Group

Please tell me what to do as i m stuck at this step and unable to complete my model submission.

Body:
You could use ifelse:

train$Income.Group<-ifelse(train$Income.Group=="1","<=50K",">50K")


问:
React.js : use  to submit the <form> inside render() method
Good day everyone.

I have a form and a table inside the render() method of .jsx Component.
And I need to use one of span inside the table to submit the form and pass the action to SpringMVC RestController.

There is some confines:

1) Unfotrunately I can't use Submit or Button input types in this specific happening.

2) Also I can't use JQuery.

The Component code

export default class MyClass extends Component {

  render() {
    let rootUrl = '../rest';

    return (

        <form action={rootUrl + "/books/genres/genre"} method="get" name="bookForm" id="bookForm">

              Book Title
              Author
              Year

                  Submit

        </form>

    )
  }
}```

I'll be very grateful for hint how to realize it.
Thanks in advance.

答:
You could set an onClick handler for your span:

```<code>class MyClass extends Component {
  constructor(super){
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick(evt){
    //submit your form
  }

  render() {
    //rest of your code
   <td className="vertical-align-middle">
     <span className="link-style" onClick={this.handleClick}>Submit</span>
   </td>
  }
}
</code>```

Title: React.js : use <span> to submit the <form> inside render() method

Body:
Good day everyone.

I have a form and a table inside the render() method of .jsx Component.
And I need to use one of span inside the table to submit the form and pass the action to SpringMVC RestController.

There is some confines:

1) Unfotrunately I can't use Submit or Button input types in this specific happening.

2) Also I can't use JQuery.

The Component code

export default class MyClass extends Component {

  render() {
    let rootUrl = '../rest';

    return (

        <form action={rootUrl + "/books/genres/genre"} method="get" name="bookForm" id="bookForm">

              Book Title
              Author
              Year

                  Submit

        </form>

    )
  }
}

I'll be very grateful for hint how to realize it.
Thanks in advance.

Body:
You could set an onClick handler for your span:

class MyClass extends Component {
  constructor(super){
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick(evt){
    //submit your form
  }

  render() {
    //rest of your code
   <td className="vertical-align-middle">
     <span className="link-style" onClick={this.handleClick}>Submit</span>
   </td>
  }
}


问:
Java EE - No suitable driver found for jdbc:sqlserver
So I tried to connect to SQL Server in Java EE Intellij IDEA the thing is that I had a successful experience of connecting to my DB while ago in Java SE. I did everything that I did in there but I get error.
Here's screenshots.

Files:

And here's database connection method:

And here's an error that I get:

So how can I solve this? Thanks!
P.S. Yes, I have added driver as library.

答: Try adding the driver in WEB-INF/lib instead. If you're using a EE server you should register it via JNDI</p>


问:
Using HTTP between CloudFront and EC2 for HTTPS site
Our application is currently running on EC2 instances, requiring HTTPS (and redirecting HTTP to HTTPS). We are now considering serving all requests via CloudFront and enforcing HTTPS through CloudFront. Our thought is that once we do that we would then block HTTP/HTTPS requests not coming from CloudFront and relax the HTTPS requirement. This way all requests to CloudFront would be via HTTPS, but CloudFront would retrieve the data from the EC2 origin via HTTP. This way we would a) reduce some server overhead since the server doesn't have to do the TLS encryption and b) eliminate the need to manage certificates for the EC2 instances.

Are there any security concerns with this or other reasons not to do this?

答:
Actually, here in the company where I am working, we have the following scenario.

EC2 -> ELB -> CF (+ AWS Certificate) = HTTP and HTTPS

EC2 always work with 80

CF work with both 443 and 80.

It is easy to configure and so far we don't have problems.


问:
Metro-style Appbar in fullscreen WPF program
I am currently working on a desktop C# WPF application where the goal is to make it look and feel like a "real" Windows Store App.

I want to add an appbar that should be shown when the user swipes up from the bottom. To do this in a normal app you just position your finger outside the screen area, and swipe up.
But if I do that in a fullscreen WPF program I don't receive any TouchDown or TouchMove events - probably because the finger is already down when entering the actual screen area.
I have tried with the Manipulation framework also, but same result here. Even when I hook directly into the message queue using WndProc or other hooks I get no events at all.

The funny thing is that I can see the "touch cursor" move around the screen, so at least something in the underlying framework is notified.

Does anyone have an idea how to do this?

p.s. It is not an option for me just to use a windows store app instead, because of hardware connectivity issues ;-)

答:
You will need to keep track of the cursor location coordinates, and see when the cursor (swipe) starts at the edge of the screen and moves in. When that triggers (with whatever trigger you want, distance covered most likely) you can fire up your Appbar.

There was a similar question asked on MSDN:
 https://social.msdn.microsoft.com/Forums/vstudio/en-US/d85dcde7-839a-44d3-9f2a-8b47b947576c/swipe-gesture-and-page-change?forum=wpf


问:
Loop over ID's and add an extra attr()
I'm trying to add an extra attribute depending on a class name but it's not quite working the way I want it.
My menu structure (simplified) is as follows:

```<code><ul class="main-menu">

<li>
    <a>Menu 1</a>
    <div class="uk-navbar-dropdown">
        <div id="km-megamenu-960" class="uk-navbar-dropdown-grid km-mode-click km-megamenu">dropdown content</div>
    </div>
</li>

<li><a>Menu 2</a></li>

<li>
    <a>Menu 3</a>
    <div class="uk-navbar-dropdown">
        <div id="km-megamenu-962" class="uk-navbar-dropdown-grid km-mode-hover km-megamenu">dropdown content</div>
    </div>
</li>

...

</ul>
</code>```

My jquery code is as follows:

```<code>var ids = $('.km-megamenu').map(function() {
  return this.id;
}).get().join(',#');

$('#' + ids).each( function(i) {
    if ( $(this).hasClass('km-mode-click') ) {
        $(this).prev(".uk-navbar-dropdown").attr('mode', 'click');
    }

    if ( $(this).hasClass('km-mode-hover') ) {
        $(this).prev(".uk-navbar-dropdown").attr('mode', 'hover');
    }
});
</code>```

Based on the class name km-mode-hover or km-mode-click, I want to add an extra attr inside the uk-navbar-dropdown div. E.g:

```<code><div class="uk-navbar-dropdown" mode="click">
</code>```

When using console all ids are correct. I just have to loop through them correctly. I'm still a newbie when it comes to jquery,
so if there's anyone who can put me on the right track, I'd really appreciate it.

答:
I have changed the way you used the selector.

Instead of mapping and getting each id, i have used a class that the elements you want to iterate have in common.

Then, changed .prev() by .parent(), since the first should be used to find siblings and not parents.

$('.km-megamenu').each(function() {
   $parent = $(this).parent('.uk-navbar-dropdown');

   if ($(this).hasClass('km-mode-click')) {
     $parent.attr('mode', 'click');
     console.log('New attribute: ' + $parent.attr('mode'));
   } else if ($(this).hasClass('km-mode-hover')) {
     $parent.attr('mode', 'hover');
     console.log('New attribute: ' + $parent.attr('mode'));
   }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="main-menu">
  <li>
    <a>Menu 1</a>
    <div class="uk-navbar-dropdown">
      <div id="km-megamenu-960" class="uk-navbar-dropdown-grid km-mode-click km-megamenu">dropdown content</div>
    </div>
  </li>

  <li><a>Menu 2</a></li>

  <li>
    <a>Menu 3</a>
    <div class="uk-navbar-dropdown">
      <div id="km-megamenu-962" class="uk-navbar-dropdown-grid km-mode-hover km-megamenu">dropdown content</div>
    </div>
  </li>
</ul></code>```

Title: Loop over ID's and add an extra attr()

Body:
I'm trying to add an extra attribute depending on a class name but it's not quite working the way I want it.
My menu structure (simplified) is as follows:

    Menu 1

dropdown content

Menu 2

    Menu 3

dropdown content

...

My jquery code is as follows:

var ids = $('.km-megamenu').map(function() {
  return this.id;
}).get().join(',#');

$('#' + ids).each( function(i) {
    if ( $(this).hasClass('km-mode-click') ) {
        $(this).prev(".uk-navbar-dropdown").attr('mode', 'click');
    }

    if ( $(this).hasClass('km-mode-hover') ) {
        $(this).prev(".uk-navbar-dropdown").attr('mode', 'hover');
    }
});

Based on the class name km-mode-hover or km-mode-click, I want to add an extra attr inside the uk-navbar-dropdown div. E.g:

When using console all ids are correct. I just have to loop through them correctly. I'm still a newbie when it comes to jquery,
so if there's anyone who can put me on the right track, I'd really appreciate it.

Body:
I have changed the way you used the selector.

Instead of mapping and getting each id, i have used a class that the elements you want to iterate have in common.

Then, changed .prev() by .parent(), since the first should be used to find siblings and not parents.

$('.km-megamenu').each(function() {
   $parent = $(this).parent('.uk-navbar-dropdown');

   if ($(this).hasClass('km-mode-click')) {
     $parent.attr('mode', 'click');
     console.log('New attribute: ' + $parent.attr('mode'));
   } else if ($(this).hasClass('km-mode-hover')) {
     $parent.attr('mode', 'hover');
     console.log('New attribute: ' + $parent.attr('mode'));
   }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="main-menu">
  <li>
    <a>Menu 1</a>
    <div class="uk-navbar-dropdown">
      <div id="km-megamenu-960" class="uk-navbar-dropdown-grid km-mode-click km-megamenu">dropdown content</div>
    </div>
  </li>

  <li><a>Menu 2</a></li>

  <li>
    <a>Menu 3</a>
    <div class="uk-navbar-dropdown">
      <div id="km-megamenu-962" class="uk-navbar-dropdown-grid km-mode-hover km-megamenu">dropdown content</div>
    </div>
  </li>
</ul>


问:
Make link from text inside brackets using preg_replace
I would like to use PHP to transform a text from this format:

foo [[http://www.google.com|This Link points to google]] foo

to this

foo This Link points to google foo

I've made this code:

```<code>function linkLine($line) {
    if (preg_match('#\[\[(.*?)\]\]#', $line, $match)) {
        $arr = explode("|", $match[1], 2);
        $link = "<a href=\"$arr[0]\">$arr[1]</a>";
        return str_replace($match[0], $link, $line);
    } else {
        return $line;
   }
}
</code>```

But i know that's is not elegant, not robust and doesn't work if there is more than one occurrences in the same line.

How can I improve it using preg_replace?

答:
You may use the same regex with a preg_replace_callback:

```<code>$re = '/\[\[(.*?)]]/';
$str = 'foo [[http://www.google.com|This Link points to google]] foo [[http://www.more.com|This Link points to more]]';
echo preg_replace_callback($re, function($m) {
    $arr = explode("|", $m[1], 2);
    return '<a href="' . $arr[0] . '">'. $arr[1] . '</a>';
}, $str);
</code>```

See the PHP demo.

Result:

```<code>foo <a href="http://www.google.com">This Link points to google</a> foo <a href="http://www.more.com">This Link points to more</a>
</code>```

If the strings inside [[ and ]] cannot have [, ] and only have 1 |, you may also use

```<code>$re = '/\[\[([^][|]*?)\|([^][]*?)]]/';
</code>```

See the following PHP demo:

```<code>$re = '/\[\[([^][|]*?)\|([^][]*?)]]/';
$str = 'foo [[http://www.google.com|This Link points to google]] foo [[http://www.more.com|This Link points to more]]';
echo preg_replace($re, '<a href="$1">$2</a>', $str);
</code>```

Body:
I would like to use PHP to transform a text from this format:

foo [[http://www.google.com|This Link points to google]] foo

to this

foo This Link points to google foo

I've made this code:

function linkLine($line) {
    if (preg_match('#\[\[(.*?)\]\]#', $line, $match)) {
        $arr = explode("|", $match[1], 2);
        $link = "$arr[1]";
        return str_replace($match[0], $link, $line);
    } else {
        return $line;
   }
}

But i know that's is not elegant, not robust and doesn't work if there is more than one occurrences in the same line.

How can I improve it using preg_replace?

Body:
You may use the same regex with a preg_replace_callback:

$re = '/\[\[(.*?)]]/';
$str = 'foo [[http://www.google.com|This Link points to google]] foo [[http://www.more.com|This Link points to more]]';
echo preg_replace_callback($re, function($m) {
    $arr = explode("|", $m[1], 2);
    return '<a href="' . $arr[0] . '">'. $arr[1] . '</a>';
}, $str);

See the PHP demo.

Result:

foo <a href="http://www.google.com">This Link points to google</a> foo <a href="http://www.more.com">This Link points to more</a>

If the strings inside [[ and ]] cannot have [, ] and only have 1 |, you may also use

$re = '/\[\[([^][|]*?)\|([^][]*?)]]/';

See the following PHP demo:

$re = '/\[\[([^][|]*?)\|([^][]*?)]]/';
$str = 'foo [[http://www.google.com|This Link points to google]] foo [[http://www.more.com|This Link points to more]]';
echo preg_replace($re, '<a href="$1">$2</a>', $str);


问:
Retrieving the last record in each group - MySQL
There is a table messages that contains data as shown below:

```<code>Id   Name   Other_Columns
-------------------------
1    A       A_data_1
2    A       A_data_2
3    A       A_data_3
4    B       B_data_1
5    B       B_data_2
6    C       C_data_1
</code>```

If I run a query select * from messages group by name, I will get the result as:

```<code>1    A       A_data_1
4    B       B_data_1
6    C       C_data_1
</code>```

What query will return the following result?

```<code>3    A       A_data_3
5    B       B_data_2
6    C       C_data_1
</code>```

That is, the last record in each group should be returned.

At present, this is the query that I use:

```<code>SELECT
  *
FROM (SELECT
  *
FROM messages
ORDER BY id DESC) AS x
GROUP BY name
</code>```

But this looks highly inefficient. Any other ways to achieve the same result?

答:
Here is my solution:</p>

```<code>SELECT
  DISTINCT NAME,
  MAX(MESSAGES) OVER(PARTITION BY NAME) MESSAGES
FROM MESSAGE;
</code>```

Body:
There is a table messages that contains data as shown below:

Id   Name   Other_Columns
-------------------------
1    A       A_data_1
2    A       A_data_2
3    A       A_data_3
4    B       B_data_1
5    B       B_data_2
6    C       C_data_1

If I run a query select * from messages group by name, I will get the result as:

1    A       A_data_1
4    B       B_data_1
6    C       C_data_1

What query will return the following result?

3    A       A_data_3
5    B       B_data_2
6    C       C_data_1

That is, the last record in each group should be returned.

At present, this is the query that I use:

SELECT
  *
FROM (SELECT
  *
FROM messages
ORDER BY id DESC) AS x
GROUP BY name

But this looks highly inefficient. Any other ways to achieve the same result?

Body:
Here is my solution:

SELECT
  DISTINCT NAME,
  MAX(MESSAGES) OVER(PARTITION BY NAME) MESSAGES
FROM MESSAGE;


问:
JavaFX 8 - Alert not open
I'm developing a little Server-Client-System for Chess. Users can ask other Users for a game and there's my problem. The Client sends a message to the server, the server sends the message directly to the other Client and the other Client gets the message. After getting the message, the Client should open an Alert to choose if he wants to play with the other Client, but it simply does not open. Here's my code</p>

```<code>} else if (readed.equals("+anfrage")){
    String n=clientSocket.readLine();
    Alert in=new Alert(AlertType.CONFIRMATION);     //here the program stucks
    in.setHeaderText("Spielanfrage von: "+n);
    in.getButtonTypes().clear();
    in.getButtonTypes().addAll(ButtonType.YES, ButtonType.NO);
    in.setResizable(false);
    Optional<ButtonType> opt=in.showAndWait();
    if (opt.get()==ButtonType.YES) {

    } else{

    }
</code>```

答:
```<code>Alert alert = new Alert(AlertType.CONFIRMATION, " Your Message" + selection + " ?", ButtonType.YES, ButtonType.NO, ButtonType.CANCEL);
alert.showAndWait();

if (alert.getResult() == ButtonType.YES) {
    //do stuff
}else{
   //do other stuffs
}
</code>```

Title: JavaFX 8 - Alert not open

Body:
I'm developing a little Server-Client-System for Chess. Users can ask other Users for a game and there's my problem. The Client sends a message to the server, the server sends the message directly to the other Client and the other Client gets the message. After getting the message, the Client should open an Alert to choose if he wants to play with the other Client, but it simply does not open. Here's my code

} else if (readed.equals("+anfrage")){
    String n=clientSocket.readLine();
    Alert in=new Alert(AlertType.CONFIRMATION);     //here the program stucks
    in.setHeaderText("Spielanfrage von: "+n);
    in.getButtonTypes().clear();
    in.getButtonTypes().addAll(ButtonType.YES, ButtonType.NO);
    in.setResizable(false);
    Optional<ButtonType> opt=in.showAndWait();
    if (opt.get()==ButtonType.YES) {

    } else{

    }


问:
What's the jquery syntax for click function of submit button
my form has a submit button that's been defined this way:

```<code><input type="submit" name="submit-reg" value="Register" class="submit button">
</code>```

What is the syntax to call the button's jquery click() function?
I've tried:

```<code>$('#submit-reg').click(function()...
</code>```

But it's not working.

答:
```<code>   <form action="">
   <input type="submit" value="Submit">
   </form>

<script>
$(document).ready(function(){
    $("form").submit(function(){
        alert("Submitted");
    });
});
</script>
</code>```

Body:
my form has a submit button that's been defined this way:

<input type="submit" name="submit-reg" value="Register" class="submit button">

What is the syntax to call the button's jquery click() function?
I've tried:

$('#submit-reg').click(function()...

But it's not working.


问:
Test that an argument to a method has been changed
I'm trying to write some tests using xUnit and Moq and I can't seem to wrap my head around how to test that an argument provided to a method has been changed by the method itself.

Here's what I have:

[Fact]
public void WhenCreateAsyncCalledSomePropertyIsSet()
{
    // Arrange
    var mockSomeService = new Mock<ISomeService>();
    var someObject = new SomeObject();

    // Act
    mockSomeService.Setup(x => x.CreateAsync(someObject)).Callback(() => {
        someObject.SomeProperty = "SomeValue";
    });

    // Assert
    Assert.NotNull(someObject.SomeProperty);
}
```

<p>Basically what I'm trying to do is make sure that when the <code>CreateAsync(someObject)</code> is called it sets the <code>SomeProperty</code> property of the <code>someObject</code> argument. My test fails..</p>

<p>UPDATE:</p>

<p>I'm trying to test the following method:</p>

<pre class="lang-cs prettyprint-override"><code>public class SomeService : ISomeService
{
    private readonly SomeContext _context;

    public SomeService(SomeContext context)
    {
        _context = context;
    }

    public async Task CreateAsync(SomeObject someObject)
    {
        someObject.SomeProperty = GenerateRandomString();

        _context.SomeObjects.Add(project);

        await _context.SaveChangesAsync();
    }
}
</code>```

I want to test whether SomeProperty is set (like above) when the method is called. If I forget to set it I want the test to fail.

答:
The service is tightly coupled to the SomeContext implementation concern. Unless you plan to do in-memory testing that context is going to cause some complications.

Abstract the context.

```<code>public interface ISomeContext {
    ISomeSet<SomeObject> SomeObjects { get; set; }
    Task<int> SaveChangesAsync();
}
</code>```

The class would refactor so that it no longer depended on implementation concerns and allow for greater flexibility.

```<code>public class SomeService : ISomeService {
    private readonly ISomeContext _context;

    public SomeService(ISomeContext context) {
        _context = context;
    }

    public async Task CreateAsync(SomeObject someObject) {
        someObject.SomeProperty = GenerateRandomString();
        _context.SomeObjects.Add(project);
        await _context.SaveChangesAsync();
    }

    string GenerateRandomString() {
        //...other code
    }
}
</code>```

And the test would mock the functionality of the dependencies of that subject under test and inject it when exercising the test.

```<code>public Task WhenCreateAsyncCalledSomePropertyIsSet() {
    // Arrange
    var mockSomeContext = new Mock<ISomeContext>();
    mockSomeContext
        .Setup(x => x.SaveChangesAsync())
        .ReturnsAsync(1); //Because the method under test is async

    var sut = new SomeService (mockSomeContext.Object); //Actual service, fake context
    var someObject = new SomeObject(); //actual object

    Assert.IsNull(someObject.SomeProperty); //making sure it was null to begin with

    // Act
    await sut.CreateAsync(someObject); //call method under test.
    var actual = someObject.SomeProperty; //get the value

    // Assert
    Assert.NotNull(actual); //Assert that it was actually set.
}
</code>```

Your real context would be derived from the abstraction/interface or wrapped by something that provides that functionality.

Review Moq Quickstart to get a better understanding of the framework.

Body:
I'm trying to write some tests using xUnit and Moq and I can't seem to wrap my head around how to test that an argument provided to a method has been changed by the method itself.

Here's what I have:

[Fact]
public void WhenCreateAsyncCalledSomePropertyIsSet()
{
    // Arrange
    var mockSomeService = new Mock<ISomeService>();
    var someObject = new SomeObject();

    // Act
    mockSomeService.Setup(x => x.CreateAsync(someObject)).Callback(() => {
        someObject.SomeProperty = "SomeValue";
    });

    // Assert
    Assert.NotNull(someObject.SomeProperty);
}

Basically what I'm trying to do is make sure that when the CreateAsync(someObject) is called it sets the SomeProperty property of the someObject argument. My test fails..

UPDATE:

I'm trying to test the following method:

public class SomeService : ISomeService
{
    private readonly SomeContext _context;

    public SomeService(SomeContext context)
    {
        _context = context;
    }

    public async Task CreateAsync(SomeObject someObject)
    {
        someObject.SomeProperty = GenerateRandomString();

        _context.SomeObjects.Add(project);

        await _context.SaveChangesAsync();
    }
}

I want to test whether SomeProperty is set (like above) when the method is called. If I forget to set it I want the test to fail.

Body:
The service is tightly coupled to the SomeContext implementation concern. Unless you plan to do in-memory testing that context is going to cause some complications.

Abstract the context.

public interface ISomeContext {
    ISomeSet<SomeObject> SomeObjects { get; set; }
    Task<int> SaveChangesAsync();
}

The class would refactor so that it no longer depended on implementation concerns and allow for greater flexibility.

public class SomeService : ISomeService {
    private readonly ISomeContext _context;

    public SomeService(ISomeContext context) {
        _context = context;
    }

    public async Task CreateAsync(SomeObject someObject) {
        someObject.SomeProperty = GenerateRandomString();
        _context.SomeObjects.Add(project);
        await _context.SaveChangesAsync();
    }

    string GenerateRandomString() {
        //...other code
    }
}

And the test would mock the functionality of the dependencies of that subject under test and inject it when exercising the test.

public Task WhenCreateAsyncCalledSomePropertyIsSet() {
    // Arrange
    var mockSomeContext = new Mock<ISomeContext>();
    mockSomeContext
        .Setup(x => x.SaveChangesAsync())
        .ReturnsAsync(1); //Because the method under test is async

    var sut = new SomeService (mockSomeContext.Object); //Actual service, fake context
    var someObject = new SomeObject(); //actual object

    Assert.IsNull(someObject.SomeProperty); //making sure it was null to begin with

    // Act
    await sut.CreateAsync(someObject); //call method under test.
    var actual = someObject.SomeProperty; //get the value

    // Assert
    Assert.NotNull(actual); //Assert that it was actually set.
}

Your real context would be derived from the abstraction/interface or wrapped by something that provides that functionality.

Review Moq Quickstart to get a better understanding of the framework.


问:
Undo last diff in Phabricator
I have an open revision in Phabricator (with Git), and I submitted a diff to this revision, with the arc diff command.

The problem is that this diff is bad, and so I would like to undo it and to come back to the previous diff.

Do you know how can I do please?

答:
I often make the mistake of diff'ing against the wrong branch.

The first step is to undo the diff. We can't kill the diff from the revision history, but we can revert it.

```<code>$ arc patch --diff <diff_id> # last good diff, creates <arcpatch-branch>
$ arc diff --update <revision_id> <arcpatch-branch> # "reverts" the offending diffs to the current state
</code>```

At this point your revision is back to its original state. If you want to perform the diff again then do what you normally do. Checkout the branch with the changes intended for the diff and then perform the diff.

```<code>$ git checkout <new_branch>
$ arc diff <source_branch> # new_branch has changes that is intended to be merged into source_branch
</code>```

Credit to altendky who listed most of these steps. However, the revision flag he referenced no longer exists and I also wanted the steps to be listed a bit more clearly.

Title: Undo last diff in Phabricator

Body:
I often make the mistake of diff'ing against the wrong branch.

The first step is to undo the diff. We can't kill the diff from the revision history, but we can revert it.

$ arc patch --diff <diff_id> # last good diff, creates <arcpatch-branch>
$ arc diff --update <revision_id> <arcpatch-branch> # "reverts" the offending diffs to the current state

At this point your revision is back to its original state. If you want to perform the diff again then do what you normally do. Checkout the branch with the changes intended for the diff and then perform the diff.

$ git checkout <new_branch>
$ arc diff <source_branch> # new_branch has changes that is intended to be merged into source_branch

Credit to altendky who listed most of these steps. However, the revision flag he referenced no longer exists and I also wanted the steps to be listed a bit more clearly.


问:
Are there any good open source smalltalk implementations?
Do you know any good smalltalk implementations which meet the following criteria:

are open source (and free)

are enterprise ready - I can do commercial apps into it

works on os x

I'm asking this because I heard a lot about smalltalk, and I want to learn it - just for fun. But it seems to be hard to find the right tools and books for this language.

答:
I am happy developing commercial web applications on a Mac in Pharo. Cross-platform development is easy and painless. I work together with a Windows-based developer and we deploy on Ubuntu. There we use the commercial Gemstone system (OODB) in its free version. We use Monticello as a distributed version control system. I've taught a student the basics of smalltallk and Seaside with James Foster's tutorial. A more in-depth explanation is in the Seaside book

When creating domain models, Glamour is a fantastic toolkit to create browsers, allowing the navigation and visualization of the model. It is part of Moose, a software reengineering system, also based on Pharo.

There are of course also weaknesses: Pharo changes a lot. Track the changes that are going on on the issue tracker and the mailing list. Staying about a month behind the bleeding edge is about right for us. Integration with legacy systems is easiest with REST web services or files. Smalltalk tends to use a lot less XML (SOAP) than .NET and java. There is no good 64 bit support. There are 64 bit images, but they have not been tested enough and are known to have problems.


问:
Tkinter skips over part of the code detailing the reaction to an input - Python
I am creating a program that judges the strength of passwords. Part of the code is supposed to check whether a password has any numbers. However, when I enter a password, it completely neglects the code detailing what to print as the output if there are no numbers, and instead returns with: 'this is too short.'

```<code>from tkinter import *

import re

def pass_Type():
  strength = pass_Type  #Applies pass_Type to the entire program

def value():
  value

def click():
    entered_text = entry.get()
    if entered_text in pass_Type:
        strength = pass_Type[entered_text]
        output.delete(0.0, END)
        output.insert(END, strength)
         #Click function
    elif len(entered_text) < 9:
        output.delete(0.0, END)
        output.insert(END, 'This is too short')
    elif pass_Type and len(entered_text) < 9:
       output.delete(0.0, END)
       output.insert(END, strength)
    elif value(entered_text):                              }
        if not any(c.isdigit() for c in value):            }
          output.delete(0.0, END)                          }
          output.insert(END, 'Incorporate some numbers')   } #The problematic area
    elif value(entered_text) and len(entered_text)  < 9:   }
        if not any(c.isdigit() for c in value):            }
          output.delete(0.0, END)
          output.insert(END, 'Try to incorporate some numbers and increase the length of your password')
    else:
        output.delete(0.0, END)
        output.insert(END, "This password is acceptable!") #When the password is ok

Password = Tk()
Password.title('Password tester')

label = Label(Password, text="Password:")
label.grid(row=0, column=0, sticky=W)    #Entry label

entry = Entry(width=20, bg='light blue')
entry.grid(row=1, column=0, sticky=W)     #Entry box

Button(Password, text='SUBMIT',width=5, command=click).grid(row=2,column=0, sticky=W)  #Button

label = Label(Password, text='Strength:')
label.grid(row=4, column=0, sticky=W)          #Output label

output = Text(Password, width=75, height=6, wrap=WORD, background='light blue')
output.grid(row=5, column=0, columnspan=2, sticky=W)                              #Output box

pass_Type = {
  'Password': 'This is a very predicatable password. You should incorporate numbers',
  'password': 'This is a very predicatable password. You should incorporate numbers and capital letters',  #Common password glossary
  '12345': 'Try and incorporate some letters',
  'qwerty': 'Try to jumble up your letters so the password is not so predictable.'
  }

Password.mainloop()
</code>```

When I attempt to test the code by itself by entering over 9 characters, it rejects the code with the following error:

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "", line 1549, in __call__
    return self.func(*args)
  File "", line 25, in click
    elif value(entered_text):
TypeError: value() takes 0 positional arguments but 1 was given
</code>```

How can I make the program not skip over the aspect, and use the alternative output that I have programmed?
And if incorporating numbers was the only problem, how can I fix the error?

答:
Try the following.

Lets create a True/False variable and decide right off the bat if there is a number in the entry box.

If there is a number in the entry box then we can change that variable to True and the elif statement can pick that up.

There are a few ways to get this done but I chose to do it this way.

EDIT:

after looking over your code a bit I noticed sever things that were either not needed or redundant or did nothing at all.

Take this following code and it should produce the results you are looking for. Note the stuff I toke out. Of the following code as it really did nothing for you in the code.

UPDATE: Added a feature we talked about in chat.

```<code>from tkinter import *
import re

pass_Type = {
  'Password': 'This is a very predictable password. You should incorporate numbers',
  'password': 'This is a very predictable password. You should incorporate numbers and capital letters',
  '12345': 'Try and incorporate some letters',
  'qwerty': 'Try to jumble up your letters so the password is not so predictable.'
  }

def click():
    entered_text = entry.get()
    x = False
    y = False
    for i in entered_text:
        if i in "0123456789":
            x = True
    for i in entered_text:
        if i in "abcdefghijklmnopqrstuvwqyzABCDEFGHIJKLMNOPQRSTUVWXYZ":
            y = True

    if entered_text in pass_Type:
        output.delete(0.0, END)
        output.insert(END, pass_Type[entered_text])

    elif len(entered_text) < 9:
        if x == True and y == True:
            output.delete(0.0, END)
            output.insert(END, 'This is too short')
        elif x == False and y == False:
            output.delete(0.0, END)
            output.insert(END, 'Try to incorporate some numbers, letters and increase the length of your password')
        elif x == False and y == True:
            output.delete(0.0, END)
            output.insert(END, 'Try to incorporate some numbers and increase the length of your password')
        else:
            output.delete(0.0, END)
            output.insert(END, 'Try to incorporate some letters and increase the length of your password')

    elif x == False:
        output.delete(0.0, END)
        output.insert(END, 'Incorporate some numbers')

    elif y == False:
        output.delete(0.0, END)
        output.insert(END, 'Incorporate some letters')

    else:
        output.delete(0.0, END)
        output.insert(END, "This password is acceptable!")

Password = Tk()
Password.title('Password tester')

label = Label(Password, text="Password:")
label.grid(row=0, column=0, sticky=W)

entry = Entry(width=20, bg='light blue')
entry.grid(row=1, column=0, sticky=W)

Button(Password, text='SUBMIT',width=5, command=click).grid(row=2,column=0, sticky=W)

label = Label(Password, text='Strength:')
label.grid(row=4, column=0, sticky=W)

output = Text(Password, width=75, height=6, wrap=WORD, background='light blue')
output.grid(row=5, column=0, columnspan=2, sticky=W)

Password.mainloop()
</code>```

I removed the following 2 function as they did literally nothing for you.

This function does nothing as no where in your code did you ever call that function. All you need to do is use pass_Type in place anywhere you had strength.

```<code>def pass_Type():
  strength = pass_Type  #Applies pass_Type to the entire program
</code>```

This function also does nothing. even if you were to have code that calls this function def value(): returns nothing and does not apply anything to a variable or widget.

```<code>def value():
  value
</code>```

Body:
I am creating a program that judges the strength of passwords. Part of the code is supposed to check whether a password has any numbers. However, when I enter a password, it completely neglects the code detailing what to print as the output if there are no numbers, and instead returns with: 'this is too short.'

from tkinter import *

import re

def pass_Type():
  strength = pass_Type  #Applies pass_Type to the entire program

def value():
  value

def click():
    entered_text = entry.get()
    if entered_text in pass_Type:
        strength = pass_Type[entered_text]
        output.delete(0.0, END)
        output.insert(END, strength)
         #Click function
    elif len(entered_text) < 9:
        output.delete(0.0, END)
        output.insert(END, 'This is too short')
    elif pass_Type and len(entered_text) < 9:
       output.delete(0.0, END)
       output.insert(END, strength)
    elif value(entered_text):                              }
        if not any(c.isdigit() for c in value):            }
          output.delete(0.0, END)                          }
          output.insert(END, 'Incorporate some numbers')   } #The problematic area
    elif value(entered_text) and len(entered_text)  < 9:   }
        if not any(c.isdigit() for c in value):            }
          output.delete(0.0, END)
          output.insert(END, 'Try to incorporate some numbers and increase the length of your password')
    else:
        output.delete(0.0, END)
        output.insert(END, "This password is acceptable!") #When the password is ok

Password = Tk()
Password.title('Password tester')

label = Label(Password, text="Password:")
label.grid(row=0, column=0, sticky=W)    #Entry label

entry = Entry(width=20, bg='light blue')
entry.grid(row=1, column=0, sticky=W)     #Entry box

Button(Password, text='SUBMIT',width=5, command=click).grid(row=2,column=0, sticky=W)  #Button

label = Label(Password, text='Strength:')
label.grid(row=4, column=0, sticky=W)          #Output label

output = Text(Password, width=75, height=6, wrap=WORD, background='light blue')
output.grid(row=5, column=0, columnspan=2, sticky=W)                              #Output box

pass_Type = {
  'Password': 'This is a very predicatable password. You should incorporate numbers',
  'password': 'This is a very predicatable password. You should incorporate numbers and capital letters',  #Common password glossary
  '12345': 'Try and incorporate some letters',
  'qwerty': 'Try to jumble up your letters so the password is not so predictable.'
  }

Password.mainloop()

When I attempt to test the code by itself by entering over 9 characters, it rejects the code with the following error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "", line 1549, in __call__
    return self.func(*args)
  File "", line 25, in click
    elif value(entered_text):
TypeError: value() takes 0 positional arguments but 1 was given

How can I make the program not skip over the aspect, and use the alternative output that I have programmed?
And if incorporating numbers was the only problem, how can I fix the error?

Body:
Try the following.

Lets create a True/False variable and decide right off the bat if there is a number in the entry box.

If there is a number in the entry box then we can change that variable to True and the elif statement can pick that up.

There are a few ways to get this done but I chose to do it this way.

EDIT:

after looking over your code a bit I noticed sever things that were either not needed or redundant or did nothing at all.

Take this following code and it should produce the results you are looking for. Note the stuff I toke out. Of the following code as it really did nothing for you in the code.

UPDATE: Added a feature we talked about in chat.

from tkinter import *
import re

pass_Type = {
  'Password': 'This is a very predictable password. You should incorporate numbers',
  'password': 'This is a very predictable password. You should incorporate numbers and capital letters',
  '12345': 'Try and incorporate some letters',
  'qwerty': 'Try to jumble up your letters so the password is not so predictable.'
  }

def click():
    entered_text = entry.get()
    x = False
    y = False
    for i in entered_text:
        if i in "0123456789":
            x = True
    for i in entered_text:
        if i in "abcdefghijklmnopqrstuvwqyzABCDEFGHIJKLMNOPQRSTUVWXYZ":
            y = True

    if entered_text in pass_Type:
        output.delete(0.0, END)
        output.insert(END, pass_Type[entered_text])

    elif len(entered_text) < 9:
        if x == True and y == True:
            output.delete(0.0, END)
            output.insert(END, 'This is too short')
        elif x == False and y == False:
            output.delete(0.0, END)
            output.insert(END, 'Try to incorporate some numbers, letters and increase the length of your password')
        elif x == False and y == True:
            output.delete(0.0, END)
            output.insert(END, 'Try to incorporate some numbers and increase the length of your password')
        else:
            output.delete(0.0, END)
            output.insert(END, 'Try to incorporate some letters and increase the length of your password')

    elif x == False:
        output.delete(0.0, END)
        output.insert(END, 'Incorporate some numbers')

    elif y == False:
        output.delete(0.0, END)
        output.insert(END, 'Incorporate some letters')

    else:
        output.delete(0.0, END)
        output.insert(END, "This password is acceptable!")

Password = Tk()
Password.title('Password tester')

label = Label(Password, text="Password:")
label.grid(row=0, column=0, sticky=W)

entry = Entry(width=20, bg='light blue')
entry.grid(row=1, column=0, sticky=W)

Button(Password, text='SUBMIT',width=5, command=click).grid(row=2,column=0, sticky=W)

label = Label(Password, text='Strength:')
label.grid(row=4, column=0, sticky=W)

output = Text(Password, width=75, height=6, wrap=WORD, background='light blue')
output.grid(row=5, column=0, columnspan=2, sticky=W)

Password.mainloop()

I removed the following 2 function as they did literally nothing for you.

This function does nothing as no where in your code did you ever call that function. All you need to do is use pass_Type in place anywhere you had strength.

def pass_Type():
  strength = pass_Type  #Applies pass_Type to the entire program

This function also does nothing. even if you were to have code that calls this function def value(): returns nothing and does not apply anything to a variable or widget.

def value():
  value


问:
UISearchController's UISearchBar embedded in Navigation Bar: Does not become first responder
I am trying to embed a UISearchController's search bar in the titleView of my navigation controller's bar. Exactly this can be seen in the UICatalog sample code by Apple and works:

```<code>// Create the search results view controller and use it for the UISearchController.
AAPLSearchResultsViewController *searchResultsController = [self.storyboard instantiateViewControllerWithIdentifier:AAPLSearchResultsViewControllerStoryboardIdentifier];

// Create the search controller and make it perform the results updating.
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
self.searchController.searchResultsUpdater = searchResultsController;
self.searchController.hidesNavigationBarDuringPresentation = NO;

/*
    Configure the search controller's search bar. For more information on how to configure
    search bars, see the "Search Bar" group under "Search".
*/
self.searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
self.searchController.searchBar.placeholder = NSLocalizedString(@"Search", nil);

// Include the search bar within the navigation bar.
self.navigationItem.titleView = self.searchController.searchBar;

self.definesPresentationContext = YES;
</code>```

I try to do the same with this code:

```<code> self.searchSuggestionsController = [[SearchSuggestionsTableViewController alloc]initWithStyle:UITableViewStylePlain];
self.searchSuggestionsController.delegate = self;
self.searchController = [[UISearchController alloc]initWithSearchResultsController:self.searchSuggestionsController];
self.searchController.delegate = self;
self.searchController.searchResultsUpdater =  self.searchSuggestionsController;
self.searchController.searchBar.delegate = self;

self.searchController.dimsBackgroundDuringPresentation = YES;
[self.searchController setHidesNavigationBarDuringPresentation:NO];

self.searchController.searchBar.searchBarStyle = UISearchBarStyleProminent;
[self.searchController.searchBar setPlaceholder:NSLocalizedString(@"Search", nil)];

[self.navigationItem setTitleView:self.searchController.searchBar];

if (self.searchQuery) {
    [self.searchController.searchBar setText:_searchQuery.queryString];
}

self.definesPresentationContext = YES;
</code>```

But when I run it on device or in simulator the search bar in the navigation bar will never become first responder. The keyboard is not showing up, I can't enter text. What I can do is use the clear button and the text clears but still I can't enter any texts.

Any ideas?

答:
Old question, but just had a similar problem. Be sure to have embedded the "searchBar" in a valid navigation controller in the VC heirachy. That happened to be my mistake. So this works;

```<code>CCCTestVC *tVC = [[CCCTestVC alloc] init];
UINavigationController *nC = [[UINavigationController alloc] initWithRootViewController:tVC];
[self.navigationController  presentViewController:nC animated:YES completion:nil];
</code>```

as opposed to doing this;

```<code>CCCTestVC *tVC = [[CCCTestVC alloc] init];
[self.navigationController pushViewController:tVC animated:YES];
</code>```

Body:
I am trying to embed a UISearchController's search bar in the titleView of my navigation controller's bar. Exactly this can be seen in the UICatalog sample code by Apple and works:

// Create the search results view controller and use it for the UISearchController.
AAPLSearchResultsViewController *searchResultsController = [self.storyboard instantiateViewControllerWithIdentifier:AAPLSearchResultsViewControllerStoryboardIdentifier];

// Create the search controller and make it perform the results updating.
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
self.searchController.searchResultsUpdater = searchResultsController;
self.searchController.hidesNavigationBarDuringPresentation = NO;

/*
    Configure the search controller's search bar. For more information on how to configure
    search bars, see the "Search Bar" group under "Search".
*/
self.searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
self.searchController.searchBar.placeholder = NSLocalizedString(@"Search", nil);

// Include the search bar within the navigation bar.
self.navigationItem.titleView = self.searchController.searchBar;

self.definesPresentationContext = YES;

I try to do the same with this code:

 self.searchSuggestionsController = [[SearchSuggestionsTableViewController alloc]initWithStyle:UITableViewStylePlain];
self.searchSuggestionsController.delegate = self;
self.searchController = [[UISearchController alloc]initWithSearchResultsController:self.searchSuggestionsController];
self.searchController.delegate = self;
self.searchController.searchResultsUpdater =  self.searchSuggestionsController;
self.searchController.searchBar.delegate = self;

self.searchController.dimsBackgroundDuringPresentation = YES;
[self.searchController setHidesNavigationBarDuringPresentation:NO];

self.searchController.searchBar.searchBarStyle = UISearchBarStyleProminent;
[self.searchController.searchBar setPlaceholder:NSLocalizedString(@"Search", nil)];

[self.navigationItem setTitleView:self.searchController.searchBar];

if (self.searchQuery) {
    [self.searchController.searchBar setText:_searchQuery.queryString];
}

self.definesPresentationContext = YES;

But when I run it on device or in simulator the search bar in the navigation bar will never become first responder. The keyboard is not showing up, I can't enter text. What I can do is use the clear button and the text clears but still I can't enter any texts.

Any ideas?

Body:
Old question, but just had a similar problem. Be sure to have embedded the "searchBar" in a valid navigation controller in the VC heirachy. That happened to be my mistake. So this works;

CCCTestVC *tVC = [[CCCTestVC alloc] init];
UINavigationController *nC = [[UINavigationController alloc] initWithRootViewController:tVC];
[self.navigationController  presentViewController:nC animated:YES completion:nil];

as opposed to doing this;

CCCTestVC *tVC = [[CCCTestVC alloc] init];
[self.navigationController pushViewController:tVC animated:YES];


问:
How does IronPython loads modules while being hosted?
I'm confused about the way IronPython loads modules while being hosted.

I'm using IronPython 2.7.7 installed using the MSI package and I've referenced C:\Program Files (x86)\IronPython 2.7\IronPython.dll and C:\Program Files (x86)\IronPython 2.7\Microsoft.Scripting.dll.

Sometimes IronPython fails to load a module throwing IronPython.Runtime.Exceptions.ImportException: 'No module named modulename', but sometimes everything works fine.

For example,

```<code>var engine = Python.CreateEngine();
engine.CreateScriptSourceFromString("import datetime; print datetime.datetime.now()").Execute();
</code>```

works, but

```<code>var engine = Python.CreateEngine();
engine.CreateScriptSourceFromString("import json; print json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])").Execute();
</code>```

doesn't.

I've found a suggestion to set search paths in engine. So I've added

```<code>var searchPaths = engine.GetSearchPaths();
searchPaths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib");
engine.SetSearchPaths(searchPaths);
</code>```

and now the example which uses json module works.

But search paths which I get from engine contain only

"."

"D:\\IronPythonTest\\bin\\Debug\\Lib"

"D:\\IronPythonTest\\bin\\Debug\\DLLs"

And I don't have neither Lib nor DLLs folders under my Debug folder.

So how does IronPython manage to load datetime module?

Thanks in advance for the clarification.

答:
Your basic approach in adding the relevant paths to the engine is correct.

IronPython uses large amounts of the standard library (wherever possible). Low level modules that are implemented natively in CPython are implemented in C# for IronPython. One of those modules is datetime. So as long as IronPython.Modules.dll is around, several standard modules are available even without specific loading/path handling.

Body:
I'm confused about the way IronPython loads modules while being hosted.

I'm using IronPython 2.7.7 installed using the MSI package and I've referenced C:\Program Files (x86)\IronPython 2.7\IronPython.dll and C:\Program Files (x86)\IronPython 2.7\Microsoft.Scripting.dll.

Sometimes IronPython fails to load a module throwing IronPython.Runtime.Exceptions.ImportException: 'No module named modulename', but sometimes everything works fine.

For example,

var engine = Python.CreateEngine();
engine.CreateScriptSourceFromString("import datetime; print datetime.datetime.now()").Execute();

works, but

var engine = Python.CreateEngine();
engine.CreateScriptSourceFromString("import json; print json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])").Execute();

doesn't.

I've found a suggestion to set search paths in engine. So I've added

var searchPaths = engine.GetSearchPaths();
searchPaths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib");
engine.SetSearchPaths(searchPaths);

and now the example which uses json module works.

But search paths which I get from engine contain only

"."

"D:\\IronPythonTest\\bin\\Debug\\Lib"

"D:\\IronPythonTest\\bin\\Debug\\DLLs"

And I don't have neither Lib nor DLLs folders under my Debug folder.

So how does IronPython manage to load datetime module?

Thanks in advance for the clarification.


问:
jQuery UI function not working
HTML:

```<code><div class="square" id="drop" data-color="red"></div>

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js" type="text/javascript"></script>
<script>
  $( ".square" ).draggable();
</script>
</code>```

For some reason this jQuery is not working at all, and I have no idea how I could fix it. Thank you

答:
You need to include jQuery UI after jQuery, as it's dependent on it.

  $( ".square" ).draggable();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
width:100px;
height:100px;
background: red;
}</code>```

```

Title: jQuery UI function not working

Body:
HTML:

For some reason this jQuery is not working at all, and I have no idea how I could fix it. Thank you

Body:
You need to include jQuery UI after jQuery, as it's dependent on it.

  $( ".square" ).draggable();

div {
width:100px;
height:100px;
background: red;
}

<div class="square" id="drop" data-color="red"></div>

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js" type="text/javascript"></script>