问:
Table from Excel to another table
Suppose there are 3 columns. In 1 column number (a1), in the second name (b1), in the third description (c1). I want to make another 1 table, so that the data would spread to it, but with 1 condition. If in the 3 column, in one cell more than 500 characters, then continue to copy the data from the rows to the next cell. (For example, there is a line a2, b2, c2 In cell c2, 600 symbols are obtained, then the remaining characters are transferred to one cell, c3 and copy the text from cells a2, b2) Is it possible to trace it? To make, some counter, that he would count the symbols in the cell.
enter image description here

table

tabletest1

答:
Well, i think this image will be self explanatory

First table contains your original data. Right upper one contains the results, and bottom one contains the formula

The formula =IF((LEN(C2) > 5);MID(C2;6;500);" ") checks the length of the text inside a cell, if its greater than 5 (you can modify this of course), then set the value of the cell to a substring (from 6th character) of the original text.

Title: Table from Excel to another table


来源: stackexchange

问:
Error on my program - How to split words by spaces on a list? Python (used Dictionaries, Lists, .txt file)
Hey my program has this which I think should work, I have gone through the whole program and everything seems fine. But somehow the program doesn't split the words in the list by spaces.
I have used lists and dictionaries in my code which seem to work, I have tested a few things but when I input the .txt file everything is fine and the program works perfectly but when you input your own words the program seems to put all of the words with spaces (example of what I mean: if I input house phone keyboard the program adds all 3 words as if they were one)

My question is how can I split the words by spaces when the user inputs the words themselves instead of using a .txt file?

```<code>#These are the helper variables
wordsList = []
wordsDict = {}
words = 0
typeFile = 0
textFile = 0
text = 0
sortValue = 0
#Here we ask the person if they want to input their own words or use a .txt
file
print("Input 'a' to input your own words or input 'b' to input text from a
.txt file")
typeFile = input()

#Here we make an if statement if they chose to input their own words
if typeFile == "a":
    print("enter 'x' when finished")
    while True:
        #Here we ask the user to input their words
        print("Input your words")
        words = input()
        #This will finish asking for input when the user enters x
        if words == 'x':
            break
        #this puts the words on the list
        wordsList.append(words)
#Here we make an if statement if they chose to use a .txt file
if typeFile == "b":
    #This asks for the .txt file they want to open
    words = input("input which .txt file you would like to use
    (text_file.txt)")
    #This opens the file
    textFile = open(words, 'r')
    text = textFile.read()
    #This adds the words of the file into the list and separates each word
    by spaces
    wordsList = text.split()

#This sorts the list
for text in range(len(wordsList)):
        #This looks if the word has been added to the dictionary
        if wordsList[text] in wordsDict.keys():
            #this will add a +1 value to the word if it is in already in the
dictionary
            wordsDict[wordsList[text]] += 1
        #This looks if the word has been added to the dictionary
        if wordsList[text] not in wordsDict.keys():
            #this adds the word to the dictionary if it isnt already in
            wordsDict[wordsList[text]] = 1

#This sorts the words from lowest to highest
sortValue = sorted(wordsDict.items(), key = lambda t:t[1])
#These will print the top 5 used words in the list
print("These are the most used 5 words")
for num in range(1,6):
    print(num,':',sortValue[num*-1])
words = input("Press return to exit.")
</code>```

答:
I have tested your code, and it works fine as long as: after choosing option a, you enter one word at a time, and then press enter. If you want to add multiple words together, with spaces in between them before pressing enter, then modify the 'if typeFile == "a":' section as follows:

```<code>if typeFile == "a":
print("enter 'x' when finished")
while True:
    #Here we ask the user to input their words
    print("Input your words")
    words = input()
    #This will finish asking for input when the user enters x
    if words == 'x':
        break
    #this puts the words on the list
    if ' ' in words:
        words=words.split()
        wordsList.extend(words)
    else:
        wordsList.append(words)
</code>```

Your program should then work, provided you provide at least 5 different words for the dictionary. If you do not, you will get a 'list index out of range' statement. To solve this, modify the section after "#These will print the top 5 used words in the list" as follows:

```<code>#These will print the top 5 used words in the list
print("These are the most used 5 words")
if len(wordsDict)<5:
    highest=len(wordsDict)
else:
    highest=6
for num in range(1,highest):
    print(num,':',sortValue[num*-1])
words = input("Press return to exit.")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hey my program has this which I think should work, I have gone through the whole program and everything seems fine. But somehow the program doesn't split the words in the list by spaces.
I have used lists and dictionaries in my code which seem to work, I have tested a few things but when I input the .txt file everything is fine and the program works perfectly but when you input your own words the program seems to put all of the words with spaces (example of what I mean: if I input house phone keyboard the program adds all 3 words as if they were one)

My question is how can I split the words by spaces when the user inputs the words themselves instead of using a .txt file?

#These are the helper variables
wordsList = []
wordsDict = {}
words = 0
typeFile = 0
textFile = 0
text = 0
sortValue = 0
#Here we ask the person if they want to input their own words or use a .txt
file
print("Input 'a' to input your own words or input 'b' to input text from a
.txt file")
typeFile = input()

#Here we make an if statement if they chose to input their own words
if typeFile == "a":
    print("enter 'x' when finished")
    while True:
        #Here we ask the user to input their words
        print("Input your words")
        words = input()
        #This will finish asking for input when the user enters x
        if words == 'x':
            break
        #this puts the words on the list
        wordsList.append(words)
#Here we make an if statement if they chose to use a .txt file
if typeFile == "b":
    #This asks for the .txt file they want to open
    words = input("input which .txt file you would like to use
    (text_file.txt)")
    #This opens the file
    textFile = open(words, 'r')
    text = textFile.read()
    #This adds the words of the file into the list and separates each word
    by spaces
    wordsList = text.split()

#This sorts the list
for text in range(len(wordsList)):
        #This looks if the word has been added to the dictionary
        if wordsList[text] in wordsDict.keys():
            #this will add a +1 value to the word if it is in already in the
dictionary
            wordsDict[wordsList[text]] += 1
        #This looks if the word has been added to the dictionary
        if wordsList[text] not in wordsDict.keys():
            #this adds the word to the dictionary if it isnt already in
            wordsDict[wordsList[text]] = 1

#This sorts the words from lowest to highest
sortValue = sorted(wordsDict.items(), key = lambda t:t[1])
#These will print the top 5 used words in the list
print("These are the most used 5 words")
for num in range(1,6):
    print(num,':',sortValue[num*-1])
words = input("Press return to exit.")

Body:
I have tested your code, and it works fine as long as: after choosing option a, you enter one word at a time, and then press enter. If you want to add multiple words together, with spaces in between them before pressing enter, then modify the 'if typeFile == "a":' section as follows:

if typeFile == "a":
print("enter 'x' when finished")
while True:
    #Here we ask the user to input their words
    print("Input your words")
    words = input()
    #This will finish asking for input when the user enters x
    if words == 'x':
        break
    #this puts the words on the list
    if ' ' in words:
        words=words.split()
        wordsList.extend(words)
    else:
        wordsList.append(words)

Your program should then work, provided you provide at least 5 different words for the dictionary. If you do not, you will get a 'list index out of range' statement. To solve this, modify the section after "#These will print the top 5 used words in the list" as follows:

#These will print the top 5 used words in the list
print("These are the most used 5 words")
if len(wordsDict)<5:
    highest=len(wordsDict)
else:
    highest=6
for num in range(1,highest):
    print(num,':',sortValue[num*-1])
words = input("Press return to exit.")


问:
Error 1064 on Mysql multiple action Trigger
I'm going crazy creating this trigger in MySql...
Could you find the error? :</p>

```<code>DELIMITER $$
CREATE TRIGGER `Gestione_qty_mov_magazzino` AFTER
INSERT ON `dj3u9lk_pods_flusso_merci_magazzi` FOR EACH ROW
BEGIN
DECLARE is_present INT default 0
SET is_present = SELECT COUNT(`dj3u9lk_pods_archivio_magazzino`.codice_articolo) FROM `dj3u9lk_pods_archivio_magazzino` WHERE `dj3u9lk_pods_archivio_magazzino`.codice_articolo = NEW.codice_articolo)
IF (is_present > 0) THEN
        UPDATE `dj3u9lk_pods_archivio_magazzino`
        SET `dj3u9lk_pods_archivio_magazzino`.quantita_presente = `dj3u9lk_pods_archivio_magazzino`.quantita_presente + NEW.quantita
        WHERE `dj3u9lk_pods_archivio_magazzino`.codice_articolo = NEW.codice_articolo AND NEW.tipo_movimentazione = 0
ELSE
        INSERT INTO `dj3u9lk_pods_archivio_magazzino` (codice_articolo)
        VALUES NEW.codice_articolo
END

 END$$
DELIMITER ;
</code>```

答:
You seem to have been a bit random with your backticks (I would remove them they aren't required) and and a bit sparing with bracketing - the select part of the set is_present needs to be bracketed as does the values clause in the insert statement. And yes the statements all need to be terminated with ;.
This code syntaxs for me.</p>

```<code>DELIMITER $$
CREATE TRIGGER Gestione_qty_mov_magazzino AFTER
INSERT ON dj3u9lk_pods_flusso_merci_magazzi FOR EACH ROW
BEGIN
DECLARE is_present INT default 0;
SET is_present = (
        SELECT COUNT(dj3u9lk_pods_archivio_magazzino.codice_articolo)
        FROM dj3u9lk_pods_archivio_magazzino
        WHERE dj3u9lk_pods_archivio_magazzino.codice_articolo = NEW.codice_articolo
        ) ;
IF is_present > 0 THEN
        UPDATE dj3u9lk_pods_archivio_magazzino
        SET dj3u9lk_pods_archivio_magazzino.quantita_presente = dj3u9lk_pods_archivio_magazzino.quantita_presente + NEW.quantita
        WHERE dj3u9lk_pods_archivio_magazzino.codice_articolo = NEW.codice_articolo AND NEW.tipo_movimentazione = 0
    ;
ELSE
        INSERT INTO dj3u9lk_pods_archivio_magazzino (codice_articolo)
        VALUES (NEW.codice_articolo)      ;
END if;

