问:
Script only entering last value to postgres database
Very new to python.  I am trying to get the data from an RSS feed, parse the data and then insert the data to a database.  My short bit of code gets the correct items and I can print the results but I can only get the last item in the RSS feed to post to the database. I believe I may have defined "html" and "link" incorrectly.  I want the item.title and item.link to populate a list that will then get entered into the database in the correct order.  Any help much appreciated.</p>

```<code>import sys
import requests
import urllib2
import feedparser
import psycopg2
import psycopg2.extras
from psycopg2.extras import execute_values
import time

url = "https://www.ferc.gov/xml/whats-new.xml"
response = urllib2.urlopen(url).read()

#saving the xml file
response = requests.get(url)
#with open('whats_hot.xml', 'wb') as file:
#    file.write(response.content)

d = feedparser.parse('https://www.ferc.gov/xml/whats-new.xml')

for item in d.entries:
    print "------"
    print item.published
    print item.title
    print item.link
    html = item.published + item.title
    link = item.link

con = psycopg2.connect(database="xx",
user="xx", password="xx", host="127.0.0.1",
port="5432")
print("Database opened successfully")

cur = con.cursor()

#try:
psycopg2.extras.execute_values(cur,
"insert into ferc_hots (link,html) values %s",
      [(link,html)])
#except psycopg2.IntegrityError:
#     print 'Duplicate values found.  Insert was not successful'

con.commit()
print("Records inserted successfully")
con.close()
</code>```

答:
Your insert statement needs to be inside the for loop as well. Otherwise, you only insert the last record.

```<code>con = psycopg2.connect(database="xx",
user="xx", password="xx", host="127.0.0.1",
port="5432")
print("Database opened successfully")

cur = con.cursor()

for item in d.entries:
    print "------"
    print item.published
    print item.title
    print item.link
    html = item.published + item.title
    link = item.link
    psycopg2.extras.execute_values(cur,"insert into ferc_hots (link,html) values %s",[(link,html)])

con.commit()
print("Records inserted successfully")
con.close()
</code>```

Another option is to save a list of records, and insert them together at the end.

Body:
Very new to python.  I am trying to get the data from an RSS feed, parse the data and then insert the data to a database.  My short bit of code gets the correct items and I can print the results but I can only get the last item in the RSS feed to post to the database. I believe I may have defined "html" and "link" incorrectly.  I want the item.title and item.link to populate a list that will then get entered into the database in the correct order.  Any help much appreciated.

import sys
import requests
import urllib2
import feedparser
import psycopg2
import psycopg2.extras
from psycopg2.extras import execute_values
import time

url = "https://www.ferc.gov/xml/whats-new.xml"
response = urllib2.urlopen(url).read()

#saving the xml file
response = requests.get(url)
#with open('whats_hot.xml', 'wb') as file:
#    file.write(response.content)

d = feedparser.parse('https://www.ferc.gov/xml/whats-new.xml')

for item in d.entries:
    print "------"
    print item.published
    print item.title
    print item.link
    html = item.published + item.title
    link = item.link

con = psycopg2.connect(database="xx",
user="xx", password="xx", host="127.0.0.1",
port="5432")
print("Database opened successfully")

cur = con.cursor()

#try:
psycopg2.extras.execute_values(cur,
"insert into ferc_hots (link,html) values %s",
      [(link,html)])
#except psycopg2.IntegrityError:
#     print 'Duplicate values found.  Insert was not successful'

con.commit()
print("Records inserted successfully")
con.close()

Body:
Your insert statement needs to be inside the for loop as well. Otherwise, you only insert the last record.

con = psycopg2.connect(database="xx",
user="xx", password="xx", host="127.0.0.1",
port="5432")
print("Database opened successfully")

cur = con.cursor()

for item in d.entries:
    print "------"
    print item.published
    print item.title
    print item.link
    html = item.published + item.title
    link = item.link
    psycopg2.extras.execute_values(cur,"insert into ferc_hots (link,html) values %s",[(link,html)])

con.commit()
print("Records inserted successfully")
con.close()

Another option is to save a list of records, and insert them together at the end.


来源: stackexchange

问:
problem with rendering ajax POST call to populate DIV
I am tearing my hair out trying to figure out why when I make an ajax POST call to populate a div - it displays just fine when I make the call from within the same SCRIPT block in the HTML document, but as soon as I move the same call out to a separate .js file as a function, nothing renders in the DIV.

I am sure I am just overlooking something but cannot figure out what ???

the following WORKS (ajax call in same script block)

```<code><div id="flow">
</div>

<script  type="text/javascript">
    $(document).ready(function() {

        $.ajax( "http://localhost:8680/jsdv-status-panel/tsv-multi-version",
            {
                data: JSON.stringify(
                    {
                        "some_json":
                                {
                                    "id": 0,
                                    ...
                                }
                    }
                ),
                contentType: 'application/json',
                type: 'POST',
                success:  function(data){
                    $("#flow").html(data);
                }
            });
    });
</script>
</body>
</html>
</code>```

However, if I move the call out to a function in a separate .js file, it displays nothing, even though I can see the Response came back as expected (e.g. Network tab of DevTools looking at the call to the external service I can see the valid HTML or preview)

The following does NOT work (no errors, but nothing displays in the DIV)

```<code><div id="flow">
</div>

<script type="text/javascript" src="assets/js/statusPanelMultiVersion.js"></script>

<script  type="text/javascript">
    $(document).ready(function() {

        statusPanelMultiVersion('#flow',
                    {
                        "some_json":
                                {
                                    "id": 0,
                                    ...
                                }
                    }
         );
    });
</script>
</body>
</html>
</code>```

statusPanelMultiVersion.js

```<code>function statusPanelMultiVersion(_dom_obj, _data_objects) {
     $.ajax( "http://localhost:8680/jsdv-status-panel/tsv-multi-version",
        {
            data: JSON.stringify(_data_objects),
            contentType: 'application/json',
            type: 'POST',
            dataType: 'json',
            success:  function(data){
                $(_dom_obj).html(data);
            }
        });
};
</code>```

Interestingly, I have a similar function in an external file which does an ajax GET - and it works as expected (the results are rendered in the DIV)

```<code>function statusPanelLastValue(_dom_obj, _params) {
    $.ajax( "http://localhost:8680/jsdv-status-panel/tsv-last-value" + _params,
        {
            contentType: 'application/json',
            type: 'GET',
            success:  function(data){
                $(_dom_obj).html(data);
            }
        });
};
</code>```

and called like so

```<code> statusPanelLastValue("#pool", "?biglongquerystring");
</code>```

I am either not seeing something obvious or not understanding a difference between the function() making a POST call and the inline code. Can anyone see what I am doing incorrectly ?

答:
Carlos's question prompted me to see the problem !

I failed to notice the incorrect dataType and ContentType in the request.

This works now

```<code>function statusPanelMultiVersion(_dom_obj, _data_objects) {
    $.ajax( "http://localhost:8680/jsdv-status-panel/tsv-multi-version",
        {
            data: JSON.stringify(_data_objects),
            dataType : "html",
            contentType: "application/json; charset=utf-8",
            type: 'POST',
            beforeSend:function(req) {
                $('#ajax-panel').html('<div class="loading"><img src="/assets/img/loading.gif" alt="Loading..." /></div>')
            },
            success:  function(data){
                $(_dom_obj).html(data);
            }
        });
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am tearing my hair out trying to figure out why when I make an ajax POST call to populate a div - it displays just fine when I make the call from within the same SCRIPT block in the HTML document, but as soon as I move the same call out to a separate .js file as a function, nothing renders in the DIV.

I am sure I am just overlooking something but cannot figure out what ???

the following WORKS (ajax call in same script block)

However, if I move the call out to a function in a separate .js file, it displays nothing, even though I can see the Response came back as expected (e.g. Network tab of DevTools looking at the call to the external service I can see the valid HTML or preview)

The following does NOT work (no errors, but nothing displays in the DIV)

statusPanelMultiVersion.js

function statusPanelMultiVersion(_dom_obj, _data_objects) {
     $.ajax( "http://localhost:8680/jsdv-status-panel/tsv-multi-version",
        {
            data: JSON.stringify(_data_objects),
            contentType: 'application/json',
            type: 'POST',
            dataType: 'json',
            success:  function(data){
                $(_dom_obj).html(data);
            }
        });
};

Interestingly, I have a similar function in an external file which does an ajax GET - and it works as expected (the results are rendered in the DIV)

function statusPanelLastValue(_dom_obj, _params) {
    $.ajax( "http://localhost:8680/jsdv-status-panel/tsv-last-value" + _params,
        {
            contentType: 'application/json',
            type: 'GET',
            success:  function(data){
                $(_dom_obj).html(data);
            }
        });
};

and called like so

 statusPanelLastValue("#pool", "?biglongquerystring");

I am either not seeing something obvious or not understanding a difference between the function() making a POST call and the inline code. Can anyone see what I am doing incorrectly ?

Body:
Carlos's question prompted me to see the problem !

I failed to notice the incorrect dataType and ContentType in the request.

This works now

function statusPanelMultiVersion(_dom_obj, _data_objects) {
    $.ajax( "http://localhost:8680/jsdv-status-panel/tsv-multi-version",
        {
            data: JSON.stringify(_data_objects),
            dataType : "html",
            contentType: "application/json; charset=utf-8",
            type: 'POST',
            beforeSend:function(req) {
                $('#ajax-panel').html('<div class="loading"><img src="/assets/img/loading.gif" alt="Loading..." /></div>')
            },
            success:  function(data){
                $(_dom_obj).html(data);
            }
        });
};


问:
Select everything after a common deliminator in Presto
I have a column where i want to take just the numbers.

However, the data is stored like this:

I want to have just the numbers to be outputted in the same column. Is there a way of doing this?

答:
You can use the regexp_extract function. Assuming your values are always numbers, this should do it:

SELECT regexp_extract(value, '.*:(\d+)', 1)
FROM data
```


问:
Get JSON to HTML JavaScript table
I created a new category as the main table list table. the question is how to insert this JSON data into the JavaScript HTML table with the format below:

```<code>{
  query: {
    count: 10,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  test1: {
    count: 16,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  bold: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  home: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  .....
}
</code>```

Table like this:

```<code>| Name | Count | Time | Language | Diag |
-------------------------------------------------------------
| query | 10 | 2015-12-09T17:12:09Z | en-US | 2 |
| test1 | 16 | 2015-12-09T17:12:09Z | en-US | 2 | .....
</code>```

答:
@Zac. i test but not work.   </p>

```<code>$.ajax({
            url: 'https://www.zpool.ca/api/currencies',
            success: function(data) {
                let htmlStr = "<table><tr><td>Name</td><td>Count</td><td>Time</td><td>Language</td></tr>";
                const keys = Object.keys(data)
                for (var key of keys) {
                    let item = data[key];
                    htmlStr += `<tr><td>${key}</td><td>${item.algo}</td><td>${item.port}</td><td>${item.name}</td></tr>`;
                }
                htmlStr += "</table>";
                document.write(htmlStr);
            }
        });
</code>```

Title: Get JSON to HTML JavaScript table

Body:
I created a new category as the main table list table. the question is how to insert this JSON data into the JavaScript HTML table with the format below:

{
  query: {
    count: 10,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  test1: {
    count: 16,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  bold: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  home: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  .....
}

Table like this:

| Name | Count | Time | Language | Diag |
-------------------------------------------------------------
| query | 10 | 2015-12-09T17:12:09Z | en-US | 2 |
| test1 | 16 | 2015-12-09T17:12:09Z | en-US | 2 | .....

Body:
@Zac. i test but not work.

$.ajax({
            url: 'https://www.zpool.ca/api/currencies',
            success: function(data) {
                let htmlStr = "<table><tr><td>Name</td><td>Count</td><td>Time</td><td>Language</td></tr>";
                const keys = Object.keys(data)
                for (var key of keys) {
                    let item = data[key];
                    htmlStr += `<tr><td>${key}</td><td>${item.algo}</td><td>${item.port}</td><td>${item.name}</td></tr>`;
                }
                htmlStr += "</table>";
                document.write(htmlStr);
            }
        });


问:
Installing cmark PECL module without root
I'm trying to install the cmark PECL module on a shared web host. I do not have sudo privileges.

I was able to get cmark compiled and installed to my home directory. The libcmark.so file is in /home/XXX/progs/lib. The cmark.h file (and other header files) are in /home/XXX/progs/include.

I was able to run phpize. I'm now trying to run ./configure with the following command:

./configure --prefix="/home/XXX/progs" --with-php-config=/usr/local/php73/bin/php-config LDFLAGS="-L/home/XXX/progs/lib/" CPPFLAGS="-I/home/XXX/progs/include/"

I get an error message when I do this.

checking for libcmark... checking for cmark_markdown_to_html in -lcmark... yes
checking for libcmark headers... checking for cmark files in default path... not found
configure: error: Please reinstall the cmark distribution

cmark is compiled properly, and I was able to get the configuration script to find the lib directory just fine, but I can't get the configuration script to find the headers.

What do I need to do?

答: I seem to have figured out a solution. I edited the configuration script. There's a line which says SEARCH_PATH="/usr/local /usr". I changed the line to read SEARCH_PATH="/usr/local /usr /home/XXX/progs". That change allowed it to complie.


问:
How to add new widget in GridLayout without resizing older widgets?
I have added GridLayout to ScrollView, and I'm adding widgets in GridLayout dynamically from python program.Instead of using more space of window it's resizing height of older widgets.What am i doing wrong here?

I tried putting BoxLayout inside GridLayout but it's not working.
I also tried to add widgets directly to ScrollView but i found out ScrollView only supports one widget.

My kv code:

```<code><Downloading>:
    my_grid: mygrid
    GridLayout:
        cols: 1
        size_hint_y : None
        hight: self.minimum_height
        id: mygrid
</code>```

My python code:

```<code>class Downloading(ScrollView):
    set_text = ObjectProperty()
    my_grid = ObjectProperty()

    def __init__(self, select, link, path, username, password):

        self.select = select
        self.link = link
        self.path = path
        self.username = username
        self.password = password
        self.p_bar = []
        self.stat = []

        self.parent_conn, self.child_conn = Pipe()

        p = Process(target=main, args=(self.child_conn, self.select,
                                       self.link, self.path,
                                       self.username, self.password))
        p.start()

        super().__init__()

        self.event = Clock.schedule_interval(self.download_GUI, 0.1)

    def newFile(self, title):
        # self.newId = "stat" + str(len(self.p_bar) + 1)
        self.stat.append(Label(text=''))
        self.p_bar.append(ProgressBar())
        self.my_grid.add_widget(Label(text=title))
        self.my_grid.add_widget(self.stat[-1])
        self.my_grid.add_widget(self.p_bar[-1])

    def download_GUI(self, a):

        temp = self.parent_conn.recv()

        print(temp)

        if temp == "new":
            self.downloading = True
            return
        if self.downloading:
            self.newFile(temp)
            self.downloading = False
            return
        if type(temp) == type({}):
            self.complete = temp['complete']
            if not self.complete:
                status = "{0}//{1} @ {2}  ETA: {3}".format(temp['dl_size'],
                                                      temp['total_size'],temp['speed'],temp['eta'])
                self.stat[-1].text = status
                self.p_bar[-1].value = temp['progress']
                return

        if temp == "end":
            self.event.cancel()
            Clock.schedule_once(exit, 3)
</code>```

答:
I believe you just need to set the height for each widget that you add to your GridLayout. For example:

```<code>    self.my_grid.add_widget(Label(text=title, size_hint=(1, None), height=50))
</code>```

You might need to do the same for the other widgets you are adding. The GridLayout may give the initially added widgets more space than that, but will not squeeze them any any tighter than your specified height.

Body:
I have added GridLayout to ScrollView, and I'm adding widgets in GridLayout dynamically from python program.Instead of using more space of window it's resizing height of older widgets.What am i doing wrong here?

I tried putting BoxLayout inside GridLayout but it's not working.
I also tried to add widgets directly to ScrollView but i found out ScrollView only supports one widget.

My kv code:

<Downloading>:
    my_grid: mygrid
    GridLayout:
        cols: 1
        size_hint_y : None
        hight: self.minimum_height
        id: mygrid

My python code:

class Downloading(ScrollView):
    set_text = ObjectProperty()
    my_grid = ObjectProperty()

    def __init__(self, select, link, path, username, password):

        self.select = select
        self.link = link
        self.path = path
        self.username = username
        self.password = password
        self.p_bar = []
        self.stat = []

        self.parent_conn, self.child_conn = Pipe()

        p = Process(target=main, args=(self.child_conn, self.select,
                                       self.link, self.path,
                                       self.username, self.password))
        p.start()

        super().__init__()

        self.event = Clock.schedule_interval(self.download_GUI, 0.1)

    def newFile(self, title):
        # self.newId = "stat" + str(len(self.p_bar) + 1)
        self.stat.append(Label(text=''))
        self.p_bar.append(ProgressBar())
        self.my_grid.add_widget(Label(text=title))
        self.my_grid.add_widget(self.stat[-1])
        self.my_grid.add_widget(self.p_bar[-1])

    def download_GUI(self, a):

        temp = self.parent_conn.recv()

        print(temp)

        if temp == "new":
            self.downloading = True
            return
        if self.downloading:
            self.newFile(temp)
            self.downloading = False
            return
        if type(temp) == type({}):
            self.complete = temp['complete']
            if not self.complete:
                status = "{0}//{1} @ {2}  ETA: {3}".format(temp['dl_size'],
                                                      temp['total_size'],temp['speed'],temp['eta'])
                self.stat[-1].text = status
                self.p_bar[-1].value = temp['progress']
                return

        if temp == "end":
            self.event.cancel()
            Clock.schedule_once(exit, 3)

Body:
I believe you just need to set the height for each widget that you add to your GridLayout. For example:

    self.my_grid.add_widget(Label(text=title, size_hint=(1, None), height=50))

You might need to do the same for the other widgets you are adding. The GridLayout may give the initially added widgets more space than that, but will not squeeze them any any tighter than your specified height.


问:
Change admob ids on existing apps
I'm studying ad networks for android apps and there's a question that's eating me up.

Admob has two ids. App id and interstitial id.

After the update "17.0.0" that adds the AndroidManifest declaration of the app id is still possible to change admob account on an existing app via json?

Example..
My admob account gets banned and I want to put a new id that's linked on the new account to keep earning money from the app...
Is possible to do that?

Basically the question is... Does the app id change on the new account or is it unique for every app?
Because if it does than I cannot change the id in the manifest and swap accounts.

答:
is still possible to change admob account on an existing app via json?

No , i don't think so , because to you have to change your google-services.json in your project , and for that you have to download it and copy it into the app/ folder of your Android Studio project

My admob account gets banned and I want to put a new id that's linked on the new account to keep earning money from the app... Is possible to do that??

No, sorry. If you got banned there is no point in creating new Admob account because you will get banned again. even if you create a new email address ,the moment you leave a small trace to your old account, Google will ban your new account as well.

The small trace can be anything like your phone number, testing devices, developer account, commonly accessed E-mail addresses in the machines and what not you do in internet which could help Google trace back to you. It is very hard to get away with Google AdMob ban by simply creating an another account.

Luckily you can still use alternative ad networks like Unity Ads, App Lovin .....etc but this time try without cheating because consequences can be the same.

Good Luck!

Does the app id change on the new account  ?

yes sir ! An app ID is generated based on application and account !

An app ID is a unique ID number assigned to your apps when they're added to AdMob. The app ID is used to identify your apps. An ad unit ID is a unique ID number assigned to each of your ad units when they're created in AdMob.

Title: Change admob ids on existing apps


问:
MySQL - Why is this slow running query not using (what seems to be) the correct index?
This query works, and does what I want it to do, but is awfully slow running.  We have a table of transactions that holds an amount, a user ID, a partner ID, and a description. When a user has 3 of a specific transaction they get a one-time bonus.

```<code>SELECT t.str_spid, count(*) AS C
  FROM transactions t
  LEFT JOIN transactions AS x
    ON t.str_spid = x.str_spid
   AND x.str_prid = 148
   AND x.str_amount = 2500
 WHERE t.str_prid = 148
   AND (t.str_desc = "Annual Rewards" OR t.str_desc = "Annual Rewards (PRO)")
   AND t.str_amount = 2000
   AND x.str_spid IS NULL
 GROUP BY t.STR_SPID
HAVING C = 3
 LIMIT 0,100;
</code>```

I have an indexes on the individual fields, and then composite indexes as follows:

```<code>SPID_DE_PRID: STR_SPID, STR_DESC, STR_PRID
SPID_DE_PRID_AMT: STR_SPID, STR_AMOUNT, STR_DESC, STR_PRID
</code>```

When I use explain I get possible keys (on t):

```<code>STR_SPID,STR_PRID,STRAMT,STRDESC,SPID_PRID,SPID_DE_PRID,SPID_DE_PRID_AMT
</code>```

And key used:  STR_PRID

On x I get possible:

```<code>STR_SPID,SPT_SOID,STRAMT,SPID_PRID,SPID_DE_PRID,SPID_DE_PRID_AMT
</code>```

And key used: STR_SPID

Is there a better index or way to rewrite this so that it runs any faster?

答:
You search t for specific values in str_prid and str_desc, so those should be the first two columns of an index, but you don't have such an index.

The optimizer does its best with the single-column index on str_prid, to narrow down the search.

If you had an index on (str_prid, str_amount, str_desc, str_spid) that's what I would expect would have the best optimization for t.

Then for x, you'd want to look up matching rows, so you'd want and index on (str_spid, str_prid, str_amount).

Body:
This query works, and does what I want it to do, but is awfully slow running.  We have a table of transactions that holds an amount, a user ID, a partner ID, and a description. When a user has 3 of a specific transaction they get a one-time bonus.

SELECT t.str_spid, count(*) AS C
  FROM transactions t
  LEFT JOIN transactions AS x
    ON t.str_spid = x.str_spid
   AND x.str_prid = 148
   AND x.str_amount = 2500
 WHERE t.str_prid = 148
   AND (t.str_desc = "Annual Rewards" OR t.str_desc = "Annual Rewards (PRO)")
   AND t.str_amount = 2000
   AND x.str_spid IS NULL
 GROUP BY t.STR_SPID
HAVING C = 3
 LIMIT 0,100;

I have an indexes on the individual fields, and then composite indexes as follows:

SPID_DE_PRID: STR_SPID, STR_DESC, STR_PRID
SPID_DE_PRID_AMT: STR_SPID, STR_AMOUNT, STR_DESC, STR_PRID

When I use explain I get possible keys (on t):

STR_SPID,STR_PRID,STRAMT,STRDESC,SPID_PRID,SPID_DE_PRID,SPID_DE_PRID_AMT

And key used:  STR_PRID

On x I get possible:

STR_SPID,SPT_SOID,STRAMT,SPID_PRID,SPID_DE_PRID,SPID_DE_PRID_AMT

And key used: STR_SPID

Is there a better index or way to rewrite this so that it runs any faster?


问:
Any good tutorials/examples for the Spring3 Security Framework?
Can someone please help me out, I am just getting into Spring3, Spring3 MVC Validation and Hibernate

Can someone please tell me of  any good tutorials/examples for the Spring3 Security Framework?

I would love to find a example that looks up the user information from a database.  please help me out!  thanks.  SPRING3

答:
Hope these links would be usefull for you:

http://krams915.blogspot.com/2010/12/spring-security-mvc-integration.html

http://krams915.blogspot.com/2010/12/spring-security-mvc-integration_18.html

http://www.javabeat.net/articles/176-spring-security-30-1.html

And of course official reference: http://static.springsource.org/spring-security/site/docs/3.0.x/reference/springsecurity-single.html

Also some links can be found here: http://static.springsource.org/spring-security/site/articles.html

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Bulk Text Editing
How can I add certain character to the END of each row? With same spacing in between old and new column values across rows!

I tried shift+Alt to select multiple rows and using search --> Regular Expression --> $ Command I can bring cursor to end of each line irrespective of Size of each word.

But How to merge new column values near existing Column values with unique alignment across rows.

Is it possible in Notepad ++

```<code>Column 1 :

action
usersessionid*
token
accountid
clientip

Column 2 :

Dinesh
Kishore
Yuva
Vignesh
Ganesh
</code>```

Expected---------------

```<code>Merged Column :
action Dinesh
usersessionid* Kishore
token Yuva
accountid Vignesh
clientip Ganesh
</code>```

答:
In case you want to skip the manual shift+Alt selection, you may want to try with regular expressions and macros. Remember that macros can be saved for later reuse.

Record the following macro:

Press Record macro

Control + H

Search: ^(?!Column \d)(\S+)(?=\h*$)([\s\S]*^Column \d[\s\S]*?)^([^\r\n]+)

Replace by: \1 \3\2

Replace All

Find Next

Replace All

Stop recording macro

Now you can play the macro with: Run macro multiple times button and then select: Run until the end of file

NOTES:

I'm assuming that first column data does not have spaces in between (like for example in Customer Id).

I also assume that Column 1 : and Column 2 : literals exist

Title: Bulk Text Editing

Body:
How can I add certain character to the END of each row? With same spacing in between old and new column values across rows!

I tried shift+Alt to select multiple rows and using search --> Regular Expression --> $ Command I can bring cursor to end of each line irrespective of Size of each word.

But How to merge new column values near existing Column values with unique alignment across rows.

Is it possible in Notepad ++

Column 1 :

action
usersessionid*
token
accountid
clientip

Column 2 :

Dinesh
Kishore
Yuva
Vignesh
Ganesh

Expected---------------

Merged Column :
action Dinesh
usersessionid* Kishore
token Yuva
accountid Vignesh
clientip Ganesh


问:
While loop doesn't exit or display results
Homework assignment: I've been asked to create a method that will count all the odd numbers from 1 to value assigned to variable but it has to be with a while loop.

I've been using modulus to try and determine whether or not it's even or odd. I've tried identifying odd numbers and then just using + 2. I suspect it's a simple logic error I don't quite see.

```<code>public static void sumOddNumber(int number){

    int counter =1;

    while (counter <= number){
        if (counter % 2 !=0){
            System.out.println (+ number);
            counter++;
        }
    }

}
</code>```

My expectation was for it to compare counter to number(the user defined variable) and to keep performing the modulus operation and printing the result, until counter exceeds number. However when I enter a number it just prints that number and keeps grinding away.

答:
Agreed with @forpas, your counter++ is only called once.

Try this...

```<code>public static void printOddNumber(int number){

    int counter = 1;

    while (counter <= number) {

        if (counter % 2 !=0) {

            System.out.println(counter);
        }
        counter++;
    }
}
</code>```

A somewhat better answer from a readability standpoint...

```<code>public static void printOddNumber(int number){

    int counter = 1;

    while (counter <= number) {

        if (isOddNumber(counter)) {

            System.out.println(counter);
        }
        counter++;
    }
}

public static boolean isOddNumber(int number) {

    return number % 2 != 0;
}
</code>```

Body:
Homework assignment: I've been asked to create a method that will count all the odd numbers from 1 to value assigned to variable but it has to be with a while loop.

I've been using modulus to try and determine whether or not it's even or odd. I've tried identifying odd numbers and then just using + 2. I suspect it's a simple logic error I don't quite see.

public static void sumOddNumber(int number){

    int counter =1;

    while (counter <= number){
        if (counter % 2 !=0){
            System.out.println (+ number);
            counter++;
        }
    }

}

My expectation was for it to compare counter to number(the user defined variable) and to keep performing the modulus operation and printing the result, until counter exceeds number. However when I enter a number it just prints that number and keeps grinding away.

Body:
Agreed with @forpas, your counter++ is only called once.

Try this...

public static void printOddNumber(int number){

    int counter = 1;

    while (counter <= number) {

        if (counter % 2 !=0) {

            System.out.println(counter);
        }
        counter++;
    }
}

A somewhat better answer from a readability standpoint...

public static void printOddNumber(int number){

    int counter = 1;

    while (counter <= number) {

        if (isOddNumber(counter)) {

            System.out.println(counter);
        }
        counter++;
    }
}

public static boolean isOddNumber(int number) {

    return number % 2 != 0;
}


问:
Creating a menu in iOS
I'm currently creating an update of my iOS application and I'm a bit stuck. I've tried to googling around but cannot find a decent answer on this.

I've a menu which links to different views. And I'm not really sure if I've done it the best method.

I've created a view, and added the links into a stack view. Should I considering changing it all to a tableview? or a collection view? Or maybe there's another way?

The current look:

Should I change this to a tableview? collection view? or something else? Or just let it stay as it is?

答:
Look, the fact of have many itens on your screen is clear on the mobile applications, to make it easy, we have collecions view like UITableView and UICollectionView. On the UITableView's case, this implements the scrolling and have methods do handle the operations' list, you can see the documentation to check these methods: https://developer.apple.com/documentation/uikit/uitableview.

Main reasons to use UITableView

Implements scroll behavior.

Independent of size screen you can access all itens.

Easy to detect interactions like tap on cell.

Easy to make changes, like insert and remove content.

The UITableView exists precisely to solve problems like you has.

Title: Creating a menu in iOS


问:
How to refactor function parameters and its usages
So i have method

```<code>function titleAndDetail(title, detail, lineHeight, lineLength, x, y,
tFontSize, dFontSize, document, replacer){
}
</code>```

I used it many, many times. And i figured out way that i dont need some of these params.

My goal is function like this:

```<code>function titleAndDetail(title, detail, lineLength, x, y,
document){
}
</code>```

My question is: Is it any way to refactor method and automatic delete these params where method is called to avoid do it by hand for hundreds times?

Im using visual studio code.

答:
There are two ways to go about this.

Either you can make it so that it accepts many parameters and ignores them if some are null. So you make the function that has all possible parameters, and then use it, and just set some to null. This can be seen in TypeScript's "optional" parameter.

A better way, which has been suggested, is to pass in a lambda JS object.
This can be done like this:

```<code>// Define it like this
function titleAndDetail(title, detail, lineLength, x, y,
document) {
  // But instead you can check if title is actually something that defines all of these. Like this:
if(title.title != undefined) {
  passTitle(title.title);
} else {
  passTitle(title);
}

if(title.detail != undefined) {
  passDetail(title.detail);
} else {
  passDetail(detail);
}

}

// How you would use this and it wouldn't hinder the other uses of your function.
titleAndDetail({title: "title", detail:"detail", lineLength:"length", x: 43, y: 432,
document: "document"});
</code>```

Remember, you can pass in anything as the value for all of these.

Hope I helped..

Body:
So i have method

function titleAndDetail(title, detail, lineHeight, lineLength, x, y,
tFontSize, dFontSize, document, replacer){
}

I used it many, many times. And i figured out way that i dont need some of these params.

My goal is function like this:

function titleAndDetail(title, detail, lineLength, x, y,
document){
}

My question is: Is it any way to refactor method and automatic delete these params where method is called to avoid do it by hand for hundreds times?

Im using visual studio code.

Body:
There are two ways to go about this.

Either you can make it so that it accepts many parameters and ignores them if some are null. So you make the function that has all possible parameters, and then use it, and just set some to null. This can be seen in TypeScript's "optional" parameter.

A better way, which has been suggested, is to pass in a lambda JS object.
This can be done like this:

// Define it like this
function titleAndDetail(title, detail, lineLength, x, y,
document) {
  // But instead you can check if title is actually something that defines all of these. Like this:
if(title.title != undefined) {
  passTitle(title.title);
} else {
  passTitle(title);
}

if(title.detail != undefined) {
  passDetail(title.detail);
} else {
  passDetail(detail);
}

}

// How you would use this and it wouldn't hinder the other uses of your function.
titleAndDetail({title: "title", detail:"detail", lineLength:"length", x: 43, y: 432,
document: "document"});

Remember, you can pass in anything as the value for all of these.

Hope I helped..


问:
Animation when user go into site, but not when he travels
I have a website, where i wanna use some simple animations when the page is loaded. The animation code is not a problem. This animation is some fading in of menu and other elements. I will call this an intro of my page. I want the end-user to see this animation ONLY when he visit a site, and dont see when he clicks some links in menu and travel around my website. I worked it out for now by putting the animation code only on fron page, but for example: what if someone gives a link to mywebsite.com/news to someone. He will go into site and he will not see the animation cause its only on the front page. Any solutions? I think about some session & cookies "if" statements with php maybe, but I'm a begginer and I dont know how to work it out.</p>

答:
You are asking your system (as a whole) to remember information between HTTP requests (page fetches). HTTP is by design a stateless system, so you will have to use one of the mechanisms which have been developed for remembering information: cookies or (server-side) sessions. (Actually, sessions are usually implemented using cookies, but you can think of them as separate technologies). </p>

<p>Sessions in PHP are quite easy to use: you'll just fire the animation when you create a new session. But you will have to work out how you are going to decide when a session is continuing, and when it has expired and you need a new one. </p>

Body:
You are asking your system (as a whole) to remember information between HTTP requests (page fetches). HTTP is by design a stateless system, so you will have to use one of the mechanisms which have been developed for remembering information: cookies or (server-side) sessions. (Actually, sessions are usually implemented using cookies, but you can think of them as separate technologies).

Sessions in PHP are quite easy to use: you'll just fire the animation when you create a new session. But you will have to work out how you are going to decide when a session is continuing, and when it has expired and you need a new one.


答:
The argument list to execute_values needs to be a "sequence of sequences". Which is a list of lists (or list of tuples). In your case, you're only leaving the final item values in html and link and so only providing a single item .

You'll want something like this:

```<code>args = []
for item in d.entries:
    print "------"
    print item.published
    print item.title
    print item.link
    args.append([item.published + item.title, item.link])
</code>```

Or, in one fell swoop:

```<code>args = [[item.published + item.title, item.link] for item in d.entries]
</code>```

Then the insert is something like:

```<code>psycopg2.extras.execute_values(cur,
          "insert into ferc_hots (link,html) values %s",
          args)
</code>```

Title: Script only entering last value to postgres database

Body:
The argument list to execute_values needs to be a "sequence of sequences". Which is a list of lists (or list of tuples). In your case, you're only leaving the final item values in html and link and so only providing a single item .

You'll want something like this:

args = []
for item in d.entries:
    print "------"
    print item.published
    print item.title
    print item.link
    args.append([item.published + item.title, item.link])

Or, in one fell swoop:

args = [[item.published + item.title, item.link] for item in d.entries]

Then the insert is something like:

psycopg2.extras.execute_values(cur,
          "insert into ferc_hots (link,html) values %s",
          args)


问:
How to expand from a child to its very first parent?
I'm trying to expand all children starting on root(parent of a parent....) until the actual node. How can I do it without clicking on every node?

I'm using it to show directories content and I would like to show the last path the user was before closing/opening the app.

The first picture shows how I would like it to be and the second picture shows what is shown at the moment.

The code is not done. There is a lot of testing and debugging.

I added all relevant code to this questions.

So far my app reads directories and if there is any mp3 file on this directory it is shown on a table view, but it is not part of my question, just a background.

```<code>extension ViewController: NSOutlineViewDataSource {
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
    let directoryItem = item as? DirectoryItem ?? rootItem
    return directoryItem.childItems.count
}

func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
    let directoryItem = item as? DirectoryItem ?? rootItem
    return directoryItem.childItems[index]
}

func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
    let directoryItem = item as? DirectoryItem ?? rootItem
    return directoryItem.isExpandable
}
}

extension ViewController: NSOutlineViewDelegate {
func outlineViewSelectionDidChange(_ notification: Notification) {
    singleClick()
}

func outlineView(_ outlineView: NSOutlineView, shouldExpandItem item: Any) -> Bool {
    let directoryItem = item as? DirectoryItem ?? rootItem
    return (directoryItem.childItems.count != 0)
}

func outlineView(_ outlineView: NSOutlineView, shouldShowOutlineCellForItem item: Any) -> Bool {
    let directoryItem = item as? DirectoryItem ?? rootItem
    return (directoryItem.childItems.count != 0)
}

func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
    var text = ""
    if let directories = item as? DirectoryItem {
        if(directories.isdir) {
            text = directories.name
            let tableCell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "cell"), owner: self) as! NSTableCellView
            tableCell.textField!.stringValue = text
            return tableCell
        }
    }
        return nil
}
}

@objc func singleClick()
{
    if let item = self.outlineView.item(atRow: self.outlineView.selectedRow)  {
        self.arrMp3File.removeAll()
        do {
            let xx = (item as! DirectoryItem).url
            let b = self.getSubDir(path: xx.path)
            self.saveDefaults(url: xx)
            DispatchQueue.global(qos: .background).async { [weak self] in
                DispatchQueue.main.async {
                    self?.progressIndicator.isHidden = false
                    self?.progressIndicator.startAnimation(self)
                }
                for bb in b {
                    self?.getTagsFromFile(file: xx.path+"/"+bb)
                }
                DispatchQueue.main.async {
                    self?.arrMp3File.sort(by: {
                        $0.file < $1.file
                    })
                    self?.tableView.reloadData()
                    self?.loadTagsFromButton.isEnabled = true
                    self?.progressIndicator.stopAnimation(self)
                    self?.progressIndicator.isHidden = true
                }
            }
        }
    }

}

override func viewDidLoad() {
    super.viewDidLoad()
     let defaults = UserDefaults.standard

    let lastDirectory = defaults.url(forKey: "LastDirectory")
    print(lastDirectory ?? "")
   // rootItem = DirectoryItem(url: lastDirectory ?? FileManager.default.homeDirectoryForCurrentUser)
   // getDir(path: age)
    outlineView.dataSource = self
    outlineView.delegate = self

    tableView.delegate = self
    tableView.dataSource = self

    tableView.doubleAction = #selector(doubleClickOnResultRow)
  //  outlineView.action = #selector(singleClick)

  self.progressIndicator.isHidden = true
    self.tableView.reloadData()

}

class Directories {
var name: String
var subDirectories: [String]

init(name: String, subDirectories: [String]) {
    self.name = name
    self.subDirectories = subDirectories
}
}

class DirectoryItem {

var name: String
var url: URL
var isdir: Bool
var prev: URL

lazy var isExpandable: Bool = {
    do {
        return try url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory ?? false
    } catch let error as NSError {
        return false
    }
}()

lazy var childItems: [DirectoryItem] = {
    do {
        let urls = try FileManager.default.contentsOfDirectory(at: url,
                                                               includingPropertiesForKeys: [.isDirectoryKey],
                                                               options: [.skipsHiddenFiles])

        var aa: [DirectoryItem]
        var bb: [DirectoryItem]
        bb = []
        aa = urls.map { DirectoryItem(url: $0) }
        for a in aa {
            if(a.isdir) {
                bb.append(a)
                // print(a)
            }

        }
        return bb
        //return urls.map { DirectoryItem(url: $0) }
    } catch let error as NSError {
        return []
    }
}()

init(url: URL) {
    self.url = url
    self.name = url.lastPathComponent
    self.isdir = url.hasDirectoryPath
    self.prev = url.deletingLastPathComponent()

}

}
</code>```

答:
If you have saved the URL that the user was last visiting, then you can show and select it in three steps:

Convert the URL to an array of DirectoryItem representing the path components of the URL.

Ask the outline view to expand each of those items, starting with the item that is a direct child of the root node.

Ask the outline view to select the last item.

Untested code:

```<code>func reveal(_ url: URL) {
    // Step 1.
    let items = itemHierarchy(for: url)

    // Step 2.
    for item in items {
        outlineView.expandItem(item)
    }

    // Step 3.
    if
        let last = items.last,
        case let row = outlineView.row(forItem: last),
        row != -1
    {
        let set = IndexSet(integer: row)
        outlineView.selectRowIndexes(set, byExtendingSelection: false)
    }
}

private func itemHierarchy(for url: URL) -> [DirectoryItem] {
    var items: [DirectoryItem] = []
    var current: DirectoryItem = rootItem
    for component in url.pathComponents {
        guard let child = current.childItems.first(where: { $0.name == component }) else {
            return items
        }
        items.append(child)
        current = child
    }
    return items
}
</code>```

Body:
I'm trying to expand all children starting on root(parent of a parent....) until the actual node. How can I do it without clicking on every node?

I'm using it to show directories content and I would like to show the last path the user was before closing/opening the app.

The first picture shows how I would like it to be and the second picture shows what is shown at the moment.

The code is not done. There is a lot of testing and debugging.

I added all relevant code to this questions.

So far my app reads directories and if there is any mp3 file on this directory it is shown on a table view, but it is not part of my question, just a background.

extension ViewController: NSOutlineViewDataSource {
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
    let directoryItem = item as? DirectoryItem ?? rootItem
    return directoryItem.childItems.count
}

func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
    let directoryItem = item as? DirectoryItem ?? rootItem
    return directoryItem.childItems[index]
}

func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
    let directoryItem = item as? DirectoryItem ?? rootItem
    return directoryItem.isExpandable
}
}