END $$
DELIMITER ;
</code>```

Body:
I'm going crazy creating this trigger in MySql...
Could you find the error? :

DELIMITER $$
CREATE TRIGGER `Gestione_qty_mov_magazzino` AFTER
INSERT ON `dj3u9lk_pods_flusso_merci_magazzi` FOR EACH ROW
BEGIN
DECLARE is_present INT default 0
SET is_present = SELECT COUNT(`dj3u9lk_pods_archivio_magazzino`.codice_articolo) FROM `dj3u9lk_pods_archivio_magazzino` WHERE `dj3u9lk_pods_archivio_magazzino`.codice_articolo = NEW.codice_articolo)
IF (is_present > 0) THEN
        UPDATE `dj3u9lk_pods_archivio_magazzino`
        SET `dj3u9lk_pods_archivio_magazzino`.quantita_presente = `dj3u9lk_pods_archivio_magazzino`.quantita_presente + NEW.quantita
        WHERE `dj3u9lk_pods_archivio_magazzino`.codice_articolo = NEW.codice_articolo AND NEW.tipo_movimentazione = 0
ELSE
        INSERT INTO `dj3u9lk_pods_archivio_magazzino` (codice_articolo)
        VALUES NEW.codice_articolo
END

 END$$
DELIMITER ;

Body:
You seem to have been a bit random with your backticks (I would remove them they aren't required) and and a bit sparing with bracketing - the select part of the set is_present needs to be bracketed as does the values clause in the insert statement. And yes the statements all need to be terminated with ;.
This code syntaxs for me.

DELIMITER $$
CREATE TRIGGER Gestione_qty_mov_magazzino AFTER
INSERT ON dj3u9lk_pods_flusso_merci_magazzi FOR EACH ROW
BEGIN
DECLARE is_present INT default 0;
SET is_present = (
        SELECT COUNT(dj3u9lk_pods_archivio_magazzino.codice_articolo)
        FROM dj3u9lk_pods_archivio_magazzino
        WHERE dj3u9lk_pods_archivio_magazzino.codice_articolo = NEW.codice_articolo
        ) ;
IF is_present > 0 THEN
        UPDATE dj3u9lk_pods_archivio_magazzino
        SET dj3u9lk_pods_archivio_magazzino.quantita_presente = dj3u9lk_pods_archivio_magazzino.quantita_presente + NEW.quantita
        WHERE dj3u9lk_pods_archivio_magazzino.codice_articolo = NEW.codice_articolo AND NEW.tipo_movimentazione = 0
    ;
ELSE
        INSERT INTO dj3u9lk_pods_archivio_magazzino (codice_articolo)
        VALUES (NEW.codice_articolo)      ;
END if;

END $$
DELIMITER ;


问:
SQL How do you SUM the fields retrieved by COUNT?
This is what I tried, but it didnt work.</p>

```<code>Select customer_id, sum(count (contact_id), count (call_id))
from contacts
limit 10
</code>```

答:
If you are trying to add together the count of contact_ids and call_ids you can simply use + between the two fields</p>

```<code>Select customer_id, count (contact_id)+count (call_id)
from contacts
limit 10
</code>```

Body:
This is what I tried, but it didnt work.

Select customer_id, sum(count (contact_id), count (call_id))
from contacts
limit 10

Body:
If you are trying to add together the count of contact_ids and call_ids you can simply use + between the two fields

Select customer_id, count (contact_id)+count (call_id)
from contacts
limit 10


问:
Mysql select where t4.name=x and t2 or t3 have a t1.user !? :)
To explain my problem lets imagine 4 tables.

```<code>users - (userid, user.data)

buy - (buyid, productid, userid, buy.conditions)

sell - (sellid, productid, userid, sell.conditions)
</code>```

product - (productid, product.data)

I want to do a select that returns all the users and product data when there is a user that have products with X on the name to buy or sell.

```<code>SELECT userid,
       USER.DATA,
       productid,
       product.DATA
FROM   users,
       buy,
       sell,
       products
WHERE  ( buy.userid = users.userid
          OR sell.userid = users.userid )
       AND ( buy.productid = product.productid
              OR buy.productid = product.productid )
       AND product.DATA LIKE '%x%'
</code>```

this doesnt work but I belive you get the idea of what I am tryng to do.

答:
Try a union like below:</p>

```<code>SELECT userid,
       USER.DATA,
       productid,
       product.DATA
FROM   users,
       buy,
       products
WHERE  (buy.userid = users.userid)
  AND  (buy.productid = product.productid)
  AND  product.DATA LIKE '%x%'
UNION
SELECT userid,
       USER.DATA,
       productid,
       product.DATA
FROM   users,
       sell,
       products
WHERE  (sell.userid = users.userid )
  AND  (sell.productid = product.productid )
  AND  product.DATA LIKE '%x%'
</code>```

ContentLicense: CC BY-SA 2.5

Body:
To explain my problem lets imagine 4 tables.

users - (userid, user.data)

buy - (buyid, productid, userid, buy.conditions)

sell - (sellid, productid, userid, sell.conditions)

product - (productid, product.data)

I want to do a select that returns all the users and product data when there is a user that have products with X on the name to buy or sell.

SELECT userid,
       USER.DATA,
       productid,
       product.DATA
FROM   users,
       buy,
       sell,
       products
WHERE  ( buy.userid = users.userid
          OR sell.userid = users.userid )
       AND ( buy.productid = product.productid
              OR buy.productid = product.productid )
       AND product.DATA LIKE '%x%'

this doesnt work but I belive you get the idea of what I am tryng to do.

Body:
Try a union like below:

SELECT userid,
       USER.DATA,
       productid,
       product.DATA
FROM   users,
       buy,
       products
WHERE  (buy.userid = users.userid)
  AND  (buy.productid = product.productid)
  AND  product.DATA LIKE '%x%'
UNION
SELECT userid,
       USER.DATA,
       productid,
       product.DATA
FROM   users,
       sell,
       products
WHERE  (sell.userid = users.userid )
  AND  (sell.productid = product.productid )
  AND  product.DATA LIKE '%x%'


问:
Select Sort by Departure on Makemytrip using Vba Internet Explorer
I am trying to select sort by Departure (early) on makemytrip (link given below) using Vba Internet explorer but not able to do it.

Link:- https://www.makemytrip.com/air/search?tripType=O&itinerary=DEL-DXB-D-30Nov2017&paxType=A-1&cabinClass=E

Please check the code given below and help the line to be get added for the same.

```<code>Sub mmtlink()

Dim IE As New SHDocVw.InternetExplorer

IE.Visible = True

IE.navigate "https://www.makemytrip.com/air/search?tripType=O&itinerary=DEL-DXB-D-30Nov2017&paxType=A-1&cabinClass=E"

IE.document.getElementById("sorterText").Click

End sub
</code>```

答:
Based on the vague discription, I had a short look on the link you provided.

Try to fill a iHTMLElementCollection with IE.document.getElementsByClassName("dropdown pull-right c-dropdown sortby-dropdown").
This will most likely you a collection of just one element - the div class containing a <button> and a
. The
 contains some
, where the third one contains the Departure sorting option.

You can point to that option from your div element via the children - for example: divelement.children(1).children(2).children(0).click

Hope that helps you to get the answer somehow. Next time: @jwdonahue said it in the comments... you need to provide some more information on your problem, what you tried, what are the exact problems, what did you try already, what is your scope?

Body:
I am trying to select sort by Departure (early) on makemytrip (link given below) using Vba Internet explorer but not able to do it.

Link:- https://www.makemytrip.com/air/search?tripType=O&itinerary=DEL-DXB-D-30Nov2017&paxType=A-1&cabinClass=E

Please check the code given below and help the line to be get added for the same.

Sub mmtlink()

Dim IE As New SHDocVw.InternetExplorer

IE.Visible = True

IE.navigate "https://www.makemytrip.com/air/search?tripType=O&itinerary=DEL-DXB-D-30Nov2017&paxType=A-1&cabinClass=E"

IE.document.getElementById("sorterText").Click

End sub

Body:
Based on the vague discription, I had a short look on the link you provided.

Try to fill a iHTMLElementCollection with IE.document.getElementsByClassName("dropdown pull-right c-dropdown sortby-dropdown").
This will most likely you a collection of just one element - the div class containing a <button> and a <ul>. The <ul> contains some <li>, where the third one contains the Departure sorting option.

You can point to that option from your div element via the children - for example: divelement.children(1).children(2).children(0).click

Hope that helps you to get the answer somehow. Next time: @jwdonahue said it in the comments... you need to provide some more information on your problem, what you tried, what are the exact problems, what did you try already, what is your scope?


问:
GSON ignore elements with wrong type
I'm using Retrofit (in combination with OkHttp and GSON) to communicate with an online webservice.
The webservice has a default wrapper around all it's responses, similar to:

```<code>{
  "resultCode":"OK",
  "resultObj":"Can be a string or JSON object / array",
  "error":"",
  "message":""
}
</code>```

In this example resultCode will either be OK or NO. Furthermore error and message only have any contents when an error has occured while processing the request. And last, but not least, resultObj will contain the actual result from the call (which is a string in the example, but some calls return a JSON array or a JSON object).

To process this meta data, I created a generic class, like this one:

public class ApiResult<T> {

    private String error;
    private String message;
    private String resultCode;
    private T resultObj;

    // + some getters, setters etcetera
}
```

<p>I've also created classes that represent the responses sometimes given in <code>resultObj</code> and I've defined an interface for use with Retrofit, that looks a bit like this:</p>