extension ViewController: NSOutlineViewDelegate {
func outlineViewSelectionDidChange(_ notification: Notification) {
    singleClick()
}

func outlineView(_ outlineView: NSOutlineView, shouldExpandItem item: Any) -> Bool {
    let directoryItem = item as? DirectoryItem ?? rootItem
    return (directoryItem.childItems.count != 0)
}

func outlineView(_ outlineView: NSOutlineView, shouldShowOutlineCellForItem item: Any) -> Bool {
    let directoryItem = item as? DirectoryItem ?? rootItem
    return (directoryItem.childItems.count != 0)
}

func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
    var text = ""
    if let directories = item as? DirectoryItem {
        if(directories.isdir) {
            text = directories.name
            let tableCell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "cell"), owner: self) as! NSTableCellView
            tableCell.textField!.stringValue = text
            return tableCell
        }
    }
        return nil
}
}

@objc func singleClick()
{
    if let item = self.outlineView.item(atRow: self.outlineView.selectedRow)  {
        self.arrMp3File.removeAll()
        do {
            let xx = (item as! DirectoryItem).url
            let b = self.getSubDir(path: xx.path)
            self.saveDefaults(url: xx)
            DispatchQueue.global(qos: .background).async { [weak self] in
                DispatchQueue.main.async {
                    self?.progressIndicator.isHidden = false
                    self?.progressIndicator.startAnimation(self)
                }
                for bb in b {
                    self?.getTagsFromFile(file: xx.path+"/"+bb)
                }
                DispatchQueue.main.async {
                    self?.arrMp3File.sort(by: {
                        $0.file < $1.file
                    })
                    self?.tableView.reloadData()
                    self?.loadTagsFromButton.isEnabled = true
                    self?.progressIndicator.stopAnimation(self)
                    self?.progressIndicator.isHidden = true
                }
            }
        }
    }

}