<pre class="lang-java prettyprint-override"><code>public interface SomeWebService {

    @GET("/method/string")
    ApiResult<String> someCallThatReturnsAString();

    @GET("/method/pojo")
    ApiResult<SomeMappedResult> someCallThatReturnsAnObject();

}
</code>```

As long as the request is valid this all works fine. But when an error occurs on the server side, it will still return a resultObj with a String-type. This causes someCallThatReturnsAnObject to crash inside the Retrofit RestAdapter / GSON library, with a message like this:

retrofit.RetrofitError:
  com.google.gson.JsonSyntaxException:
  java.lang.IllegalStateException:

Expected BEGIN_OBJECT but was STRING at line 1 column 110 path $.resultObj

Now, finally, my questions are:

Is there an (easy) way to tell GSON that it should just ignore (aka "nullify") a property if it does not match the expected type?

Can I tell GSON to treat empty strings as null?

答:
I'm reusing my reponse pojo.

In one response it's String and another response it's List<MajicalModel> magicalField so one parsing failed.

I change it to com.google.gson.JsonElement magicalField; it's work for me. This way it parse raw json and also ignore type mismatch.

Title: GSON ignore elements with wrong type

Body:
I'm using Retrofit (in combination with OkHttp and GSON) to communicate with an online webservice.
The webservice has a default wrapper around all it's responses, similar to:

{
  "resultCode":"OK",
  "resultObj":"Can be a string or JSON object / array",
  "error":"",
  "message":""
}

In this example resultCode will either be OK or NO. Furthermore error and message only have any contents when an error has occured while processing the request. And last, but not least, resultObj will contain the actual result from the call (which is a string in the example, but some calls return a JSON array or a JSON object).

To process this meta data, I created a generic class, like this one:

public class ApiResult<T> {

    private String error;
    private String message;
    private String resultCode;
    private T resultObj;

    // + some getters, setters etcetera
}

I've also created classes that represent the responses sometimes given in resultObj and I've defined an interface for use with Retrofit, that looks a bit like this:

public interface SomeWebService {

    @GET("/method/string")
    ApiResult<String> someCallThatReturnsAString();

    @GET("/method/pojo")
    ApiResult<SomeMappedResult> someCallThatReturnsAnObject();

}

As long as the request is valid this all works fine. But when an error occurs on the server side, it will still return a resultObj with a String-type. This causes someCallThatReturnsAnObject to crash inside the Retrofit RestAdapter / GSON library, with a message like this:

retrofit.RetrofitError:
  com.google.gson.JsonSyntaxException:
  java.lang.IllegalStateException:

Expected BEGIN_OBJECT but was STRING at line 1 column 110 path $.resultObj

Now, finally, my questions are:

Is there an (easy) way to tell GSON that it should just ignore (aka "nullify") a property if it does not match the expected type?

Can I tell GSON to treat empty strings as null?


问:
Fit YouTube video thumbnail in UIWebView on video start up
I'm loading Youtube video inside UIWebView using following code.

```<code>let videoUrl = "https://www.youtube.com/embed/F9GujgK0y2M"
let embedHTML = "<iframe width=\(self.webView.frame.size.width)\" height=\(self.webView.frame.size.height)\" src=\(videoUrl)?&playsinline=1\" frameborder=\"0\" allowfullscreen></iframe>"
</code>```

Starting thumbnail for video is very large. I need to fit it according to size of UIWebView. Please help me, How can I change it ?

答:
maybe this code can help you:</p>

```<code>let yourVideoID = "F9GujgK0y2M"
let css = ".video-container {position:relative;padding-bottom:56.25%;height:0;overflow:hidden;} .video-container iframe, .video-container object, .video-container embed { position:absolute; top:0; left:0; width:100%; height:100%; }"
let url = "https://www.youtube.com/embed/\(yourVideoID)?playsinline=1&modestbranding=1&showinfo=0&rel=0&showsearch=0&loop=1&iv_load_policy=3"
let htmlString = "<html><head><style type=\"text/css\">\(css)</style></head><body><div class=\"video-container\"><iframe src=\"\(url)\" frameborder=\"0\"></iframe></div></body></html>"

yourWebView.scalesPageToFit = false
yourWebView.allowsInlineMediaPlayback = true;
yourWebView.loadHTMLString(htmlString, baseURL: nil)
</code>```

Body:
I'm loading Youtube video inside UIWebView using following code.

let videoUrl = "https://www.youtube.com/embed/F9GujgK0y2M"
let embedHTML = ""

Starting thumbnail for video is very large. I need to fit it according to size of UIWebView. Please help me, How can I change it ?

Body:
maybe this code can help you:

let yourVideoID = "F9GujgK0y2M"
let css = ".video-container {position:relative;padding-bottom:56.25%;height:0;overflow:hidden;} .video-container iframe, .video-container object, .video-container embed { position:absolute; top:0; left:0; width:100%; height:100%; }"
let url = "https://www.youtube.com/embed/\(yourVideoID)?playsinline=1&modestbranding=1&showinfo=0&rel=0&showsearch=0&loop=1&iv_load_policy=3"
let htmlString = "<html><head><style type=\"text/css\">\(css)</style></head><body><div class=\"video-container\"><iframe src=\"\(url)\" frameborder=\"0\"></iframe></div></body></html>"

yourWebView.scalesPageToFit = false
yourWebView.allowsInlineMediaPlayback = true;
yourWebView.loadHTMLString(htmlString, baseURL: nil)


问:
RewriteRule on two directories
I'm trying to keep the user-end pages and the backend pages seperated by adding cms/ in front of the URL. My .htaccess file looks like this.

```<code>RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [NC]
RewriteRule ^cms/(.*)$ cms/index.php?url=$1 [NC]
</code>```

My directory looks like this :

```<code>> Project
   > cms
      index.php
      cms_page1.php
      cms_page2.php
   > pages
      page1.php
      page2.php
      page3.php
.htaccess
index.php
</code>```

In my outer index.php I include al the pages in pages folder by the URL parameter url. Those will be for the user-end pages. I'm doing this because in that index page I also have the styling and navigation for all the pages. I want to do the same thing for the pages in the cms folder.

When I go to www.mysite.com/cms/, it goes to the index page in the cms directory like it is supposed to. But when I go to  www.mysite.com/cms/cms_page1, it goes to the outer index file and the url parameter in that file is cms/cms_page1. But what I want it to do is this: cms/index.php?url=cms_page1 so it opens the index.php in the cms directory and then includes the cms_page1 page.

答:
I'm not sure why this is happening. You should enable logging so you can see how URLs are being rewritten.

I suspect it has to do with the order of your rules, and that you're not stopping once certain rules match.

Try this:

```<code>RewriteRule ^cms/(.*)$ cms/index.php?url=$1 [L,NC]
RewriteRule ^(.*)$ index.php?url=$1 [NC]
</code>```

Adding the L flag stops any other rules being applied.

Title: RewriteRule on two directories

Body:
I'm trying to keep the user-end pages and the backend pages seperated by adding cms/ in front of the URL. My .htaccess file looks like this.

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [NC]
RewriteRule ^cms/(.*)$ cms/index.php?url=$1 [NC]

My directory looks like this :

> Project
   > cms
      index.php
      cms_page1.php
      cms_page2.php
   > pages
      page1.php
      page2.php
      page3.php
.htaccess
index.php

In my outer index.php I include al the pages in pages folder by the URL parameter url. Those will be for the user-end pages. I'm doing this because in that index page I also have the styling and navigation for all the pages. I want to do the same thing for the pages in the cms folder.

When I go to www.mysite.com/cms/, it goes to the index page in the cms directory like it is supposed to. But when I go to  www.mysite.com/cms/cms_page1, it goes to the outer index file and the url parameter in that file is cms/cms_page1. But what I want it to do is this: cms/index.php?url=cms_page1 so it opens the index.php in the cms directory and then includes the cms_page1 page.

Body:
I'm not sure why this is happening. You should enable logging so you can see how URLs are being rewritten.

I suspect it has to do with the order of your rules, and that you're not stopping once certain rules match.

Try this:

RewriteRule ^cms/(.*)$ cms/index.php?url=$1 [L,NC]
RewriteRule ^(.*)$ index.php?url=$1 [NC]

Adding the L flag stops any other rules being applied.


问:
How to use React with Python and keep both frontend and backend separate?
I am using React as frontend and  Python & Flask as my backend with Rauth as OAuth2 for Facebook login and storing details of every user in db and using flask_login as protection. Those information are Sports, Education, Phone number and other things.

What I am doing is after user gets logged in I am trying to fetch his details from react app. But I am getting error user not logged in while on browser if I open that API I can see the json.

```<code>@login_manager.user_loader
def load_user(id):
    return User.select().where(User.id == id).first()

@app.route('/')
def index():
    return redirect(WEB_URL)

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(WEB_URL)

@app.route('/me')
@login_required  # After removing decorator still I am not getting
def me():
    return jsonify({'email': current_user.email}), 200

@app.route('/authorize/<provider>')
def oauth_authorize(provider):
    if not current_user.is_anonymous:
        return redirect(WEB_URL)
    oauth = OAuthSignIn.get_provider(provider)
    return oauth.authorize()

@app.route('/callback/<provider>')
def oauth_callback(provider):
    if not current_user.is_anonymous:
        return redirect(WEB_URL)
    oauth = OAuthSignIn.get_provider(provider)
    social_id, username, email = oauth.callback()
    if social_id is None:
        return redirect(WEB_URL)
    user = User.select().where(User.social_id == social_id).first()
    if not user:
        user = User(social_id=social_id, nickname=username, email=email)
        user.save()
    login_user(user, True)
    return redirect(WEB_URL)
</code>```

So from fronend I am calling /authorize/<provider> which then redirects to /callback/<provider> and logs user in.

Now When I am opening /me on browser it works fine returns required json or redirects me to homepage.

But when I am trying to fetch the api from frontend or Postman either I am getting user not found (if I remove the decorator login_required) or returning the whole homepage.

I am fetching like this:

```<code>componentWillMount() {
    fetch('http://localhost:5000/me').then(function(response) {
      const contentType = response.headers.get("content-type");
      if(contentType && contentType.includes("application/json")) {
        return response.json();
      }
    }).then(function(json) {
        debugger
        const self = this;
        if (json) self.serState({ loggedIn: true });
    }).catch(function(error) { console.log(error); });
  }
</code>```

My frontend is running on http://localhost:3000/

Got the Answer
Backend add this line after importing flask_cors

```<code>CORS(app, supports_credentials=True)
</code>```

And Fetch using

```<code>fetch('http://localhost:5000/me', {
      method: 'GET',
      credentials: 'include'
    })