override func viewDidLoad() {
    super.viewDidLoad()
     let defaults = UserDefaults.standard

    let lastDirectory = defaults.url(forKey: "LastDirectory")
    print(lastDirectory ?? "")
   // rootItem = DirectoryItem(url: lastDirectory ?? FileManager.default.homeDirectoryForCurrentUser)
   // getDir(path: age)
    outlineView.dataSource = self
    outlineView.delegate = self

    tableView.delegate = self
    tableView.dataSource = self

    tableView.doubleAction = #selector(doubleClickOnResultRow)
  //  outlineView.action = #selector(singleClick)

  self.progressIndicator.isHidden = true
    self.tableView.reloadData()

}

class Directories {
var name: String
var subDirectories: [String]

init(name: String, subDirectories: [String]) {
    self.name = name
    self.subDirectories = subDirectories
}
}

class DirectoryItem {

var name: String
var url: URL
var isdir: Bool
var prev: URL

lazy var isExpandable: Bool = {
    do {
        return try url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory ?? false
    } catch let error as NSError {
        return false
    }
}()

lazy var childItems: [DirectoryItem] = {
    do {
        let urls = try FileManager.default.contentsOfDirectory(at: url,
                                                               includingPropertiesForKeys: [.isDirectoryKey],
                                                               options: [.skipsHiddenFiles])

        var aa: [DirectoryItem]
        var bb: [DirectoryItem]
        bb = []
        aa = urls.map { DirectoryItem(url: $0) }
        for a in aa {
            if(a.isdir) {
                bb.append(a)
                // print(a)
            }

        }
        return bb
        //return urls.map { DirectoryItem(url: $0) }
    } catch let error as NSError {
        return []
    }
}()

init(url: URL) {
    self.url = url
    self.name = url.lastPathComponent
    self.isdir = url.hasDirectoryPath
    self.prev = url.deletingLastPathComponent()

}

}