</code>```

答:
Install flask restful
https://flask-restful.readthedocs.io/en/latest/

Use rxjs to grab data from the api using a "service"

Body:
I am using React as frontend and  Python & Flask as my backend with Rauth as OAuth2 for Facebook login and storing details of every user in db and using flask_login as protection. Those information are Sports, Education, Phone number and other things.

What I am doing is after user gets logged in I am trying to fetch his details from react app. But I am getting error user not logged in while on browser if I open that API I can see the json.

@login_manager.user_loader
def load_user(id):
    return User.select().where(User.id == id).first()

@app.route('/')
def index():
    return redirect(WEB_URL)

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(WEB_URL)

@app.route('/me')
@login_required  # After removing decorator still I am not getting
def me():
    return jsonify({'email': current_user.email}), 200

@app.route('/authorize/<provider>')
def oauth_authorize(provider):
    if not current_user.is_anonymous:
        return redirect(WEB_URL)
    oauth = OAuthSignIn.get_provider(provider)
    return oauth.authorize()

@app.route('/callback/<provider>')
def oauth_callback(provider):
    if not current_user.is_anonymous:
        return redirect(WEB_URL)
    oauth = OAuthSignIn.get_provider(provider)
    social_id, username, email = oauth.callback()
    if social_id is None:
        return redirect(WEB_URL)
    user = User.select().where(User.social_id == social_id).first()
    if not user:
        user = User(social_id=social_id, nickname=username, email=email)
        user.save()
    login_user(user, True)
    return redirect(WEB_URL)

So from fronend I am calling /authorize/<provider> which then redirects to /callback/<provider> and logs user in.

Now When I am opening /me on browser it works fine returns required json or redirects me to homepage.

But when I am trying to fetch the api from frontend or Postman either I am getting user not found (if I remove the decorator login_required) or returning the whole homepage.

I am fetching like this:

componentWillMount() {
    fetch('http://localhost:5000/me').then(function(response) {
      const contentType = response.headers.get("content-type");
      if(contentType && contentType.includes("application/json")) {
        return response.json();
      }
    }).then(function(json) {
        debugger
        const self = this;
        if (json) self.serState({ loggedIn: true });
    }).catch(function(error) { console.log(error); });
  }

My frontend is running on http://localhost:3000/

Got the Answer
Backend add this line after importing flask_cors

CORS(app, supports_credentials=True)

And Fetch using

fetch('http://localhost:5000/me', {
      method: 'GET',
      credentials: 'include'
    })


问:
elastic search setup in asp.net mvc
I am working on an asp.net application where I have huge database. I want to implement elastic search. Here is what I have done in code:

```<code>var node = new Uri("http://localhost:9200/");
            var setting = new ConnectionSettings(node);
            setting.DefaultIndex("businessuser");
            client = new ElasticClient(setting);

 CanadaBusinessDBEntities db = new CanadaBusinessDBEntities();
            client.DeleteIndex("businessuser", null);
            var ListofBusiness = db.CanadaTables.ToList();
            foreach (var Business in ListofBusiness)
            {
                var resutl = client.Index(Business, null);
            }
</code>```

This code is written in constructor which gets all records and then index them using elastic search. indexing is taking long time. I want to ask if this is correct way? I am new to elastic search. please suggest better way to do this.

Thanks.

答:
You have to use ElasticsearchContext Class of Nest.

```<code>private readonly ElasticsearchContext _elasticsearchContext;
private const string ConnectionString = "http://localhost:9200";
private readonly IElasticsearchMappingResolver _elasticsearchMappingResolver;

_elasticsearchMappingResolver = new ElasticsearchMappingResolver();
_elasticsearchContext = new ElasticsearchContext(ConnectionString, new ElasticsearchSerializerConfiguration(_elasticsearchMappingResolver,true,true));
</code>```

for Delete purpose you can use like that below

```<code> public void DeleteSkill(int  Id)
        {
            _elasticsearchContext.DeleteDocument<Tag>(Id);
            _elasticsearchContext.SaveChanges();
        }
</code>```

Title: elastic search setup in asp.net mvc

Body:
I am working on an asp.net application where I have huge database. I want to implement elastic search. Here is what I have done in code:

var node = new Uri("http://localhost:9200/");
            var setting = new ConnectionSettings(node);
            setting.DefaultIndex("businessuser");
            client = new ElasticClient(setting);

 CanadaBusinessDBEntities db = new CanadaBusinessDBEntities();
            client.DeleteIndex("businessuser", null);
            var ListofBusiness = db.CanadaTables.ToList();
            foreach (var Business in ListofBusiness)
            {
                var resutl = client.Index(Business, null);
            }

This code is written in constructor which gets all records and then index them using elastic search. indexing is taking long time. I want to ask if this is correct way? I am new to elastic search. please suggest better way to do this.

Thanks.

Body:
You have to use ElasticsearchContext Class of Nest.

private readonly ElasticsearchContext _elasticsearchContext;
private const string ConnectionString = "http://localhost:9200";
private readonly IElasticsearchMappingResolver _elasticsearchMappingResolver;

_elasticsearchMappingResolver = new ElasticsearchMappingResolver();
_elasticsearchContext = new ElasticsearchContext(ConnectionString, new ElasticsearchSerializerConfiguration(_elasticsearchMappingResolver,true,true));

for Delete purpose you can use like that below

 public void DeleteSkill(int  Id)
        {
            _elasticsearchContext.DeleteDocument<Tag>(Id);
            _elasticsearchContext.SaveChanges();
        }


问:
Is it possible to sort a table column based on a month in griddle
I have a timestamp returned like this:

Fri Jun 30 2017 09:57:18 GMT+0100 (BST)

and I formatted it to look like this :
Jun 30, Fri 2017 09:57

When it is sorted in the Griddle it is sorted alphabetically
(apr,aug,dec,feb,jan,jul,jun,mar,may,nov,oct,sep) as it should but I really want to have them sorted according to months.

sortType: 'date' in metacolumns does not work.

```<code>return (<Griddle results={lRowData}
            columns={this.columns()}
            columnMetadata={this.columnMetadata()}
            initialSort="date"
            resultsPerPage={20}/>
        );
},
columns() {
    const lColumns = ['date'];
    return lColumns;
},
columnMetadata() {
    const lColumnMetadata = [{
        columnName: 'date',
        displayName: 'Date'
    }];
    return lColumnMetadata;
}
</code>```

Is there a way to use some kind of indexed table like:

allMonths = ['Jan' , 'Feb', 'Mar', 'Apr', 'May',...., 'Dec'] where will be the one that helps on sorting them ?

答:
For Griddle v0.x, check out customCompareFn (docs), e.g.

```<code>const allMonths = ['Jan', 'Feb', ...];
const lColumnMetadata = [{
    columnName: 'date',
    customCompareFn: date => allMonths.indexOf(date.substring(0, 3)),
    displayName: 'Date'
}];
</code>```

Body:
I have a timestamp returned like this:

Fri Jun 30 2017 09:57:18 GMT+0100 (BST)

and I formatted it to look like this :
Jun 30, Fri 2017 09:57

When it is sorted in the Griddle it is sorted alphabetically
(apr,aug,dec,feb,jan,jul,jun,mar,may,nov,oct,sep) as it should but I really want to have them sorted according to months.

sortType: 'date' in metacolumns does not work.

return (<Griddle results={lRowData}
            columns={this.columns()}
            columnMetadata={this.columnMetadata()}
            initialSort="date"
            resultsPerPage={20}/>
        );
},
columns() {
    const lColumns = ['date'];
    return lColumns;
},
columnMetadata() {
    const lColumnMetadata = [{
        columnName: 'date',
        displayName: 'Date'
    }];
    return lColumnMetadata;
}

Is there a way to use some kind of indexed table like:

allMonths = ['Jan' , 'Feb', 'Mar', 'Apr', 'May',...., 'Dec'] where will be the one that helps on sorting them ?

Body:
For Griddle v0.x, check out customCompareFn (docs), e.g.

const allMonths = ['Jan', 'Feb', ...];
const lColumnMetadata = [{
    columnName: 'date',
    customCompareFn: date => allMonths.indexOf(date.substring(0, 3)),
    displayName: 'Date'
}];


问:
pre set value for dropdown in angular 2
I have a drop down to select countries from a back-end API call.

code:

```<code>this.http.get(SERVER_URL+"/edit/getAllCountry")
    .subscribe((res) => {
        this.countries = res;
    });
</code>```

this will returns me list of countries from my database.

ill be printing them in html like:

billingPage.html

```<code><select [(ngModel)]="country" (ngModelChange)="countryChanged(country)" >
                            <option *ngFor="let c of countries" [ngValue] = 'c'> {{c.countryName}} </option>
                        </select>
</code>```

the question is , before coming to this billing.html page I have a selected value for the country. for example I have selected 'USA' and how can I load it in into to the dropdown when the page is loaded.

in the dropdown list 'USA' should be selected when the page loads.

答:
Try this,

Ts

```<code> selectedcountry:any;

 this.selectedcountry="USA";
 this.http.get(SERVER_URL+"/edit/getAllCountry")
.subscribe((res) => {
    this.countries = res;
});
</code>```

it is custom example .Once we selected and save into DB means, call another API which we saved the values, like below example:

```<code> this.http.get(SERVER_URL+"/edit/getselectedCountry")
.subscribe((data) => {
    this.selectedcountry = data;
});
</code>```

billingPage.html

```<code>  <select [(ngModel)]="selectedcountry"  >
  <option *ngFor="let c of countries" [selected]="selectedcountry==c.countryName" value="{{c.countryName}}"> {{c.countryName}}
  </option>
</code>```

Title: pre set value for dropdown in angular 2

Body:
I have a drop down to select countries from a back-end API call.

code:

this.http.get(SERVER_URL+"/edit/getAllCountry")
    .subscribe((res) => {
        this.countries = res;
    });

this will returns me list of countries from my database.

ill be printing them in html like:

billingPage.html

<select [(ngModel)]="country" (ngModelChange)="countryChanged(country)" >
                            <option *ngFor="let c of countries" [ngValue] = 'c'> {{c.countryName}} </option>
                        </select>

the question is , before coming to this billing.html page I have a selected value for the country. for example I have selected 'USA' and how can I load it in into to the dropdown when the page is loaded.

in the dropdown list 'USA' should be selected when the page loads.

Body:
Try this,

Ts

 selectedcountry:any;

 this.selectedcountry="USA";
 this.http.get(SERVER_URL+"/edit/getAllCountry")
.subscribe((res) => {
    this.countries = res;
});

it is custom example .Once we selected and save into DB means, call another API which we saved the values, like below example:

 this.http.get(SERVER_URL+"/edit/getselectedCountry")
.subscribe((data) => {
    this.selectedcountry = data;
});

billingPage.html

  <select [(ngModel)]="selectedcountry"  >
  <option *ngFor="let c of countries" [selected]="selectedcountry==c.countryName" value="{{c.countryName}}"> {{c.countryName}}
  </option>


问:
FontAwesome caret down does not appear in ngClass
I have a strange issue where I need to show the fontawesome caret up and down on sorting the field.But only the fa-caret-up is shown but not fa-caret-down.I am using the below code.

HTML

```<code> <th (click)="sort('ref')">Ref {{reverse}}
    <span *ngIf="sortKey=='ref'"  ><i  [ngClass]="{'fa fa-caret-down':reverse,'fa fa-caret-up':!reverse}" ></i></span>
 </th>
</code>```

TS

```<code>     sortKey:string = "";
     reverse:boolean = true;

  sort(field){
    this.sortKey = field;
    this.reverse = !this.reverse;

  }