Body:
If you have saved the URL that the user was last visiting, then you can show and select it in three steps:

Convert the URL to an array of DirectoryItem representing the path components of the URL.

Ask the outline view to expand each of those items, starting with the item that is a direct child of the root node.

Ask the outline view to select the last item.

Untested code:

func reveal(_ url: URL) {
    // Step 1.
    let items = itemHierarchy(for: url)

    // Step 2.
    for item in items {
        outlineView.expandItem(item)
    }

    // Step 3.
    if
        let last = items.last,
        case let row = outlineView.row(forItem: last),
        row != -1
    {
        let set = IndexSet(integer: row)
        outlineView.selectRowIndexes(set, byExtendingSelection: false)
    }
}

private func itemHierarchy(for url: URL) -> [DirectoryItem] {
    var items: [DirectoryItem] = []
    var current: DirectoryItem = rootItem
    for component in url.pathComponents {
        guard let child = current.childItems.first(where: { $0.name == component }) else {
            return items
        }
        items.append(child)
        current = child
    }
    return items
}


问:
Columns not working in both Bootstrap 3 and 4
I'm trying to set up a new internal web page using bootstrap (both versions 3.3.6 and 4.0.0-alpha.6) columns, but for some reason they don't show up in Internet Explorer 11 (company-mandated). Instead of columns, the text is stacked vertically (see examples).

I have tried everything from complex code to the simple code I have attached to this question. Nothing has worked. I have also looked at every single web page I could find on this, and likewise nothing has worked. I have also tried using xs, sm, md, lg and xl column sizes, and they don't make any difference.

```<code><!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />
<script src="js/bootstrap.min.js"></script>
<title>Test 4</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
  <div class="col-lg-4">lg-4</div>
  <div class="col-lg-4">lg-4</div>
</div>
<div class="row">
  <div class="col-lg-3">lg-3</div>
  <div class="col-lg-3">lg-3</div>
  <div class="col-lg-3">lg-3</div>
</div>
<div class="container">
<div class="row">
  <div class="col-3">variable</div>
  <div class="col-3">variable</div>
  <div class="col-3">variable</div>
</div>
</div>
</code>```

The above code results in:

lg-4

lg-4

lg-3

lg-3

lg-3

variable

variable

variable

Instead of:

lg-4     lg-4     lg-3     lg-3     lg-3

variable     variable     variable

答:
Bootstrap Grid System allows 12 columns across a page.
In order to avoid using all the 12 columns individually we can split the columns into sub columns as per our requirements.
However we need to ensure that the sub columns always sums up to 12 and never exceed 12 or else the content switches on to the next line.
So perform appropriate changes in your code as per the above concept and apart from  that to support the grid system in IE 11 consider including the following tag:

```<code><meta http-equiv="X-UA-Compatible" content="IE=edge">
</code>```

In order to have further knowledge about grid system visit the following link :
https://www.w3schools.com/bootstrap/bootstrap_grid_system.asp

Body:
I'm trying to set up a new internal web page using bootstrap (both versions 3.3.6 and 4.0.0-alpha.6) columns, but for some reason they don't show up in Internet Explorer 11 (company-mandated). Instead of columns, the text is stacked vertically (see examples).

I have tried everything from complex code to the simple code I have attached to this question. Nothing has worked. I have also looked at every single web page I could find on this, and likewise nothing has worked. I have also tried using xs, sm, md, lg and xl column sizes, and they don't make any difference.

<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />

<title>Test 4</title>

lg-4

lg-4

lg-3

lg-3

lg-3

variable

variable

variable

The above code results in:

lg-4

lg-4

lg-3

lg-3

lg-3

variable

variable

variable

Instead of:

lg-4     lg-4     lg-3     lg-3     lg-3

variable     variable     variable

Body:
Bootstrap Grid System allows 12 columns across a page.
In order to avoid using all the 12 columns individually we can split the columns into sub columns as per our requirements.
However we need to ensure that the sub columns always sums up to 12 and never exceed 12 or else the content switches on to the next line.
So perform appropriate changes in your code as per the above concept and apart from  that to support the grid system in IE 11 consider including the following tag:

<meta http-equiv="X-UA-Compatible" content="IE=edge">

In order to have further knowledge about grid system visit the following link :
https://www.w3schools.com/bootstrap/bootstrap_grid_system.asp


问:
Fastest way to get subset of array of items into a string?
My method receives an array of positions that are used to concatenate some of the items in another array. Currently, I am looping through the positions and adding them to a StringBuilder, but is there a faster way? Does C# have some method that uses native code (similar to Java's System.arraycopy) to do a much faster "loop"?

Basic idea:

int[] positions = new int[] { 2, 5, 7 };
string[] values = new string[] { "one", "two", "three", "four", "five", "six", "seven", "eight" };

StringBuilder concat = new StringBuilder();

for ( int i = 0; i < positions.length; i++ )
{
    concat.Append(values[positions[i]]);
    concat.Append(",");
}
```

Is there anything faster?

答:
Try:</p>

```<code>int[] positions = new int[] { 2, 5, 7 };
string[] values = new string[] { "one", "two", "three", "four", "five", "six", "seven", "eight" };

var res = string.Join(",", positions.Select(f => values[f]));

</code>```

Body:
My method receives an array of positions that are used to concatenate some of the items in another array. Currently, I am looping through the positions and adding them to a StringBuilder, but is there a faster way? Does C# have some method that uses native code (similar to Java's System.arraycopy) to do a much faster "loop"?

Basic idea:

int[] positions = new int[] { 2, 5, 7 };
string[] values = new string[] { "one", "two", "three", "four", "five", "six", "seven", "eight" };

StringBuilder concat = new StringBuilder();

for ( int i = 0; i < positions.length; i++ )
{
    concat.Append(values[positions[i]]);
    concat.Append(",");
}

Is there anything faster?

Body:
Try:

int[] positions = new int[] { 2, 5, 7 };
string[] values = new string[] { "one", "two", "three", "four", "five", "six", "seven", "eight" };

var res = string.Join(",", positions.Select(f => values[f]));


问:
Software to draw graphical models in plate notation
So I see graphical models expressed in plate notation in research papers and online all the time (for example: http://www.cs.princeton.edu/~blei/papers/BleiNgJordan2003.pdf).

Is there a quick and easy way to produce these?? I've searched and searched but all I've found are solutions like GraphViz which are really way more powerful than what I need (and hence much more difficult to use). PGF/Tikz seems like my best bet, but again it seems like overkill.

Maybe my best bet is to just produce them in Inkscape, or bite the bullet and learn PGF/Tikz. They're just so popular that I thought there would be a simpler way to churn them out, but maybe not... TIA.

答: Check out the excellent Tikz-package by Laura Dietz, available from http://www.mpi-inf.mpg.de/~dietz/probabilistic-models-tikz.zip. A pdf with some examples is available at http://www.mpi-inf.mpg.de/~dietz/probabilistic-models-tikz.pdf.</p>


问:
How use reduce() to concat an array and delete the items duplicated
I have a problem using the reduce function in JavaScript. My goal is to take an array of arrays and, using reduce, then concat all the values and delete the duplicates:

I have an array like this:
firstArray = [[1, 2],[2, 3, 4],[4, 5, 6]]

I need an array like this after apply reduce():
resultArray = [1, 2, 3, 4, 5, 6]

```<code>const arrayElements = [[1,2],[2,3,4],[5,6]];
const newArray = arrayElements.reduce((total, value) => {
    return total.concat(value);
}, []);
</code>```

This is the fragment that I have, this only concat all the values, this is to say, [1, 2, 2, 3, 4, 5, 6]

答:
You can use Set and flat

const array = [[1,2],[2,3,4],[5,6]];
const newArray = [...new Set(array.flat(Infinity))]

console.log(newArray)```

Body:
I have a problem using the reduce function in JavaScript. My goal is to take an array of arrays and, using reduce, then concat all the values and delete the duplicates:

I have an array like this:
firstArray = [[1, 2],[2, 3, 4],[4, 5, 6]]

I need an array like this after apply reduce():
resultArray = [1, 2, 3, 4, 5, 6]

const arrayElements = [[1,2],[2,3,4],[5,6]];
const newArray = arrayElements.reduce((total, value) => {
    return total.concat(value);
}, []);

This is the fragment that I have, this only concat all the values, this is to say, [1, 2, 2, 3, 4, 5, 6]


问:
How to speed up a data file import in Excel VBA
Update as of June 11, 2019: I still haven’t figured out why practically all of my delay happens in those two lines, but current status is that I put up with the delay. So far, I have about 6000 rows of data in the master document, and an import process takes about 20 seconds regardless of how many rows I import.

—

I have a "master document" and I import data from lots and lots of little documents all day long. I admit I'm not a super-genius here, and a lot of my coding habits come from doing it "old school" so there may be "Excel ways" that I don't know (but want to learn!).