</code>```

On Inspecting the html generated I observe that fa is not concatenated when fa-caret-down.But it is concatenated when fa-caret-up is shown.Is this a bug in Angular 4?

I also tried concatenating the class="fa" before it with no difference.Please Clarify.

答:
It is strange, when reverse is true, it removes fa class from fa-caret-down.

This works,

```<code><span><i class="fa" [ngClass]="{'fa-caret-down':reverse,'fa-caret-up':!reverse}" ></i></span>
</code>```

edit: also you can use,

```<code><span><i [ngClass]="reverse ? 'fa fa-caret-down': 'fa fa-caret-up'" ></i></span>
</code>```

Body:
I have a strange issue where I need to show the fontawesome caret up and down on sorting the field.But only the fa-caret-up is shown but not fa-caret-down.I am using the below code.

HTML

 Ref {{reverse}}

TS

     sortKey:string = "";
     reverse:boolean = true;

  sort(field){
    this.sortKey = field;
    this.reverse = !this.reverse;

  }

On Inspecting the html generated I observe that fa is not concatenated when fa-caret-down.But it is concatenated when fa-caret-up is shown.Is this a bug in Angular 4?

I also tried concatenating the class="fa" before it with no difference.Please Clarify.

Body:
It is strange, when reverse is true, it removes fa class from fa-caret-down.

This works,

<span><i class="fa" [ngClass]="{'fa-caret-down':reverse,'fa-caret-up':!reverse}" ></i></span>

edit: also you can use,

<span><i [ngClass]="reverse ? 'fa fa-caret-down': 'fa fa-caret-up'" ></i></span>


问:
xhtml code "float: right" and "clear: right" is not working
The image file is floating to the right ok.  It is the paragraph with a span style with a "clear: right" attribute that is not clearing the image.  The text is appearing before the margin to the right is clear of an element, in this case an image.

Here is the all the code that is between the body tags.  The file has the xml prolog,has a DTD that is using xhtml transitional, the opening  tag includes an xmlns attribute that specifies the HTML namespace.

```<code><h1 style="text-align: center">Tourist Attractions</h1>

<hr />

<p>
<img src="images/child.jpg" alt="child" style="border: 5px ridge orange;
float: right" />
<span style="font-weight: bold; font-family: arial, helvetica, sans serif;
color: darkblue">

The City of Desert Park has many opportunities for fun, recreation, and
entertainment. Throughout every month, you will find activities for all ages
and lifestyles. The weather in Desert Park is conducive to outdoor
activities year-round.

</span>
</p>
<p><span style="font-family: arial, helvetica, sans-serif; color: darkblue;
clear: right">

Visit the Parks and Recreation Page for the latest information on the
Basketball League Play-off Games.

</span>
</p>
</code>```

It is the second paragraph that is not clearing the image to the right.  I know a "clear" attribute only clears a preceding element.  But the image is before the "clear" tag.  I just can't figure out why it is not clearing.  It has been a few years since I last used xhtml.  I know that html5 is the thing but the DTD is pointing to xhtml transitional so it should still work.

Can someone tell me why the second paragraph is not clearing the image to the right? I probably have been thinking about this too much and the answer is right in front of me.  Thank you for your responses.

答:
The clear property only applies to block level elements. Span elements are, by default, inline level and you are not changing that. Move the clear:right to the span's containing p element, and the clear will take effect.

This is not specific to XHTML 1.0 Transitional. HTML5 would be exactly the same.

Body:
The image file is floating to the right ok.  It is the paragraph with a span style with a "clear: right" attribute that is not clearing the image.  The text is appearing before the margin to the right is clear of an element, in this case an image.

Here is the all the code that is between the body tags.  The file has the xml prolog,has a DTD that is using xhtml transitional, the opening  tag includes an xmlns attribute that specifies the HTML namespace.

Tourist Attractions

The City of Desert Park has many opportunities for fun, recreation, and
entertainment. Throughout every month, you will find activities for all ages
and lifestyles. The weather in Desert Park is conducive to outdoor
activities year-round.

Visit the Parks and Recreation Page for the latest information on the
Basketball League Play-off Games.

It is the second paragraph that is not clearing the image to the right.  I know a "clear" attribute only clears a preceding element.  But the image is before the "clear" tag.  I just can't figure out why it is not clearing.  It has been a few years since I last used xhtml.  I know that html5 is the thing but the DTD is pointing to xhtml transitional so it should still work.

Can someone tell me why the second paragraph is not clearing the image to the right? I probably have been thinking about this too much and the answer is right in front of me.  Thank you for your responses.


问:
How to fill a vector with the results of a for loop in julia?
I'm building a kalman filter to extimate arma models, now I've made it for an arma(1,1). In order to optimize the likelihood function I need to store all the values of the innovations and of them covariance matrix.
I'm new to julia and I've used mostly r.
 That's my code:

```<code>    for i=1:length(y)
x=A*x
Vt=y[i]-Z'x
Ft=Z'*P*Z
Kt=(A*P*Z)/Ft
x=A*x+Kt*Vt
P=A*(P-(P*Z*Z'*P)/Ft)*A'+R*R'*sigma^2
end
</code>```

And it's working. If i try to store the Vt values in this way:

```<code>v= zeros(1:1000)
for i=1:length(y)
x=A*x
Vt=y[i]-Z'x
v[i]=Vt
Ft=Z'*P*Z
Kt=(A*P*Z)/Ft
x=A*x+Kt*Vt
P=A*(P-(P*Z*Z'*P)/Ft)*A'+R*R'*sigma^2
end
</code>```

I get an error message thta says: "MethodError: Cannot convert an object of type Array{Float64,1} to an object of type Int64"
I've tried to do it in different ways, like using dataframs etc, but i keep reciving errors about the type of objects not being convertible, I only managed to save the last value of Vt as a dataframe, but i need its values during all the loop.
How could i solve this problem? I think that it's someting really simple but i'm not used to program. Thank you!

答:
Reiterating answers from comments:

Change the zeros(1:1000) to zeros(1000). And make sure RHS and LHS of assignment v[i]=Vt are of the same shape/type by replacing with v[i]=Vt[1] or making sure Vt is a scalar.

Passing an AbstractVector a (this time a was 1:1000) to zeros calls zeros(typeof(a), length(a)), which is often convenient but surprising sometimes.

Body:
I'm building a kalman filter to extimate arma models, now I've made it for an arma(1,1). In order to optimize the likelihood function I need to store all the values of the innovations and of them covariance matrix.
I'm new to julia and I've used mostly r.
 That's my code:

    for i=1:length(y)
x=A*x
Vt=y[i]-Z'x
Ft=Z'*P*Z
Kt=(A*P*Z)/Ft
x=A*x+Kt*Vt
P=A*(P-(P*Z*Z'*P)/Ft)*A'+R*R'*sigma^2
end

And it's working. If i try to store the Vt values in this way:

v= zeros(1:1000)
for i=1:length(y)
x=A*x
Vt=y[i]-Z'x
v[i]=Vt
Ft=Z'*P*Z
Kt=(A*P*Z)/Ft
x=A*x+Kt*Vt
P=A*(P-(P*Z*Z'*P)/Ft)*A'+R*R'*sigma^2
end

I get an error message thta says: "MethodError: Cannot convert an object of type Array{Float64,1} to an object of type Int64"
I've tried to do it in different ways, like using dataframs etc, but i keep reciving errors about the type of objects not being convertible, I only managed to save the last value of Vt as a dataframe, but i need its values during all the loop.
How could i solve this problem? I think that it's someting really simple but i'm not used to program. Thank you!


问:
Equivalent in git of "hg cat" or "svn cat"
I want to extract a copy of the latest version of a file held in a git repository, and pass it into a script for some processing.  With svn or hg, I just use the "cat" command:

Print the specified files as they were at the given revision. If
  no revision is given, the parent of the working directory is used,
  or tip if no revision is checked out.

(that's from the description of hg cat in the hg documentation)

What's the equivalent command to do this with git?

答:
Also work with branch names (like HEAD in the 1st p) :</p>

```<code>git show $branch:$filename
</code>```

Body:
Also work with branch names (like HEAD in the 1st p) :

git show $branch:$filename


问:
Passing arguments to an interactive program non interactively but based on output
My question is an enhancement for the following one passing arguments to an interactive program non interactively.

I am using a script which will ask me to choose an option from the list:

```<code>1 - ABC
2 - CDE
3 - EFG
</code>```

I know which option I should choose based on letters, but script expect to provide a number.

Is there any way to do it in a non-interactive way? I mean to pass a "parameter" which will find a number based on the given letters.

[EDIT 1]

I see that my description is not very clear, therefore I am adding a test case.
I have a script: test.sh. It is the interactive script, so question are asked when I run it:

```<code>./test.sh
Are you sure you want to run it? (y/n): y
Please choose option:
1 - ABC
2 - CDE
3 - EFG
1
</code>```

To run this script in a non-interactive way I am using:

```<code>echo "y
1" | test.sh
</code>```

The problem is that when I am running the script I don't know which number is assigned to the option that I would like to choose.

答:
Posing this question I was looking for any hint how to start with this task. After spending hours on searching finally I managed to implement sth that meets my requirements using expect script.

If you have any idea how to improve this script, any comments are welcome.

```<code>#!/usr/bin/expect -f

proc parse_output {search_in to_find} {
    set lines [split $search_in \n]
    foreach line $lines {
        if {[regexp "$to_find" $line]} {
            puts $line
            set i [string first "-" $line]
            set n [string range $line 0 [expr {$i-1}]]
            set nn [string trim $n]
            send -- "$nn\r"
        }
    }
}

set PARAM1 [lindex $argv 0]

spawn deploy
expect "?choose change to deploy:"
parse_output $expect_out(buffer) "$PARAM1\r"
expect "$" {send "\r"}
</code>```

Body:
My question is an enhancement for the following one passing arguments to an interactive program non interactively.

I am using a script which will ask me to choose an option from the list:

1 - ABC
2 - CDE
3 - EFG

I know which option I should choose based on letters, but script expect to provide a number.

Is there any way to do it in a non-interactive way? I mean to pass a "parameter" which will find a number based on the given letters.

[EDIT 1]

I see that my description is not very clear, therefore I am adding a test case.
I have a script: test.sh. It is the interactive script, so question are asked when I run it:

./test.sh
Are you sure you want to run it? (y/n): y
Please choose option:
1 - ABC
2 - CDE
3 - EFG
1

To run this script in a non-interactive way I am using:

echo "y
1" | test.sh

The problem is that when I am running the script I don't know which number is assigned to the option that I would like to choose.

Body:
Posing this question I was looking for any hint how to start with this task. After spending hours on searching finally I managed to implement sth that meets my requirements using expect script.

If you have any idea how to improve this script, any comments are welcome.

#!/usr/bin/expect -f

proc parse_output {search_in to_find} {
    set lines [split $search_in \n]
    foreach line $lines {
        if {[regexp "$to_find" $line]} {
            puts $line
            set i [string first "-" $line]
            set n [string range $line 0 [expr {$i-1}]]
            set nn [string trim $n]
            send -- "$nn\r"
        }
    }
}

set PARAM1 [lindex $argv 0]

spawn deploy
expect "?choose change to deploy:"
parse_output $expect_out(buffer) "$PARAM1\r"
expect "$" {send "\r"}


答:
Try this:

```<code>webView.scalesPageToFit = true
</code>```

From Apple Documentation, setting this to true scales the webpage to fit the screen.

Title: Fit YouTube video thumbnail in UIWebView on video start up

Body:
I'm loading Youtube video inside UIWebView using following code.

let videoUrl = "https://www.youtube.com/embed/F9GujgK0y2M"
let embedHTML = ""

Starting thumbnail for video is very large. I need to fit it according to size of UIWebView. Please help me, How can I change it ?

Body:
Try this:

webView.scalesPageToFit = true

From Apple Documentation, setting this to true scales the webpage to fit the screen.


问:
Why does the application crash when I press the button to insert the values in the table?
DataBaseHelper

```<code>    public class DataBaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME ="Glucoplate.bd";
    public static final String TABLE_NAME ="User_table";

    public static final String COL_1 = "ID";
    public static final String COL_2 ="NAME";
    public static final String COL_3 = "SURNAME";
    public static final String COL_4 = "MARKS";

    public DataBaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE" + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,SURNAME TEXT, MARKS INTEGER)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXIST "+TABLE_NAME);
    }
    public boolean insertData(String name, String surname, String marks){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,name);
        contentValues.put(COL_3,surname);
        contentValues.put(COL_4, marks);
        long result = db.insert(TABLE_NAME,null,contentValues);
        db.close();

        if (result == -1) {
            return false;
        }else{
         return true;
        }
    }
}
</code>```

I followed the tutorial in Android Academy, but i doesn't want to work, even after, Building, and cleaning the project.

MainActivity

```<code>public class MainActivity extends AppCompatActivity {

    DataBaseHelper myDb;
    EditText txtName, txtSurname, txtMarks;
    Button btnClick;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    myDb= new DataBaseHelper(this);
        txtName = (EditText) findViewById(R.id.idName);
        txtSurname = (EditText) findViewById(R.id.idSurname);
        txtMarks =(EditText) findViewById(R.id.idMarks);
        btnClick = (Button) findViewById(R.id.idBtn);
        btnClick.setOnClickListener(new View.OnClickListener(){
            @Override
        public void onClick(View v){
            ClickMe();
        }
        });
    }

    private void ClickMe(){
        String name= txtName.getText().toString();
        String surname = txtSurname.getText().toString();
        String marks = txtMarks.getText().toString();
        Boolean result= myDb.insertData(name, surname, marks);
        if(result == true){
            Toast.makeText(this, "agragado", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this,"Fallo",Toast.LENGTH_SHORT).show();
        }
    }
}
</code>```

I'm using android Nougat, i tried another 4 methods and still doesn't work; Also the ID doesn't show any error, warning or anything it just crash.

答: According to your code and stacktrace, you didn't add a space " " between the CREATE TABLE and TABLE_NAME. Add a " " after TABLE_NAME too.

Body:
DataBaseHelper

    public class DataBaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME ="Glucoplate.bd";
    public static final String TABLE_NAME ="User_table";

    public static final String COL_1 = "ID";
    public static final String COL_2 ="NAME";
    public static final String COL_3 = "SURNAME";
    public static final String COL_4 = "MARKS";

    public DataBaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE" + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,SURNAME TEXT, MARKS INTEGER)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXIST "+TABLE_NAME);
    }
    public boolean insertData(String name, String surname, String marks){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,name);
        contentValues.put(COL_3,surname);
        contentValues.put(COL_4, marks);
        long result = db.insert(TABLE_NAME,null,contentValues);
        db.close();

        if (result == -1) {
            return false;
        }else{
         return true;
        }
    }
}

I followed the tutorial in Android Academy, but i doesn't want to work, even after, Building, and cleaning the project.

MainActivity

public class MainActivity extends AppCompatActivity {

    DataBaseHelper myDb;
    EditText txtName, txtSurname, txtMarks;
    Button btnClick;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    myDb= new DataBaseHelper(this);
        txtName = (EditText) findViewById(R.id.idName);
        txtSurname = (EditText) findViewById(R.id.idSurname);
        txtMarks =(EditText) findViewById(R.id.idMarks);
        btnClick = (Button) findViewById(R.id.idBtn);
        btnClick.setOnClickListener(new View.OnClickListener(){
            @Override
        public void onClick(View v){
            ClickMe();
        }
        });
    }

    private void ClickMe(){
        String name= txtName.getText().toString();
        String surname = txtSurname.getText().toString();
        String marks = txtMarks.getText().toString();
        Boolean result= myDb.insertData(name, surname, marks);
        if(result == true){
            Toast.makeText(this, "agragado", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this,"Fallo",Toast.LENGTH_SHORT).show();
        }
    }
}

I'm using android Nougat, i tried another 4 methods and still doesn't work; Also the ID doesn't show any error, warning or anything it just crash.


问:
StatFs returns different size from setting
I am trying to get the storage space on Android. Here is the solution I found.

```<code>StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath())
stat.getTotalBytes()
</code>```

It returns 774 MB while the setting app shows1 GB. In AVD Manager, size on disk is 1 GB. Is it possible to get the same value like setting app?

答:
below are methods to check if there is external sd-card  available, total space and free space in internal storage and external sd- card</p>

```<code>public boolean isExternalSDCardAvailable() {
    String secStore = System.getenv("SECONDARY_STORAGE");
    if (secStore != null) {
        File f_secs = new File(secStore);
        return f_secs.exists();
    } else return false;
}