The issue I'm seeing is how much time a data file import can take.

When I started the tool out, data imports took only a few seconds.

Now that I have about 3500 rows of data, data imports take about 15-20 seconds. It doesn't matter if I am importing one row or a hundred rows. I expect this to keep going up. By the time I get to 7000 rows or 10,000 rows, I expect it to become unbearable.

By using message boxes (remember: "old school"), I've been able to narrow the speed bottleneck down to two lines of code. Between "Step 1" and "Step 2" is about 30% of my delay, and between "Step 2" and "Step 3" is about 70% of my delay.

I've included the whole sub below to make sure I'm not missing something obvious, but I made sure to UNINDENT my message boxes so you can go r-i-g-h-t to the code I suspect. Also, I included the entire sub because usually one of the first responses is “can you show the whole sub so I have better context?”

Thank you kindly for any thoughts or suggestions you might have. :)

```<code>Private Sub Btn_ImportDataFiles_Click()
  ' Search the current worksheet and assign the next TransactionID
    Dim TransactionCounter As Integer
    Dim TransactionID As Long ' This is the next available Transaction ID
    TransactionID = Application.WorksheetFunction.Max(Range("a:a")) + 1
  ' open the file and import the data
    Dim customerBook As Workbook
    Dim filter As String
    Dim caption As String
    Dim customerFilename As String
    Dim customerWorkbook As Workbook
    Dim targetWorkbook As Workbook

    ' make weak assumption that active workbook is the target
      Set targetWorkbook = Application.ActiveWorkbook

    ' get the customer workbook
      filter = "Text files (*.xlsx),*.xlsx"
      caption = "Please Select an input file "
      customerFilename = Application.GetOpenFilename(filter, , caption)

    If customerFilename <> "False" Then
    ' If they have uploaded the file before, let them know.
    ' If they want to keep uploading it, no harm done,
    ' but no need to stupidly add data that is already present.
    ' Select the archive sheet
      Sheets("Upload_Archive").Select
      Dim FileNameHunt As String
      Dim cell As Range
      Dim ContinueUpload As Boolean
      ContinueUpload = True
      FileNameHunt = Mid(customerFilename, InStrRev(customerFilename, "\") + 1)
      Columns("A:A").Select
      Set cell = Selection.Find(what:=FileNameHunt, after:=ActiveCell, LookIn:=xlFormulas, lookat:=xlWhole, searchorder:=xlByRows, searchdirection:=xlNext, MatchCase:=False, searchformat:=False)
      If cell Is Nothing Then ' Add the new filename to the archive
        Sheets("Upload_Archive").Select
        Rows(1).Insert shift:=xlDown
        Range("a1:a1").Value = FileNameHunt
        Sheets("MasterSheet").Select
        Application.Cells.Font.Name = "Calibri Light"
        Application.Cells.Font.Size = "8"
        Application.Cells.Font.Bold = False
      Else
        response = MsgBox("This data file has previously been uploaded. " & vbCrLf & "Do you want to cancel this upload?" & vbCrLf & vbCrLf & "Pressing [yes] will cancel the process." & vbCrLf & "Pressing [no] will continue with the file upload" & vbCrLf & "and add the data to the tracking sheet.", vbYesNo)
        If response = vbYes Then
          ContinueUpload = False
          Sheets("MasterSheet").Select
          Exit Sub
        End If
      End If ' If cell Is Nothing Then...

      If ContinueUpload = True Then
        ' Continue with data upload procedure
          Sheets("MasterSheet").Select
          Set customerWorkbook = Application.Workbooks.Open(customerFilename)
        ' Copy data from customer to target workbook
          Dim targetSheet As Worksheet
          Set targetSheet = targetWorkbook.Worksheets(1)
          Dim sourceSheet As Worksheet
          Set sourceSheet = customerWorkbook.Worksheets(1)
          Dim ImportRecordCount As Integer
          ImportRecordCount = sourceSheet.Range("B1")
          Dim ReconciliationID As String
          ReconciliationID = ""
          If sourceSheet.Range("E3") = "Removed from Depot" Then ReconciliationID = "1"
MsgBox ("Step 1")
          targetSheet.Range("A1").EntireRow.Offset(1).Resize(ImportRecordCount).Insert shift:=xlDown ' Add the blank rows
MsgBox ("Step 2")
          targetSheet.Range("B2:AB" & ImportRecordCount + 1).Value = sourceSheet.Range("A3:AA" & ImportRecordCount + 2).Value ' Bring in the big pile of data
MsgBox ("Step 3")
          targetSheet.Range("AJ2:AJ" & ImportRecordCount + 1).Value = ReconciliationID ' To help with reconciling shipments
          targetSheet.Range("AK2:AK" & ImportRecordCount + 1).Value = ReconciliationID ' To help with deployment timing
          'targetSheet.Range("AI2:AI" & ImportRecordCount + 1).Value = "=COUNTIFS($D:$D, D2, $F:$F, F2)" ' This is the helper formula for identifying duplicates (deprecated, but I'm saving the code)
          For TransactionCounter = 2 To ImportRecordCount + 1 ' Create and add the new Transaction ID values
            targetSheet.Range("a" & TransactionCounter) = TransactionID + ImportRecordCount - TransactionCounter + 1
          Next
        ' Close customer workbook
          customerWorkbook.Close
        ' Format the sheet properly
          Application.Cells.Font.Name = "Calibri Light"
          Application.Cells.Font.Size = "8"
          Application.Cells.Font.Bold = False
          Application.Range("1:1").Font.Size = "10"
          Application.Range("1:1").Font.Bold = True
        ' Query the User -- delete the file?
          If MsgBox("Delete the local client-generated data file?" & vbCrLf & vbCrLf & "(this will NOT affect your email)", vbYesNo, "Confirm") = vbYes Then
            Kill customerFilename
            ' MsgBox ("File: " & vbCrLf & customerFilename & vbCrLf & "has been deleted.")
          End If
      End If ' If ContinueUpload = True Then
    End If ' If customerFilename <> "False" Then

End Sub

</code>```

edit

I edited your original question to highlight things I found as suspect. These are things I felt are worth pointing out to you. I shaved everything else out as to focus on these particular issue. Review them and do soem research to see if you can find yourself in a better situation.

```<code>    MsgBox ("Step 2")

        'Ive never moved large amounts of data using this method. Ive always just used arrays. I have moved smaller bits of data though.
        ' I suspect that this might take a moment if the data set is large. Again use arrays to grab the data and move it.
        ' Edward says “This step takes about 70% of my delay — even if bringing in only a single line of data.”

        targetSheet.Range("B2:AB" & ImportRecordCount + 1).Value = sourceSheet.Range("A3:AA" & ImportRecordCount + 2).Value ' Bring in the big pile of data

    MsgBox ("Step 3")

      ' this loop is probably your main culprit of your performance issue.
      ' Edward says “Nope, this flies by. It is not the issue at all. I have verified this already.”
      ' Learn how to construct an array of data on the fly and then learn how to dump the entire array to
      ' sheet using a simple method.

        For TransactionCounter = 2 To ImportRecordCount + 1 ' Create and add the new Transaction ID values
            targetSheet.Range("a" & TransactionCounter) = TransactionID + ImportRecordCount - TransactionCounter + 1
        Next
</code>```

答:
It looks like you have a lot of good things going here. A few things that I saw that could potentially be changed to improve your performance.

First, between "Step 1" and "Step 2": In my  experience, adding rows takes longer than using rows that already exist. It looks like you are basically "pushing" everything down to make room for the new data, such that the newly entered data is at the top and the oldest data is at the bottom. (Correct me if I am wrong on any of this.) If you were to simply add the data to the end of the sheet, you would probably see some performance improvements, although I don't know how big of an improvement it would be.

Second, between "Step 2" and "Step 3": I have found that using .Value2 as opposed to .Value can give you some performance improvements, and the larger the data the bigger the improvement. This has a down side - Value2 does not retain any of the formatting that might be present, meaning that the number type (date, accounting, etc) does not pull over correctly. If this is something that you do not need, then you can use Value2.

Finally, other methods: When I run extensive macros, I always try to do everything I can to get a performance boost. You can get slight boosts across the board by using tricks like turning off screen updating (Application.ScreenUpdating = False), just be sure to turn it back on at the end of the macro.

I hope that this helps you figure it out! If all else fails, you can do it once or twice by hand to remember how much faster it is using the macro! Haha. Good Luck!

Body:
Update as of June 11, 2019: I still haven’t figured out why practically all of my delay happens in those two lines, but current status is that I put up with the delay. So far, I have about 6000 rows of data in the master document, and an import process takes about 20 seconds regardless of how many rows I import.

—

I have a "master document" and I import data from lots and lots of little documents all day long. I admit I'm not a super-genius here, and a lot of my coding habits come from doing it "old school" so there may be "Excel ways" that I don't know (but want to learn!).

The issue I'm seeing is how much time a data file import can take.

When I started the tool out, data imports took only a few seconds.

Now that I have about 3500 rows of data, data imports take about 15-20 seconds. It doesn't matter if I am importing one row or a hundred rows. I expect this to keep going up. By the time I get to 7000 rows or 10,000 rows, I expect it to become unbearable.

By using message boxes (remember: "old school"), I've been able to narrow the speed bottleneck down to two lines of code. Between "Step 1" and "Step 2" is about 30% of my delay, and between "Step 2" and "Step 3" is about 70% of my delay.

I've included the whole sub below to make sure I'm not missing something obvious, but I made sure to UNINDENT my message boxes so you can go r-i-g-h-t to the code I suspect. Also, I included the entire sub because usually one of the first responses is “can you show the whole sub so I have better context?”

Thank you kindly for any thoughts or suggestions you might have. :)