public long getAvailableInternalMemorySize() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
        long bytesAvailable = stat.getBlockSizeLong() * stat.getFreeBlocksLong();
        return bytesAvailable / (1024 * 1024);
    } else {
        StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
        long bytesAvailable = (long) stat.getBlockSize() * (long) stat.getFreeBlocks();
        return bytesAvailable / (1024 * 1024);
    }
}

public long getTotalInternalMemorySize() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
        long bytesAvailable = stat.getBlockSizeLong() * stat.getBlockCountLong();
        return bytesAvailable / (1024 * 1024);
    } else {
        StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
        long bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks();
        return bytesAvailable / (1024 * 1024);
    }
}

public long getAvailableExternalMemorySize() {
    String secStore = System.getenv("SECONDARY_STORAGE");
    File f_secs = new File(secStore);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        StatFs stat = new StatFs(f_secs.getPath());
        long bytesAvailable = stat.getBlockSizeLong() * stat.getAvailableBlocksLong();
        return bytesAvailable / (1024 * 1024);
    } else {
        StatFs stat = new StatFs(f_secs.getPath());
        long bytesAvailable = stat.getBlockSize() * stat.getAvailableBlocks();
        return bytesAvailable / (1024 * 1024);
    }

}

public Long getTotalExternalMemorySize() {
    String secStore = System.getenv("SECONDARY_STORAGE");
    File f_secs = new File(secStore);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        StatFs stat = new StatFs(f_secs.getPath());
        long bytesAvailable = stat.getBlockSizeLong() * stat.getBlockCountLong();
        long megAvailable = bytesAvailable / (1024 * 1024);
        return megAvailable;
    } else {
        StatFs stat = new StatFs(f_secs.getPath());
        long bytesAvailable = stat.getBlockSize() * stat.getBlockCount();
        long megAvailable = bytesAvailable / (1024 * 1024);
        return megAvailable;
    }

}
</code>```

Body:
I am trying to get the storage space on Android. Here is the solution I found.

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath())
stat.getTotalBytes()

It returns 774 MB while the setting app shows1 GB. In AVD Manager, size on disk is 1 GB. Is it possible to get the same value like setting app?

Body:
below are methods to check if there is external sd-card  available, total space and free space in internal storage and external sd- card

public boolean isExternalSDCardAvailable() {
    String secStore = System.getenv("SECONDARY_STORAGE");
    if (secStore != null) {
        File f_secs = new File(secStore);
        return f_secs.exists();
    } else return false;
}

public long getAvailableInternalMemorySize() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
        long bytesAvailable = stat.getBlockSizeLong() * stat.getFreeBlocksLong();
        return bytesAvailable / (1024 * 1024);
    } else {
        StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
        long bytesAvailable = (long) stat.getBlockSize() * (long) stat.getFreeBlocks();
        return bytesAvailable / (1024 * 1024);
    }
}

public long getTotalInternalMemorySize() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
        long bytesAvailable = stat.getBlockSizeLong() * stat.getBlockCountLong();
        return bytesAvailable / (1024 * 1024);
    } else {
        StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
        long bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks();
        return bytesAvailable / (1024 * 1024);
    }
}

public long getAvailableExternalMemorySize() {
    String secStore = System.getenv("SECONDARY_STORAGE");
    File f_secs = new File(secStore);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        StatFs stat = new StatFs(f_secs.getPath());
        long bytesAvailable = stat.getBlockSizeLong() * stat.getAvailableBlocksLong();
        return bytesAvailable / (1024 * 1024);
    } else {
        StatFs stat = new StatFs(f_secs.getPath());
        long bytesAvailable = stat.getBlockSize() * stat.getAvailableBlocks();
        return bytesAvailable / (1024 * 1024);
    }

}

public Long getTotalExternalMemorySize() {
    String secStore = System.getenv("SECONDARY_STORAGE");
    File f_secs = new File(secStore);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        StatFs stat = new StatFs(f_secs.getPath());
        long bytesAvailable = stat.getBlockSizeLong() * stat.getBlockCountLong();
        long megAvailable = bytesAvailable / (1024 * 1024);
        return megAvailable;
    } else {
        StatFs stat = new StatFs(f_secs.getPath());
        long bytesAvailable = stat.getBlockSize() * stat.getBlockCount();
        long megAvailable = bytesAvailable / (1024 * 1024);
        return megAvailable;
    }

}


问:
Select values from subquery without duplicates sql
I have table, where type A has two values and type B has two values

```<code>A    |   B
-----|--------
val1 | val1
val2 | val2
</code>```

I do subquery but I get dubolicate values,it looks like this

```<code>A    |   B
-----|--------
val1 | val1
val1 | val2
val2 | val1
val2 | val2
</code>```

My query:

```<code>SELECT A, B
FROM
(SELECT DISTINCT title as A
FROM TABLE1
INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'A' AND TABLE1_AKTIV = 'Y')
LEFT JOIN
(SELECT DISTINCT title as B
FROM TABLE1
INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'B' AND TABLE1_AKTIV = 'Y')
ON 1 = 1
</code>```

Have you any Ideas how I can do it without duplicates?

答: The problem is ON 1=1. This will get you all combinations. you need to change query with proper reference column some thing like ON A.id=B.id.

Body:
I have table, where type A has two values and type B has two values

A    |   B
-----|--------
val1 | val1
val2 | val2

I do subquery but I get dubolicate values,it looks like this

A    |   B
-----|--------
val1 | val1
val1 | val2
val2 | val1
val2 | val2

My query:

SELECT A, B
FROM
(SELECT DISTINCT title as A
FROM TABLE1
INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'A' AND TABLE1_AKTIV = 'Y')
LEFT JOIN
(SELECT DISTINCT title as B
FROM TABLE1
INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'B' AND TABLE1_AKTIV = 'Y')
ON 1 = 1

Have you any Ideas how I can do it without duplicates?


问:
how to POST/Submit an Input Checkbox that is disabled?
I have a checkbox that, given certain conditions, needs to be disabled. Turns out HTTP doesn't post disabled inputs.

How can I get around that? submitting the input even if it's disabled and keeping the input disabled?

答:
UPDATE: READONLY doesn't work on checkboxes

You could use disabled="disabled" but at this point checkbox's value will not appear into POST values. One of the strategy is to add an hidden field holding checkbox's value within the same form and read value back from that field

<s>Simply change disabled to readonly</s>


问:
no module - gunicorn
I am making a helloworld application in Django/python to test gunicorn integration. I have a directory and I have a start.sh file. I want to run a gunicorn server that will host a testing page. I am getting the following error:

```<code>omars-mbp:helloworld omarjandali$ ../start.sh
Starting Gunicorn.
[2017-11-13 22:10:43 -0800] [1238] [INFO] Starting gunicorn 19.6.0
[2017-11-13 22:10:43 -0800] [1238] [INFO] Listening at: http://0.0.0.0:8000 (1238)
[2017-11-13 22:10:43 -0800] [1238] [INFO] Using worker: sync
[2017-11-13 22:10:43 -0800] [1241] [INFO] Booting worker with pid: 1241
[2017-11-13 22:10:43 -0800] [1241] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker
    worker.init_process()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process
    self.load_wsgi()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 65, in load
    return self.load_wsgiapp()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/util.py", line 357, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'helloworld'
[2017-11-13 22:10:43 -0800] [1241] [INFO] Worker exiting (pid: 1241)
[2017-11-13 22:10:43 -0800] [1242] [INFO] Booting worker with pid: 1242
[2017-11-13 22:10:43 -0800] [1242] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker
    worker.init_process()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process
    self.load_wsgi()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 65, in load
    return self.load_wsgiapp()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/util.py", line 357, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'helloworld'
[2017-11-13 22:10:43 -0800] [1242] [INFO] Worker exiting (pid: 1242)
[2017-11-13 22:10:44 -0800] [1238] [INFO] Shutting down: Master
[2017-11-13 22:10:44 -0800] [1238] [INFO] Reason: Worker failed to boot.
</code>```

Here is my start.sh file and an image of my directory:

```<code>echo Starting Gunicorn.
exec gunicorn helloworld.wsgi:application \
  --bind 0.0.0.0:8000 \
  --workers 3
</code>```

I am executing the code from the helloworld folder with the wsgi file:

答:
If you want to start gunicorn from the helloworld folder you need to modify your script like this:

```<code>echo Starting Gunicorn.
exec gunicorn wsgi:application --bind 0.0.0.0:8000 --workers 3
</code>```

Title: no module - gunicorn

Body:
I am making a helloworld application in Django/python to test gunicorn integration. I have a directory and I have a start.sh file. I want to run a gunicorn server that will host a testing page. I am getting the following error:

omars-mbp:helloworld omarjandali$ ../start.sh
Starting Gunicorn.
[2017-11-13 22:10:43 -0800] [1238] [INFO] Starting gunicorn 19.6.0
[2017-11-13 22:10:43 -0800] [1238] [INFO] Listening at: http://0.0.0.0:8000 (1238)
[2017-11-13 22:10:43 -0800] [1238] [INFO] Using worker: sync
[2017-11-13 22:10:43 -0800] [1241] [INFO] Booting worker with pid: 1241
[2017-11-13 22:10:43 -0800] [1241] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker
    worker.init_process()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process
    self.load_wsgi()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 65, in load
    return self.load_wsgiapp()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/util.py", line 357, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'helloworld'
[2017-11-13 22:10:43 -0800] [1241] [INFO] Worker exiting (pid: 1241)
[2017-11-13 22:10:43 -0800] [1242] [INFO] Booting worker with pid: 1242
[2017-11-13 22:10:43 -0800] [1242] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker
    worker.init_process()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process
    self.load_wsgi()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 65, in load
    return self.load_wsgiapp()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/util.py", line 357, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'helloworld'
[2017-11-13 22:10:43 -0800] [1242] [INFO] Worker exiting (pid: 1242)
[2017-11-13 22:10:44 -0800] [1238] [INFO] Shutting down: Master
[2017-11-13 22:10:44 -0800] [1238] [INFO] Reason: Worker failed to boot.

Here is my start.sh file and an image of my directory:

echo Starting Gunicorn.
exec gunicorn helloworld.wsgi:application \
  --bind 0.0.0.0:8000 \
  --workers 3

I am executing the code from the helloworld folder with the wsgi file:

Body:
If you want to start gunicorn from the helloworld folder you need to modify your script like this:

echo Starting Gunicorn.
exec gunicorn wsgi:application --bind 0.0.0.0:8000 --workers 3


问:
Any alternative to BPMN and DMN notations for describing business logic?
I am looking for some tool capable of creating complex process of data manipulation which can be more or less easily modified by people who do not write code.

For example, my task is:

fetch data from sourceA

2.1 if data is full - filter it by condition 45

2.2 if data is not full - fetch additional data from source B

if result passes validation - return 1, otherwise 0

This should be described in some readable manner, best option is if one can modify this process in some UI tool.

What are the requirements?

Each process consists of two parts: steps, and a way to arrange them in a sequence.

(1)
The process in each step should be able to
1. emit commands for fetching some data from data-sources and inserting this into process context
2. filter, enrich, transform datasets obtained
Thus each step of this process should be described with some more or less simple DSL.

(2)
The selection of the step to go, i.e. the consequence of steps should be described by some visual tool, or again, as in (1), with some simple dsl.

Can you advise something for this typical, from my point of view, task?

Meanwhile, here are my own ideas.

First think comes to mind is BPMN combined with Drools.

For steps I may use DRL rules: they can make only basic data manipulation themselves, but I can call Java functions from them if I need something complicated.

For steps consequence I may use standart BPMN diagramm.

Mat be, there is something better?

答:
The combination of BPMN with DMN would allow you indeed to describe with these visual standards, the execution of the process and decision logic to be applied, in order to achieve what in the "For example" paragraph.

In order to make it fully accessible by the business people, the BPMN task for fetching the data or performing any interaction with external system, should be prepared in advance and made available during the composition of the BPMN/DMN diagrams.

Alternatively to BPMN+DMN combination, you can look into Fuse or Fuse Online, it cannot describe all the semantics of the BPMN+DMN combination, but with Fuse Online for instance you can fully visually implement the steps you described in the "For example" paragraph.


问:
Login to docker registry located in Gitlab
I created a docker registry and want to connect it with GitLab. I followed this documentation https://docs.gitlab.com/ce/user/project/container_registry.html. After that I tried to login to docker, but I received 401 or Access denied, do you know how to fix this ?

```<code>docker login url
Username: gitlab-ci-token
Password:
https://<url>/v2/: unauthorized: HTTP Basic: Access denied

docker login <url>
Username: knikolov
Password:
https://<url>/v2/: unauthorized: HTTP Basic: Access denied

docker login <url>
Username: knikolov
Password:
Error response from daemon: login attempt to https://<url>/v2/ failed with status: 401 Unauthorized
</code>```

production.log

```<code>Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:42:51 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:42:54 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:42:57 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:43:00 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:43:03 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:43:06 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:43:09 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:43:12 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:43:15 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:43:18 +0000
Started GET "/jwt/auth?account=knikolov&client_id=docker&offline_token=true&service=container_registry" for 172.17.0.1 at 2017-06-22 14:43:19 +0000
Processing by JwtController#auth as HTML
Parameters: {"account"=>"knikolov", "client_id"=>"docker", "offline_token"=>"true", "service"=>"container_registry"}
Completed 200 OK in 191ms (Views: 0.5ms | ActiveRecord: 5.7ms)
Started GET "/admin/logs" for 172.17.0.1 at 2017-06-22 14:43:21 +0000
Processing by Admin::LogsController#show as HTML
</code>```

Form the registry log I received:

```<code>registry_1  | time="2017-06-25T17:34:31Z" level=warning msg="error authorizing context: authorization token required" go.version=go1.7.3 http.request.host=<url> http.request.id=e088c13e-aa4c-4701-af26-29e12874519b http.request.method=GET http.request.remoteaddr=37.59.24.105 http.request.uri="/v2/" http.request.useragent="docker/17.03.1-ce go/go1.7.5 git-commit/c6d412e kernel/4.4.0-81-generic os/linux arch/amd64 UpstreamClient(Docker-Client/17.03.1-ce \\(linux\\))" instance.id=c8d463e0-cf04-48f5-8daa-d096b4e75494 version=v2.6.1
registry_1  | 172.17.0.1 - - [25/Jun/2017:17:34:31 +0000] "GET /v2/ HTTP/1.0" 401 87 "" "docker/17.03.1-ce go/go1.7.5 git-commit/c6d412e kernel/4.4.0-81-generic os/linux arch/amd64 UpstreamClient(Docker-Client/17.03.1-ce \\(linux\\))"

registry_1  | time="2017-06-25T17:34:32Z" level=info msg="token from untrusted issuer: \"omnibus-gitlab-issuer\""