Private Sub Btn_ImportDataFiles_Click()
  ' Search the current worksheet and assign the next TransactionID
    Dim TransactionCounter As Integer
    Dim TransactionID As Long ' This is the next available Transaction ID
    TransactionID = Application.WorksheetFunction.Max(Range("a:a")) + 1
  ' open the file and import the data
    Dim customerBook As Workbook
    Dim filter As String
    Dim caption As String
    Dim customerFilename As String
    Dim customerWorkbook As Workbook
    Dim targetWorkbook As Workbook

    ' make weak assumption that active workbook is the target
      Set targetWorkbook = Application.ActiveWorkbook

    ' get the customer workbook
      filter = "Text files (*.xlsx),*.xlsx"
      caption = "Please Select an input file "
      customerFilename = Application.GetOpenFilename(filter, , caption)

    If customerFilename <> "False" Then
    ' If they have uploaded the file before, let them know.
    ' If they want to keep uploading it, no harm done,
    ' but no need to stupidly add data that is already present.
    ' Select the archive sheet
      Sheets("Upload_Archive").Select
      Dim FileNameHunt As String
      Dim cell As Range
      Dim ContinueUpload As Boolean
      ContinueUpload = True
      FileNameHunt = Mid(customerFilename, InStrRev(customerFilename, "\") + 1)
      Columns("A:A").Select
      Set cell = Selection.Find(what:=FileNameHunt, after:=ActiveCell, LookIn:=xlFormulas, lookat:=xlWhole, searchorder:=xlByRows, searchdirection:=xlNext, MatchCase:=False, searchformat:=False)
      If cell Is Nothing Then ' Add the new filename to the archive
        Sheets("Upload_Archive").Select
        Rows(1).Insert shift:=xlDown
        Range("a1:a1").Value = FileNameHunt
        Sheets("MasterSheet").Select
        Application.Cells.Font.Name = "Calibri Light"
        Application.Cells.Font.Size = "8"
        Application.Cells.Font.Bold = False
      Else
        response = MsgBox("This data file has previously been uploaded. " & vbCrLf & "Do you want to cancel this upload?" & vbCrLf & vbCrLf & "Pressing [yes] will cancel the process." & vbCrLf & "Pressing [no] will continue with the file upload" & vbCrLf & "and add the data to the tracking sheet.", vbYesNo)
        If response = vbYes Then
          ContinueUpload = False
          Sheets("MasterSheet").Select
          Exit Sub
        End If
      End If ' If cell Is Nothing Then...

      If ContinueUpload = True Then
        ' Continue with data upload procedure
          Sheets("MasterSheet").Select
          Set customerWorkbook = Application.Workbooks.Open(customerFilename)
        ' Copy data from customer to target workbook
          Dim targetSheet As Worksheet
          Set targetSheet = targetWorkbook.Worksheets(1)
          Dim sourceSheet As Worksheet
          Set sourceSheet = customerWorkbook.Worksheets(1)
          Dim ImportRecordCount As Integer
          ImportRecordCount = sourceSheet.Range("B1")
          Dim ReconciliationID As String
          ReconciliationID = ""
          If sourceSheet.Range("E3") = "Removed from Depot" Then ReconciliationID = "1"
MsgBox ("Step 1")
          targetSheet.Range("A1").EntireRow.Offset(1).Resize(ImportRecordCount).Insert shift:=xlDown ' Add the blank rows
MsgBox ("Step 2")
          targetSheet.Range("B2:AB" & ImportRecordCount + 1).Value = sourceSheet.Range("A3:AA" & ImportRecordCount + 2).Value ' Bring in the big pile of data
MsgBox ("Step 3")
          targetSheet.Range("AJ2:AJ" & ImportRecordCount + 1).Value = ReconciliationID ' To help with reconciling shipments
          targetSheet.Range("AK2:AK" & ImportRecordCount + 1).Value = ReconciliationID ' To help with deployment timing
          'targetSheet.Range("AI2:AI" & ImportRecordCount + 1).Value = "=COUNTIFS($D:$D, D2, $F:$F, F2)" ' This is the helper formula for identifying duplicates (deprecated, but I'm saving the code)
          For TransactionCounter = 2 To ImportRecordCount + 1 ' Create and add the new Transaction ID values
            targetSheet.Range("a" & TransactionCounter) = TransactionID + ImportRecordCount - TransactionCounter + 1
          Next
        ' Close customer workbook
          customerWorkbook.Close
        ' Format the sheet properly
          Application.Cells.Font.Name = "Calibri Light"
          Application.Cells.Font.Size = "8"
          Application.Cells.Font.Bold = False
          Application.Range("1:1").Font.Size = "10"
          Application.Range("1:1").Font.Bold = True
        ' Query the User -- delete the file?
          If MsgBox("Delete the local client-generated data file?" & vbCrLf & vbCrLf & "(this will NOT affect your email)", vbYesNo, "Confirm") = vbYes Then
            Kill customerFilename
            ' MsgBox ("File: " & vbCrLf & customerFilename & vbCrLf & "has been deleted.")
          End If
      End If ' If ContinueUpload = True Then
    End If ' If customerFilename <> "False" Then

End Sub

edit

I edited your original question to highlight things I found as suspect. These are things I felt are worth pointing out to you. I shaved everything else out as to focus on these particular issue. Review them and do soem research to see if you can find yourself in a better situation.

    MsgBox ("Step 2")

        'Ive never moved large amounts of data using this method. Ive always just used arrays. I have moved smaller bits of data though.
        ' I suspect that this might take a moment if the data set is large. Again use arrays to grab the data and move it.
        ' Edward says “This step takes about 70% of my delay — even if bringing in only a single line of data.”

        targetSheet.Range("B2:AB" & ImportRecordCount + 1).Value = sourceSheet.Range("A3:AA" & ImportRecordCount + 2).Value ' Bring in the big pile of data

    MsgBox ("Step 3")

      ' this loop is probably your main culprit of your performance issue.
      ' Edward says “Nope, this flies by. It is not the issue at all. I have verified this already.”
      ' Learn how to construct an array of data on the fly and then learn how to dump the entire array to
      ' sheet using a simple method.

        For TransactionCounter = 2 To ImportRecordCount + 1 ' Create and add the new Transaction ID values
            targetSheet.Range("a" & TransactionCounter) = TransactionID + ImportRecordCount - TransactionCounter + 1
        Next


问:
Ordered list in Django
Can anyone help, I want to return an ordered list based on forloop in Django using a field in the model that contains both integer and string in the format MM/1234. The loop should return the values with the least interger(1234) in ascending order in the html template.</p>

答:
Ideally you want to change the model to have two fields, one integer and one string, so you can code a queryset with ordering based on the integer one. You can then define a property of the model to return the self.MM+"/"+str( self.nn) composite value if you often need to use that. But if it's somebody else's database schema, this may not be an option.

In which case you'll have to convert your queryset into a list (which reads all the data rows at once) and then sort the list in Python rather than in the database. You can run out of memory or bring your server to its knees if the list contains millions of objects. count=qs.count() is a DB operation that won't.

```<code>qs = Foo.objects.filter( your_selection_criteria)
# you might want to count this before the next step, and chicken out if too many
# also this simple key function will crash if there's ever no "/" in that_field
all_obj = sorted( list( qs),
            key = lambda obj: obj.that_field.split('/')[1] )
</code>```

Title: Ordered list in Django

Body:
Ideally you want to change the model to have two fields, one integer and one string, so you can code a queryset with ordering based on the integer one. You can then define a property of the model to return the self.MM+"/"+str( self.nn) composite value if you often need to use that. But if it's somebody else's database schema, this may not be an option.

In which case you'll have to convert your queryset into a list (which reads all the data rows at once) and then sort the list in Python rather than in the database. You can run out of memory or bring your server to its knees if the list contains millions of objects. count=qs.count() is a DB operation that won't.

qs = Foo.objects.filter( your_selection_criteria)
# you might want to count this before the next step, and chicken out if too many
# also this simple key function will crash if there's ever no "/" in that_field
all_obj = sorted( list( qs),
            key = lambda obj: obj.that_field.split('/')[1] )


问:
How to use variable cells referrals to link them between different workbooks (variable: worksheet name)
I need to use variable referrals to link data between two different workbooks. My scope is wage calculations for more employees.

One workbook contains the data (working hours split in different columns, e.g. overtime hours, nightshift hours, weekend hours, etc. for different rows that are the single days). Let's call it WORKING HOURS.

The other workbook have to use these data to make the calculations. Let's call it WAGES.

Both of these workbooks contain different worksheets, each one named with the employee's full name.

Now, I need to link the total values (e.g. total working hours) in the cells inside the WORKING HOURS to the empty cells of WAGES, but in a way that is variable depending on the name of the worksheet (that is, the full name of the specific employee).

Is it something that could be done only by using Macro/code or is there a way to put variables in the formula {='[WORKING HOURS.xls]JOHN SMITH'!$E$38} where replacing the part of "JOHN SMITH" with, let's say, active worksheet name code string?

Thanks in advance

答:
E.g.

=INDIRECT("'[WORKING HOURS.xls]" & $B$5 & "'!E38")

where:

B5 is the cell which contains the active sheet name (outputted with a formula like the following one)
=MID(CELL("filename",A1),FIND("]",CELL("filename",A1))+1,255)

E38 is the cell which contains the total working hours


问:
socket.recvmsg is ignoring ancbufsize, ancillary data
Using a TCP socket, on a unix system, python is seemingly ignoring my ancbufsize completely.

```<code>data, ancdata, msg_flags, address = sock.recvmsg(1, socket.CMSG_LEN(4))
</code>```

From the linux man page for recvmsg:

size_t        msg_controllen; /* ancillary data buffer len */

If I strace my program, I see that msg_controllen is 0, I cant seem to do anything to get it to have a non-zero value. Is there some other package I need to install? Running pretty stock centos7

Here is the recvmsg call in my strace output:

```<code>recvmsg(3, {msg_name(0)=0x7ffcc97e2c90, msg_iov(1)=[{"\360", 1}], msg_controllen=0, msg_flags=0}, 0) = 1
</code>```

This returns only the msg_iov, and has no ancillary data, presumably because msg_controllen is 0.

the above returns "360"

答:
How does ancillary data in sendmsg() work?

I think that ancillary data is never sent over a TCP socket, frustrating that is not listed in many documents, including the python socket docs, c message docs, or even the APUE book

Body:
Using a TCP socket, on a unix system, python is seemingly ignoring my ancbufsize completely.

data, ancdata, msg_flags, address = sock.recvmsg(1, socket.CMSG_LEN(4))

From the linux man page for recvmsg:

size_t        msg_controllen; /* ancillary data buffer len */

If I strace my program, I see that msg_controllen is 0, I cant seem to do anything to get it to have a non-zero value. Is there some other package I need to install? Running pretty stock centos7

Here is the recvmsg call in my strace output:

recvmsg(3, {msg_name(0)=0x7ffcc97e2c90, msg_iov(1)=[{"\360", 1}], msg_controllen=0, msg_flags=0}, 0) = 1

This returns only the msg_iov, and has no ancillary data, presumably because msg_controllen is 0.

the above returns "360"


问:
How do I use functions from Project 1 in Project 2?
Im wondering how I would call functions from Project 1 in Project 2.
What I have already done is adding my first Project as a reference to my second project but if I try to call, for example hello(); it wont work.
I'd really appreciate help.

Thanks!

答:
Simple:
Create a library (Project 3) of the stuff you want to share between projects. Link the library in both projects.</p>


答:
As far as i know the for loop is one of the fastest loops in c#, in this case your code cannot be made parallel. So short answer is no, it cant be made faster.

Long answer, while there will be no performance improvement, there is no need to use a string builder here, you can simply append without the string builder. just delcare concat as a string and you can do something like this inside the for loop

```<code>concat += $"{values[positions[i]]},"
</code>```

One thing to mention, while you might have taken this into account position 0 will return value "three" remember in c# arrays starts from 0

EDIT: From what the user Steve point out i did a lil try and error, and i found the fastest way is to do it like this

```<code>        string concat3 = "";
        for (int i = 0; i < positions.Length; i++)
        {
            concat3 += values[positions[i]] + ", ";
        }
        Console.WriteLine(stop.ElapsedTicks);
</code>```

but we are talking about 5 ticks (with around 20 tries from each) of difference between the 3 of them so i wouldnt not even consider this to be a downgrade in performance

Title: Fastest way to get subset of array of items into a string?

Body:
As far as i know the for loop is one of the fastest loops in c#, in this case your code cannot be made parallel. So short answer is no, it cant be made faster.

Long answer, while there will be no performance improvement, there is no need to use a string builder here, you can simply append without the string builder. just delcare concat as a string and you can do something like this inside the for loop

concat += $"{values[positions[i]]},"

One thing to mention, while you might have taken this into account position 0 will return value "three" remember in c# arrays starts from 0

EDIT: From what the user Steve point out i did a lil try and error, and i found the fastest way is to do it like this

        string concat3 = "";
        for (int i = 0; i < positions.Length; i++)
        {
            concat3 += values[positions[i]] + ", ";
        }
        Console.WriteLine(stop.ElapsedTicks);

but we are talking about 5 ticks (with around 20 tries from each) of difference between the 3 of them so i wouldnt not even consider this to be a downgrade in performance


问:
Python Pandas, how can I merge 2 columns of a csv taking only the values valued?
I haven't been able to create a column for 2 days starting from 2 columns inside a CSV file; my interest is to create a third column by taking the values of the 2 columns:

Example:

```<code>Column        | NUMBER 1 | NUMBER 2 | NUMBER 3 | NUMBER 4 | NUMBER 5 |
                                                   YES        NaN
                                                   NaN         YES
                                                   NO         NaN
                                                   YES        NaN

Column | NUMBER 6 |
           YES
           YES
           NO
           YES
</code>```

I have tried

df['Number6'] = df['Number4'].fillna(df['Number5'])
```

but I have only value of Number4 column.

where is the error?

Thanks a lot

Marco

答:
I used your sample data:

```<code>df = pd.DataFrame(data=[[ 'YES',  np.nan ], [ np.nan, 'YES' ],
    [ 'NO',   np.nan ], [ 'YES',  np.nan ]],
    columns=['Number4', 'Number5'])
</code>```

Then I executed your instruction:

```<code>df['Number6'] = df['Number4'].fillna(df['Number5'])
</code>```

and I got just your expected result:

```<code>  Number4 Number5 Number6
0     YES     NaN     YES
1     NaN     YES     YES
2      NO     NaN      NO
3     YES     NaN     YES
</code>```

I'm using Python 3.7 and Jupyter Notebook. Maybe you should upgrade
your installation?

I noticed also that your heading contains e.g. NUMBER 4 not Number4.
Did you write correct column names?

Body:
I haven't been able to create a column for 2 days starting from 2 columns inside a CSV file; my interest is to create a third column by taking the values of the 2 columns:

Example:

Column        | NUMBER 1 | NUMBER 2 | NUMBER 3 | NUMBER 4 | NUMBER 5 |
                                                   YES        NaN
                                                   NaN         YES
                                                   NO         NaN
                                                   YES        NaN

Column | NUMBER 6 |
           YES
           YES
           NO
           YES

I have tried

df['Number6'] = df['Number4'].fillna(df['Number5'])

but I have only value of Number4 column.

where is the error?

Thanks a lot

Marco

Body:
I used your sample data:

df = pd.DataFrame(data=[[ 'YES',  np.nan ], [ np.nan, 'YES' ],
    [ 'NO',   np.nan ], [ 'YES',  np.nan ]],
    columns=['Number4', 'Number5'])

Then I executed your instruction:

df['Number6'] = df['Number4'].fillna(df['Number5'])

and I got just your expected result:

  Number4 Number5 Number6
0     YES     NaN     YES
1     NaN     YES     YES
2      NO     NaN      NO
3     YES     NaN     YES

I'm using Python 3.7 and Jupyter Notebook. Maybe you should upgrade
your installation?

I noticed also that your heading contains e.g. NUMBER 4 not Number4.
Did you write correct column names?


问:
Methods, Loops and the `this` Keyword
I am new at Javascript. I am currently looking at the keyword this and methods and how to return strings.
I am struggling to return a string using the keyword this.

I have successfully created code that returns the string, but the problem is that it shows the error that "the object is already defined".

Here is the exercise I am working on and also the code I have tried to create which fails to return the correct results:

```<code>function exerciseTwo(userObj) {

  // Exercise Two: You will be given an object called 'userObj'
  // userObject will already have a key on it called 'name'
  // Add a method to userObj, called 'greeting'.
  // Using the keyword 'this', the greeting method should return the following string:
  // 'Hi, my name is ' and the users name.
  // eg: If userObj has a name: 'Dan', greeting should return: Hi, my name is Dan'
  // NOTE: DO NOT create a new object.
  // NOTE: DO NOT create a key called name the key is already on the object.

  let userObj = {
    name: "Lisa",
    greeting: function() {
      return "Hi, my name is " + this.name;
    },
  };
  console.log(userObj.greeting());
}

//In the first line of code it shows a error which says that "userObj" is already defined. So I do not know how to return the string without creating a new object and creating a key called name.

//Here is another option I tried but it also did not work out:

function greeting() {
  this.name = "Lisa";
  let result = "Hi, my name is " + this.name;
  return result;
},
userObj.greeting();
}

//The exercise should add a greeting method to userObject object.
</code>```

So if userObj has a name: 'Lisa', greeting should return: 'Hi, my name is Lisa'

答:
As the exercise says you only have to add the greeting function to the users object. Like this:</p>

```<code>let userObj = { name: "Lisa" };

function exercise2(userObj) {
    userObj.greetings = function () {
        return "Hi, my name is " + this.name;
    }
}

exercise2(userObj);

console.log(userObj.greetings());
</code>```

Title: Methods, Loops and the `this` Keyword

Body:
I am new at Javascript. I am currently looking at the keyword this and methods and how to return strings.
I am struggling to return a string using the keyword this.

I have successfully created code that returns the string, but the problem is that it shows the error that "the object is already defined".

Here is the exercise I am working on and also the code I have tried to create which fails to return the correct results:

function exerciseTwo(userObj) {

  // Exercise Two: You will be given an object called 'userObj'
  // userObject will already have a key on it called 'name'
  // Add a method to userObj, called 'greeting'.
  // Using the keyword 'this', the greeting method should return the following string:
  // 'Hi, my name is ' and the users name.
  // eg: If userObj has a name: 'Dan', greeting should return: Hi, my name is Dan'
  // NOTE: DO NOT create a new object.
  // NOTE: DO NOT create a key called name the key is already on the object.

  let userObj = {
    name: "Lisa",
    greeting: function() {
      return "Hi, my name is " + this.name;
    },
  };
  console.log(userObj.greeting());
}

//In the first line of code it shows a error which says that "userObj" is already defined. So I do not know how to return the string without creating a new object and creating a key called name.

//Here is another option I tried but it also did not work out:

function greeting() {
  this.name = "Lisa";
  let result = "Hi, my name is " + this.name;
  return result;
},
userObj.greeting();
}

//The exercise should add a greeting method to userObject object.

So if userObj has a name: 'Lisa', greeting should return: 'Hi, my name is Lisa'

Body:
As the exercise says you only have to add the greeting function to the users object. Like this:

let userObj = { name: "Lisa" };

function exercise2(userObj) {
    userObj.greetings = function () {
        return "Hi, my name is " + this.name;
    }
}

exercise2(userObj);

console.log(userObj.greetings());


问:
Read specific columns from a csv file with csv module?
I'm trying to parse through a csv file and extract the data from only specific columns.

Example csv:

ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
```

<p>I'm trying to capture only specific columns, say <code>ID</code>, <code>Name</code>, <code>Zip</code> and <code>Phone</code>.</p>

<p>Code I've looked at has led me to believe I can call the specific column by its corresponding number, so ie: <code>Name</code> would correspond to <code>2</code> and iterating through each row using <code>row[2]</code> would produce all the items in column 2. Only it doesn't.</p>

<p>Here's what I've done so far:</p>

```import sys, argparse, csv
from settings import *

# command arguments
parser = argparse.ArgumentParser(description='csv to postgres',\
 fromfile_prefix_chars="@" )
parser.add_argument('file', help='csv file to import', action='store')
args = parser.parse_args()
csv_file = args.file

# open csv file
with open(csv_file, 'rb') as csvfile:

    # get number of columns
    for line in csvfile.readlines():
        array = line.split(',')
        first_item = array[0]

    num_columns = len(array)
    csvfile.seek(0)

    reader = csv.reader(csvfile, delimiter=' ')
        included_cols = [1, 2, 6, 7]

    for row in reader:
            content = list(row[i] for i in included_cols)
            print content
```

and I'm expecting that this will print out only the specific columns I want for each row except it doesn't, I get the last column only.

答:
```<code>import pandas as pd
csv_file = pd.read_csv("file.csv")
column_val_list = csv_file.column_name._ndarray_values
</code>```

Body:
I'm trying to parse through a csv file and extract the data from only specific columns.

Example csv:

ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |

I'm trying to capture only specific columns, say ID, Name, Zip and Phone.

Code I've looked at has led me to believe I can call the specific column by its corresponding number, so ie: Name would correspond to 2 and iterating through each row using row[2] would produce all the items in column 2. Only it doesn't.

Here's what I've done so far:

import sys, argparse, csv
from settings import *

# command arguments
parser = argparse.ArgumentParser(description='csv to postgres',\
 fromfile_prefix_chars="@" )
parser.add_argument('file', help='csv file to import', action='store')
args = parser.parse_args()
csv_file = args.file

# open csv file
with open(csv_file, 'rb') as csvfile:

    # get number of columns
    for line in csvfile.readlines():
        array = line.split(',')
        first_item = array[0]

    num_columns = len(array)
    csvfile.seek(0)

    reader = csv.reader(csvfile, delimiter=' ')
        included_cols = [1, 2, 6, 7]

    for row in reader:
            content = list(row[i] for i in included_cols)
            print content

and I'm expecting that this will print out only the specific columns I want for each row except it doesn't, I get the last column only.


问:
How to escape single quote (') character in scilab?
I want to print the symbol ' (quote)

for example:

disp (' ' ')

and the output that I would like to get is:
'

But, as the ' is the string delimiter, I can't use that way.

Is there a code which I can use instead of the symbol ' ?

thank you

disp (' ' ')

答: I don't know scilab, but you could try to escape the character like this disp('\''). Also, If scilab supports it, you could also use double quotes like this: disp("'")