registry_1  | time="2017-06-25T17:34:32Z" level=warning msg="error authorizing context: invalid token" go.version=go1.7.3 http.request.host=<url> http.request.id=ff0d15e4-3198-4d69-910b-50bc27dd02f2 http.request.method=GET http.request.remoteaddr=37.59.24.105 http.request.uri="/v2/" http.request.useragent="docker/17.03.1-ce go/go1.7.5 git-commit/c6d412e kernel/4.4.0-81-generic os/linux arch/amd64 UpstreamClient(Docker-Client/17.03.1-ce \\(linux\\))" instance.id=c8d463e0-cf04-48f5-8daa-d096b4e75494 version=v2.6.1
registry_1  | 172.17.0.1 - - [25/Jun/2017:17:34:32 +0000] "GET /v2/ HTTP/1.0" 401 87 "" "docker/17.03.1-ce go/go1.7.5 git-commit/c6d412e kernel/4.4.0-81-generic os/linux arch/amd64 UpstreamClient(Docker-Client/17.03.1-ce \\(linux\\))"
</code>```

this is my config for my registry:

```<code>version: 0.1
log:
  fields:
    service: registry
storage:
  cache:
    blobdescriptor: inmemory
  filesystem:
    rootdirectory: /var/lib/registry
  delete:
    enabled: true
http:
  addr: :5000
  headers:
    X-Content-Type-Options: [nosniff]
health:
  storagedriver:
    enabled: true
    interval: 10s
    threshold: 3
auth:
  token:
    realm: https://<url>/jwt/auth
    service: container_registry
    issuer: gitlab-issuer
    rootcertbundle: /certs/registry.crt
</code>```

docker-compose.yml

```<code>registry:
  restart: always
  image: registry:2
  ports:
    - 127.0.0.1:5000:5000
  environment:
    - REGISTRY_STORAGE_DELETE_ENABLED=true
  volumes:
    - ./data:/var/lib/registry
    - ./certs:/certs
    - ./config.yml:/etc/docker/registry/config.yml
</code>```

Gitlab docker-compose.yml

```<code>web:
  image: 'gitlab/gitlab-ce:latest'
  restart: always
  hostname: '<gitlab_url>'
  container_name: gitlab
  environment:
    GITLAB_OMNIBUS_CONFIG: |
      external_url '<gitlab_url>'
      gitlab_rails['gitlab_shell_ssh_port'] = 2224
      registry_external_url '<docker-registry_url>'

      gitlab_rails['smtp_enable'] = true
      gitlab_rails['smtp_address'] = "172.17.0.1"
      gitlab_rails['smtp_domain'] = "<smtp_domain>"
      gitlab_rails['gitlab_email_from'] = '<gitlab_email_from>'
      gitlab_rails['smtp_enable_starttls_auto'] = false

      gitlab_rails['registry_enabled'] = true

      registry_nginx['ssl_certificate'] = '/etc/gitlab/ssl/docker.registry.crt'
      registry_nginx['ssl_certificate_key'] = '/etc/gitlab/ssl/docker.registry.key'

      registry_nginx['proxy_set_headers'] = {
          "Host" => "<dokcer-registry_url>"
      }

      nginx['listen_port'] = 80
      nginx['listen_https'] = false
      nginx['proxy_set_headers'] = {
          "X-Forwarded-Proto" => "https",
          "X-Forwarded-Ssl" => "on"
      }
  ports:
    - '127.0.0.1:5432:80'
    - '2224:22'
  volumes:
    - '/home/gitlab/gitlab-ce/config:/etc/gitlab'
    - '/home/gitlab/gitlab-ce/logs:/var/log/gitlab'
    - '/home/gitlab/gitlab-ce/data:/var/opt/gitlab'
    - '/home/docker-registry/data:/var/opt/gitlab/gitlab-rails/shared/registry'
</code>```

答:
Make sure the .crt file and .key file exists on the path specified here in gitlab.rb if not make the changes and restart gitlab with - sudo gitlab-ctl restart

```<code>external_url 'https://myrepo.xyz.com'
nginx['redirect_http_to_https'] = true
registry_external_url 'https://registry.xyz.com'
registry_nginx['ssl_certificate'] = "/etc/gitlab/ssl/registry.xyz.com.crt"
registry_nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/registry.xyz.com.key"
</code>```

More details available at - Appychip

Body:
I created a docker registry and want to connect it with GitLab. I followed this documentation https://docs.gitlab.com/ce/user/project/container_registry.html. After that I tried to login to docker, but I received 401 or Access denied, do you know how to fix this ?

docker login url
Username: gitlab-ci-token
Password:
https://<url>/v2/: unauthorized: HTTP Basic: Access denied

docker login <url>
Username: knikolov
Password:
https://<url>/v2/: unauthorized: HTTP Basic: Access denied

docker login <url>
Username: knikolov
Password:
Error response from daemon: login attempt to https://<url>/v2/ failed with status: 401 Unauthorized

production.log

Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:42:51 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:42:54 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:42:57 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:43:00 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:43:03 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:43:06 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:43:09 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:43:12 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:43:15 +0000
Started POST "/api/v4/jobs/request" for 172.17.0.1 at 2017-06-22 14:43:18 +0000
Started GET "/jwt/auth?account=knikolov&client_id=docker&offline_token=true&service=container_registry" for 172.17.0.1 at 2017-06-22 14:43:19 +0000
Processing by JwtController#auth as HTML
Parameters: {"account"=>"knikolov", "client_id"=>"docker", "offline_token"=>"true", "service"=>"container_registry"}
Completed 200 OK in 191ms (Views: 0.5ms | ActiveRecord: 5.7ms)
Started GET "/admin/logs" for 172.17.0.1 at 2017-06-22 14:43:21 +0000
Processing by Admin::LogsController#show as HTML

Form the registry log I received:

registry_1  | time="2017-06-25T17:34:31Z" level=warning msg="error authorizing context: authorization token required" go.version=go1.7.3 http.request.host=<url> http.request.id=e088c13e-aa4c-4701-af26-29e12874519b http.request.method=GET http.request.remoteaddr=37.59.24.105 http.request.uri="/v2/" http.request.useragent="docker/17.03.1-ce go/go1.7.5 git-commit/c6d412e kernel/4.4.0-81-generic os/linux arch/amd64 UpstreamClient(Docker-Client/17.03.1-ce \\(linux\\))" instance.id=c8d463e0-cf04-48f5-8daa-d096b4e75494 version=v2.6.1
registry_1  | 172.17.0.1 - - [25/Jun/2017:17:34:31 +0000] "GET /v2/ HTTP/1.0" 401 87 "" "docker/17.03.1-ce go/go1.7.5 git-commit/c6d412e kernel/4.4.0-81-generic os/linux arch/amd64 UpstreamClient(Docker-Client/17.03.1-ce \\(linux\\))"

registry_1  | time="2017-06-25T17:34:32Z" level=info msg="token from untrusted issuer: \"omnibus-gitlab-issuer\""

registry_1  | time="2017-06-25T17:34:32Z" level=warning msg="error authorizing context: invalid token" go.version=go1.7.3 http.request.host=<url> http.request.id=ff0d15e4-3198-4d69-910b-50bc27dd02f2 http.request.method=GET http.request.remoteaddr=37.59.24.105 http.request.uri="/v2/" http.request.useragent="docker/17.03.1-ce go/go1.7.5 git-commit/c6d412e kernel/4.4.0-81-generic os/linux arch/amd64 UpstreamClient(Docker-Client/17.03.1-ce \\(linux\\))" instance.id=c8d463e0-cf04-48f5-8daa-d096b4e75494 version=v2.6.1
registry_1  | 172.17.0.1 - - [25/Jun/2017:17:34:32 +0000] "GET /v2/ HTTP/1.0" 401 87 "" "docker/17.03.1-ce go/go1.7.5 git-commit/c6d412e kernel/4.4.0-81-generic os/linux arch/amd64 UpstreamClient(Docker-Client/17.03.1-ce \\(linux\\))"

this is my config for my registry:

version: 0.1
log:
  fields:
    service: registry
storage:
  cache:
    blobdescriptor: inmemory
  filesystem:
    rootdirectory: /var/lib/registry
  delete:
    enabled: true
http:
  addr: :5000
  headers:
    X-Content-Type-Options: [nosniff]
health:
  storagedriver:
    enabled: true
    interval: 10s
    threshold: 3
auth:
  token:
    realm: https://<url>/jwt/auth
    service: container_registry
    issuer: gitlab-issuer
    rootcertbundle: /certs/registry.crt

docker-compose.yml

registry:
  restart: always
  image: registry:2
  ports:
    - 127.0.0.1:5000:5000
  environment:
    - REGISTRY_STORAGE_DELETE_ENABLED=true
  volumes:
    - ./data:/var/lib/registry
    - ./certs:/certs
    - ./config.yml:/etc/docker/registry/config.yml

Gitlab docker-compose.yml

web:
  image: 'gitlab/gitlab-ce:latest'
  restart: always
  hostname: '<gitlab_url>'
  container_name: gitlab
  environment:
    GITLAB_OMNIBUS_CONFIG: |
      external_url '<gitlab_url>'
      gitlab_rails['gitlab_shell_ssh_port'] = 2224
      registry_external_url '<docker-registry_url>'

      gitlab_rails['smtp_enable'] = true
      gitlab_rails['smtp_address'] = "172.17.0.1"
      gitlab_rails['smtp_domain'] = "<smtp_domain>"
      gitlab_rails['gitlab_email_from'] = '<gitlab_email_from>'
      gitlab_rails['smtp_enable_starttls_auto'] = false

      gitlab_rails['registry_enabled'] = true

      registry_nginx['ssl_certificate'] = '/etc/gitlab/ssl/docker.registry.crt'
      registry_nginx['ssl_certificate_key'] = '/etc/gitlab/ssl/docker.registry.key'

      registry_nginx['proxy_set_headers'] = {
          "Host" => "<dokcer-registry_url>"
      }

      nginx['listen_port'] = 80
      nginx['listen_https'] = false
      nginx['proxy_set_headers'] = {
          "X-Forwarded-Proto" => "https",
          "X-Forwarded-Ssl" => "on"
      }
  ports:
    - '127.0.0.1:5432:80'
    - '2224:22'
  volumes:
    - '/home/gitlab/gitlab-ce/config:/etc/gitlab'
    - '/home/gitlab/gitlab-ce/logs:/var/log/gitlab'
    - '/home/gitlab/gitlab-ce/data:/var/opt/gitlab'
    - '/home/docker-registry/data:/var/opt/gitlab/gitlab-rails/shared/registry'

Body:
Make sure the .crt file and .key file exists on the path specified here in gitlab.rb if not make the changes and restart gitlab with - sudo gitlab-ctl restart

external_url 'https://myrepo.xyz.com'
nginx['redirect_http_to_https'] = true
registry_external_url 'https://registry.xyz.com'
registry_nginx['ssl_certificate'] = "/etc/gitlab/ssl/registry.xyz.com.crt"
registry_nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/registry.xyz.com.key"

More details available at - Appychip