问:
Regex to match all us phone number formats
First of all i would say i have seen many example here and googled but none found that matches all the condition i am looking for some match top 3 not below some inbetween.
Kindly let me know how to put all of them in one place.

```<code>(xxx)xxxxxxx
(xxx) xxxxxxx
(xxx)xxx-xxxx
(xxx) xxx-xxxx
xxxxxxxxxx
xxx-xxx-xxxxx
</code>```

Using as :

```<code>  const string MatchPhonePattern =
           @"\(?\d{3}\)?-? *\d{3}-? *-?\d{4}";
            Regex rx = new Regex(MatchPhonePattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            // Find matches.
            MatchCollection matches = rx.Matches(text);
            // Report the number of matches found.
            int noOfMatches = matches.Count;
            // Report on each match.

            foreach (Match match in matches)
            {

                tempPhoneNumbers= match.Value.ToString(); ;

             }
</code>```

SAMPLE OUTPUT:

```<code>3087774825
(281)388-0388
(281)388-0300
(979) 778-0978
(281)934-2479
(281)934-2447
(979)826-3273
(979)826-3255
1334714149
(281)356-2530
(281)356-5264
(936)825-2081
(832)595-9500
(832)595-9501
281-342-2452
1334431660
</code>```

Body:
First of all i would say i have seen many example here and googled but none found that matches all the condition i am looking for some match top 3 not below some inbetween.
Kindly let me know how to put all of them in one place.

(xxx)xxxxxxx
(xxx) xxxxxxx
(xxx)xxx-xxxx
(xxx) xxx-xxxx
xxxxxxxxxx
xxx-xxx-xxxxx

Using as :

  const string MatchPhonePattern =
           @"\(?\d{3}\)?-? *\d{3}-? *-?\d{4}";
            Regex rx = new Regex(MatchPhonePattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            // Find matches.
            MatchCollection matches = rx.Matches(text);
            // Report the number of matches found.
            int noOfMatches = matches.Count;
            // Report on each match.

            foreach (Match match in matches)
            {

                tempPhoneNumbers= match.Value.ToString(); ;

             }

SAMPLE OUTPUT:

3087774825
(281)388-0388
(281)388-0300
(979) 778-0978
(281)934-2479
(281)934-2447
(979)826-3273
(979)826-3255
1334714149
(281)356-2530
(281)356-5264
(936)825-2081
(832)595-9500
(832)595-9501
281-342-2452
1334431660

Body:
^?\(?\d{3}?\)??-??\(?\d{3}?\)??-??\(?\d{4}?\)??-?$

This allows:

(123)-456-7890

123-456-7890


来源: stackexchange

问:
Find the second maximum number in an array with the smallest complexity
Tried to googled it but with no luck.
How can I find the second maximum number in an array with the smallest complexity?

code OR idea will be much help.

I can loop through an array and look for the maximum number
after that, I have the maximum number and then loop the array again to find the second the same way.

But for sure it is not efficient.

答:
```<code>/* we can use recursion */
var counter = 0;
     findSecondMax = (arr)=> {

        let max = Math.max(...arr);
        counter++;
        return counter == 1 ? findSecondMax(arr.slice(0,arr.indexOf(max)).concat(arr.slice(arr.indexOf(max)+1))) : max;
    }

    console.log(findSecondMax([1,5,2,3,0]))
</code>```

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Evaluating a List of Variables to a List of Their Values in Common Lisp
I am wondering how one can achieve the following. Suppose I have a list of variables that are bound by some let above. I would like to turn this list into a list of the values to which those variables are bound.

That is, suppose we have

```<code>(define make-plist-from-variables (variables)
  (let ((keys variables)
        (values (mapcar #'identity variables)))
    (if (eq (length keys) (length values))
     (make-plist keys values)
     nil))))
</code>```

What can I use in place of #'identity to unpack those values properly?

At the moment, the following call produces the following output.

```<code>CL-USER> (let ((a 2) (b 3)) (make-plist-from-variables '(a b)))
(A A B B)
</code>```

I would like it to be (A 2 B 3)

答:
It needs to be a macro because there is no way to fetch a variable's lexical value based on its symbol.

```<code>(defmacro make-plist-from-variables (&rest variables)
  (loop :for binding :in variables
        :collect `',binding :into result
        :collect binding :into result
        :finally (return `(list ,@result))))

(macroexpand-1 '(make-plist-from-variables a b))
; ==> (list 'a a 'b b)

(let ((a 2) (b 3))
  (make-plist-from-variables a b))
; ==> (a 2 b 3)
</code>```

EDIT

Implementation without loop using mapcan:

```<code>(defmacro make-plist-from-variables (&rest variables)
  `(list ,@(mapcan (lambda (v) `(',v ,v)) variables))
</code>```

Body:
I am wondering how one can achieve the following. Suppose I have a list of variables that are bound by some let above. I would like to turn this list into a list of the values to which those variables are bound.

That is, suppose we have

(define make-plist-from-variables (variables)
  (let ((keys variables)
        (values (mapcar #'identity variables)))
    (if (eq (length keys) (length values))
     (make-plist keys values)
     nil))))

What can I use in place of #'identity to unpack those values properly?

At the moment, the following call produces the following output.

CL-USER> (let ((a 2) (b 3)) (make-plist-from-variables '(a b)))
(A A B B)

I would like it to be (A 2 B 3)

Body:
It needs to be a macro because there is no way to fetch a variable's lexical value based on its symbol.

(defmacro make-plist-from-variables (&rest variables)
  (loop :for binding :in variables
        :collect `',binding :into result
        :collect binding :into result
        :finally (return `(list ,@result))))

(macroexpand-1 '(make-plist-from-variables a b))
; ==> (list 'a a 'b b)

(let ((a 2) (b 3))
  (make-plist-from-variables a b))
; ==> (a 2 b 3)

EDIT

Implementation without loop using mapcan:

(defmacro make-plist-from-variables (&rest variables)
  `(list ,@(mapcan (lambda (v) `(',v ,v)) variables))


问:
What does the rotation matrix truly represent, with only 1 image or camera?
The concept of extrinsic parameters of a camera seem fuzzy to me when there is only one viewing plane.  What is the rotation matrix and translation vector relative to when we only have one image?  Why wouldn't this always be the origin?</p>

答:
It appears you are recovering extrinsic parameters (R+T, 6 DOF) from one image of a known object (calibration target). If this is true, then the recovered parameters correspond to the camera pose relative to the intrinsic coordinate system of the calibration target. </p>

<p>For instance, if you are viewing a Zhang's planar target, and if you denote the target point coordinates as (0,0), (0,1), (0,2), ..., (1,0), (1,1), etc, then the recovered camera pose is relative to the coordinate system with origin at (0,0), and whose axes are defined by the vectors e1((0,0),(0,1)), e2((0,0),(1,0)) and e3 = e1 x e2. </p>

Body:
It appears you are recovering extrinsic parameters (R+T, 6 DOF) from one image of a known object (calibration target). If this is true, then the recovered parameters correspond to the camera pose relative to the intrinsic coordinate system of the calibration target.

For instance, if you are viewing a Zhang's planar target, and if you denote the target point coordinates as (0,0), (0,1), (0,2), ..., (1,0), (1,1), etc, then the recovered camera pose is relative to the coordinate system with origin at (0,0), and whose axes are defined by the vectors e1((0,0),(0,1)), e2((0,0),(1,0)) and e3 = e1 x e2.


问:
How to ingegrate sabre booking SOAP API into React Native
We are planning to use sabre SOAP api for booking
https://beta.developer.sabre.com/docs/soap_apis/air/book/book_air_segment

as its not available for REST. we are using react native to build our app and want to use above API. we had tried to integrate SOAP api but it doesn't work.

Is there any one out there who have used SOAP api to book the flight or any other SOAP api with react native? is there REST api available for booking the flight?

any information will be really helpful

thank you

答:
When you want to integrate a SOAP web service ( or any other ) you should separate concerns to different application layer. To make an example my approach would by

Create a library that will be your simplified interface to the web service API, for example if the booking procedure is a subsequential call of remote services your library interface would be just $myClient->book($request).
Internally, the library will do all the calls that are necessary to make the job done.

Create you application backend and have that library as dependency: in the application layer you will store in your database all the data you need, manage log, exceptions etc.
This can be you JSON/REST API.

Frontend application: this will just render the data given by your application backend, the data supplied by your backend will be as simple as possible, ready to be rendered in a fancy layout.
For the frontend you can use any technology you like, Angular, React, Cordova etc..

Hope it helps

Cheers


问:
How to output a pattern without including the beginning of the pattern?
I am trying to extract two characters from CLOB in Orcale. For example, the CLOB column looks like this:

"rateArea":"KCMO","state":"MO","addressComponent":null,"msag":null

I wrote:

```<code> SELECT
 REGEXP_SUBSTR( ORD_DETAILS,  'state":"+\w\w' ) state
 from order_log
</code>```

This gives me the output - state":"MO

I just want MO as my output.

Can you please suggest the regex code for the desired output?

答:
Your data is very similar to JSON, and if your Oracle database version is 12c or higher, you can try using the JSON_TABLE function:

```<code>SELECT jt.state
FROM order_log ol
CROSS JOIN json_table(
  '{'||ol.ord_details||'}', '$'
  COLUMNS (
    rate_area VARCHAR2(30) PATH '$.rateArea',
    state VARCHAR2(5) PATH '$.state',
    addr_comp VARCHAR2(100) PATH '$.addressComponent',
    msag VARCHAR2(100) PATH '$.msag'
  )
) jt;
</code>```

Output:

```<code>STATE
-----
MO
</code>```

Test it online with db<>fiddle.

Body:
I am trying to extract two characters from CLOB in Orcale. For example, the CLOB column looks like this:

"rateArea":"KCMO","state":"MO","addressComponent":null,"msag":null

I wrote:

 SELECT
 REGEXP_SUBSTR( ORD_DETAILS,  'state":"+\w\w' ) state
 from order_log

This gives me the output - state":"MO

I just want MO as my output.

Can you please suggest the regex code for the desired output?

Body:
Your data is very similar to JSON, and if your Oracle database version is 12c or higher, you can try using the JSON_TABLE function:

SELECT jt.state
FROM order_log ol
CROSS JOIN json_table(
  '{'||ol.ord_details||'}', '$'
  COLUMNS (
    rate_area VARCHAR2(30) PATH '$.rateArea',
    state VARCHAR2(5) PATH '$.state',
    addr_comp VARCHAR2(100) PATH '$.addressComponent',
    msag VARCHAR2(100) PATH '$.msag'
  )
) jt;

Output:

STATE
-----
MO

Test it online with db<>fiddle.


问:
Python using multiprocessing on PostgreSQL queries reduce runtime
I have the following code in Python, which will execute 5 queries in a row. The average runtime per query is around 181.1 seconds (~3 minutes), and the total runtime for all 5 queries is 905.4 seconds (~15 minutes). Eventually, after loading the data into DataFrames, I am going to perform ETL work (mostly looking for errors, data quality issues, and inconsistencies), but before that I want to try to leverage multiprocessing to shave off on runtime. I am not familiar with multiprocessing in Python, so I have been reading about different methodologies (Queue vs Pooling, etc.). I am curious which method would run best for this workflow, and how would I implement this? Ideally, a multiprocessed-translated version of this code, or a guide to get there would be great.

Thank you.

EDIT: in case I wasn’t clear, I want to run all 5 queries concurrently. Something that may be an issue is appending each DataFrame to the list concurrently, so if I need to I am willing to forgo that.

```<code>import pandas as pd
import psycopg2
import time
import os

host = os.environ["DBHOST"]
user = os.environ["DBUSER"]
pass = os.environ["DBPWD"]

db_conn = psycopg2.connect("host='{}' port={} dbname='{}' user={} password={}".format(host,
                                                                                port#,
                                                                                "db_name",
                                                                                user,
                                                                                pass))
query_load = [("SELECT column_name_1, COUNT(*) "
            "FROM schema.table "
            "GROUP BY column_name_1 "
            "ORDER BY column_name_1 ASC"),

             ("SELECT column_name_2, COUNT(*) "
            "FROM schema.table "
            "GROUP BY column_name_2 "
            "ORDER BY column_name_2 ASC"),

             ("SELECT column_name_3, COUNT(*) "
            "FROM schema.table "
            "GROUP BY column_name_3 "
            "ORDER BY column_name_3 ASC"),

             ("SELECT column_name_4, COUNT(*) "
            "FROM schema.table "
            "GROUP BY column_name_4 "
            "ORDER BY column_name_4 ASC"),

            ("SELECT column_name_5, COUNT(*) "
            "FROM schema.table "
            "GROUP BY column_name_5 "
            "ORDER BY column_name_5 ASC")]
start_time = time.time()
data_load = []
for queries in query_load:
    data_load.append(pd.read_sql(queries, db_conn))
elapsed_time = time.time() - start_time
print ("Job finished in {} seconds".format(elapsed_time))
</code>```

答:
Since you already have a collection of queries, we can organise a function to take one at a time, but by using Pool.map, they can run concurrently:

```<code>from multiprocessing import Pool
import pandas as pd
import time

# define query_load
# define db_conn

def read_sql(query):
    return pd.read_sql(query, db_conn)

if __name__ == '__main__':
    start_time = time.time()
    with Pool(5) as p:
        data_load = p.map(read_sql, query_load)
    elapsed_time = time.time() - start_time
    print ("Job finished in {} seconds".format(elapsed_time))
    # carry on re-processing data_load
</code>```

Now, I'm assuming that db_conn will allow concurrent requests.

Also note that p.map does the organising of taking results and loading them into a list for you.

Body:
I have the following code in Python, which will execute 5 queries in a row. The average runtime per query is around 181.1 seconds (~3 minutes), and the total runtime for all 5 queries is 905.4 seconds (~15 minutes). Eventually, after loading the data into DataFrames, I am going to perform ETL work (mostly looking for errors, data quality issues, and inconsistencies), but before that I want to try to leverage multiprocessing to shave off on runtime. I am not familiar with multiprocessing in Python, so I have been reading about different methodologies (Queue vs Pooling, etc.). I am curious which method would run best for this workflow, and how would I implement this? Ideally, a multiprocessed-translated version of this code, or a guide to get there would be great.

Thank you.

EDIT: in case I wasn’t clear, I want to run all 5 queries concurrently. Something that may be an issue is appending each DataFrame to the list concurrently, so if I need to I am willing to forgo that.

import pandas as pd
import psycopg2
import time
import os

host = os.environ["DBHOST"]
user = os.environ["DBUSER"]
pass = os.environ["DBPWD"]

db_conn = psycopg2.connect("host='{}' port={} dbname='{}' user={} password={}".format(host,
                                                                                port#,
                                                                                "db_name",
                                                                                user,
                                                                                pass))
query_load = [("SELECT column_name_1, COUNT(*) "
            "FROM schema.table "
            "GROUP BY column_name_1 "
            "ORDER BY column_name_1 ASC"),

             ("SELECT column_name_2, COUNT(*) "
            "FROM schema.table "
            "GROUP BY column_name_2 "
            "ORDER BY column_name_2 ASC"),

             ("SELECT column_name_3, COUNT(*) "
            "FROM schema.table "
            "GROUP BY column_name_3 "
            "ORDER BY column_name_3 ASC"),

             ("SELECT column_name_4, COUNT(*) "
            "FROM schema.table "
            "GROUP BY column_name_4 "
            "ORDER BY column_name_4 ASC"),

            ("SELECT column_name_5, COUNT(*) "
            "FROM schema.table "
            "GROUP BY column_name_5 "
            "ORDER BY column_name_5 ASC")]
start_time = time.time()
data_load = []
for queries in query_load:
    data_load.append(pd.read_sql(queries, db_conn))
elapsed_time = time.time() - start_time
print ("Job finished in {} seconds".format(elapsed_time))

Body:
Since you already have a collection of queries, we can organise a function to take one at a time, but by using Pool.map, they can run concurrently:

from multiprocessing import Pool
import pandas as pd
import time

# define query_load
# define db_conn

def read_sql(query):
    return pd.read_sql(query, db_conn)

if __name__ == '__main__':
    start_time = time.time()
    with Pool(5) as p:
        data_load = p.map(read_sql, query_load)
    elapsed_time = time.time() - start_time
    print ("Job finished in {} seconds".format(elapsed_time))
    # carry on re-processing data_load

Now, I'm assuming that db_conn will allow concurrent requests.

Also note that p.map does the organising of taking results and loading them into a list for you.


问:
Getting first day of the month, is outputting the wrong first day of the month
I want to display the first day of the month in 'day of the week' format.
For example, The below code should select the month of August and say the day of the week 01 falls on which is Thursday, but for some reason, the below code outputs Friday which is wrong, on some months such as May it correctly says Wednesday.

```<code>$monthNumber = 3;
$base = strtotime(date('Y-m',time()) . '-01 00:00:01');
$dateTest = date("Ym" . 1, strtotime($monthNumber . " month", $base));
$unixTimestamp = strtotime($dateTest, $base);
echo date("l", $unixTimestamp);
</code>```

Does anyone have any ideas to make it show the correct day?

$base fixes a bug with it not showing the correct month.

答:
You have to use date() at first:

```<code>$base = date('Y-m',time()) . '-01 00:00:00';
</code>```

And dont have to set the first second :)

Body:
I want to display the first day of the month in 'day of the week' format.
For example, The below code should select the month of August and say the day of the week 01 falls on which is Thursday, but for some reason, the below code outputs Friday which is wrong, on some months such as May it correctly says Wednesday.

$monthNumber = 3;
$base = strtotime(date('Y-m',time()) . '-01 00:00:01');
$dateTest = date("Ym" . 1, strtotime($monthNumber . " month", $base));
$unixTimestamp = strtotime($dateTest, $base);
echo date("l", $unixTimestamp);

Does anyone have any ideas to make it show the correct day?

$base fixes a bug with it not showing the correct month.

Body:
You have to use date() at first:

$base = date('Y-m',time()) . '-01 00:00:00';

And dont have to set the first second :)


问:
Converting VB6 varables to C#
I am converting old VB6 code and am having an issue with these constants:

VB6 code:

```<code>Private Const GENERIC_WRITE = &H40000000
Private Const GENERIC_READ = &H80000000
</code>```

C# code:

```<code>private const int GENERIC_WRITE = 0x40000000;
private const uint GENERIC_READ = 0x80000000;
</code>```

Why does the second line have to be uint?
If I do it as int, it gives me an error?

答:
The primitive data types prefixed with "u" are unsigned versions with the same bit sizes.
Effectively, this means they cannot store negative numbers, but on the other hand they can store positive numbers twice as large as their signed counterparts.</p>

Title: Converting VB6 varables to C#

Body:
I am converting old VB6 code and am having an issue with these constants:

VB6 code:

Private Const GENERIC_WRITE = &H40000000
Private Const GENERIC_READ = &H80000000

C# code:

private const int GENERIC_WRITE = 0x40000000;
private const uint GENERIC_READ = 0x80000000;

Why does the second line have to be uint?
If I do it as int, it gives me an error?


问:
Grep and inserting a string
I have a text file with a bunch of file paths such as -

```<code>web/index.erb

web/contact.erb

...
</code>```

etc. I need to append before the

```<code></head>
</code>```

a line of code, to every single file, I'm trying to figure out how to do this without opening each file of course. I've heard sed, but I've never used it before..was hoping there would be a grep command maybe?

Thanks

答:
```<code>while read f ; do
    sed -i '/<\/head>/i*iamthelineofcode*' "$f"
done <iamthefileoffiles.list
</code>```

or

```<code>sed -i '/<\/head>/i*iamthelineofcode*' $(cat iamthefileoffiles.list)
</code>```

Title: Grep and inserting a string

Body:
I have a text file with a bunch of file paths such as -

web/index.erb

web/contact.erb

...

etc. I need to append before the

a line of code, to every single file, I'm trying to figure out how to do this without opening each file of course. I've heard sed, but I've never used it before..was hoping there would be a grep command maybe?

Thanks

Body:
while read f ; do
    sed -i '/<\/head>/i*iamthelineofcode*' "$f"
done <iamthefileoffiles.list

or

sed -i '/<\/head>/i*iamthelineofcode*' $(cat iamthefileoffiles.list)


问:
How to run one-off Docker containers locally (triggered from within a container)
When hosting applications on Heroku I often trigger one-off dynos via the Heroku API from within the code to do heavy lifting in the background. I recently set up some stacks on AWS and followed a similar pattern by using AWS ECS run task.

I am not using long running queue workers for this as hardware resources vary heavily according to the specific task and usually the workload occurs in peaks.

For local development, I usually skipped this topic by either executing the background tasks within the running container or triggering the background command manually from the console. What would be a good approach for running one-off containers locally?

答:
You can simply call ECS RunTask API call from inside the container.

All you need is to setup ECS Task role to have runtask permissions and to have either aws cli or any aws sdk in container to call runtask call.


问:
How to show Bing map layers with OpenLayers
I want to show the Bing map layers on the HTML page using OpenLayers. I've got the Bing API too, but the map is not shown. This is the code I have downloaded and changed. Is my API wrong? I got the API recently from the site.</p>

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Show OSM map</title>
   <link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/css/ol.css" type="text/css">
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
    <style>
      html, body {
        height: 100%;
        width: 100%;
    padding: 0px;
    margin: 0px;
      }
      .map {
        height: 90%;
        width: 100%;
      }
    </style>
    <script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
  </head>
  <body>
    <div id="map" class="map" "></div>
    <div>
    <select id="layer-select">
       <option value="Aerial">Aerial</option>
       <option value="AerialWithLabels" selected>Aerial with labels</option>
       <option value="Road">Road (static)</option>
       <option value="RoadOnDemand">Road (dynamic)</option>
       <option value="collinsBart">Collins Bart</option>
       <option value="ordnanceSurvey">Ordnance Survey</option>
     </select>
    </div>
    <script>
     var styles = [
        'Road',
        'RoadOnDemand',
        'Aerial',
        'AerialWithLabels',
        'collinsBart',
        'ordnanceSurvey'
      ];
      var layers = [];
      var i, ii;
      for (i = 0, ii = styles.length; i < ii; ++i) {
        layers.push(new ol.layers.TileLayer({
          visible: false,
          preload: Infinity,
          source: new ol.source.BingMaps({
            key: '------------',
            imagerySet: styles[i]
            // use maxZoom 19 to see stretched tiles instead of the BingMaps
            // "no photos at this zoom level" tiles
            maxZoom: 19
          })
        }));
      }
      var map = new ol.Map({
        layers: layers,
        // Improve user experience by loading tiles while dragging/zooming. Will make
        // zooming choppy on mobile or slow devices.
        loadTilesWhileInteracting: true,
        target: 'map',
        view: new ol.View({
          center: [-6655.5402445057125, 6709968.258934638],
          zoom: 13
        })
      });

      var select = document.getElementById('layer-select');
      function onChange() {
        var style = select.value;
        for (var i = 0, ii = layers.length; i < ii; ++i) {
          layers[i].setVisible(styles[i] === style);
        }
      }
      select.addEventListener('change', onChange);
      onChange();
    </script>

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

答:
There are two syntax errors in that code

```<code>    layers.push(new ol.layers.TileLayer({
</code>```

should be

```<code>    layers.push(new ol.layer.Tile({
</code>```

and

```<code>        imagerySet: styles[i]
</code>```

needs a comma because it is followed by maxZoom

```<code>        imagerySet: styles[i],
</code>```

Also Collins Bart os no longer supported, but there is a new Road dark style available

```<code><select id="layer-select">
   <option value="Aerial">Aerial</option>
   <option value="AerialWithLabels" selected>Aerial with labels</option>
   <option value="Road">Road (static)</option>
   <option value="RoadOnDemand">Road (dynamic)</option>
   <option value="CanvasDark">Road dark</option>
   <option value="ordnanceSurvey">Ordnance Survey</option>
 </select>
</div>
<script>
 var styles = [
    'Road',
    'RoadOnDemand',
    'Aerial',
    'AerialWithLabels',
    'CanvasDark',
    'ordnanceSurvey'
  ];
</code>```

Body:
I want to show the Bing map layers on the HTML page using OpenLayers. I've got the Bing API too, but the map is not shown. This is the code I have downloaded and changed. Is my API wrong? I got the API recently from the site.

<!DOCTYPE html>

    <title>Show OSM map</title>
   <link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/css/ol.css" type="text/css">

    <select id="layer-select">
       <option value="Aerial">Aerial</option>
       <option value="AerialWithLabels" selected>Aerial with labels</option>
       <option value="Road">Road (static)</option>
       <option value="RoadOnDemand">Road (dynamic)</option>
       <option value="collinsBart">Collins Bart</option>
       <option value="ordnanceSurvey">Ordnance Survey</option>
     </select>

Body:
There are two syntax errors in that code

    layers.push(new ol.layers.TileLayer({

should be

    layers.push(new ol.layer.Tile({

and

        imagerySet: styles[i]

needs a comma because it is followed by maxZoom

        imagerySet: styles[i],

Also Collins Bart os no longer supported, but there is a new Road dark style available

<select id="layer-select">
   <option value="Aerial">Aerial</option>
   <option value="AerialWithLabels" selected>Aerial with labels</option>
   <option value="Road">Road (static)</option>
   <option value="RoadOnDemand">Road (dynamic)</option>
   <option value="CanvasDark">Road dark</option>
   <option value="ordnanceSurvey">Ordnance Survey</option>
 </select>
</div>
<script>
 var styles = [
    'Road',
    'RoadOnDemand',
    'Aerial',
    'AerialWithLabels',
    'CanvasDark',
    'ordnanceSurvey'
  ];


问:
Do single letters in R have a length of 2?
Again I'm confounded by my datacamp R tutorial. A video presentation tries to explain the  difference between vapply and sapply, and presents the following code and outputs:

```<code>first_and_last <-function(name) {
  name <- gsub(" ", "", name)
  letters <- strsplit(name, split = "")[[1]]
  return(c(first = min(letters), last = max(letters))))
}

sapply(cities, first_and_last)

New York Paris London Tokyo Rio de Janeiro Cape Town
first   "e"  "a"   "d"    "k"   "a"            "a"
last    "y"  "s"   "o"    "y"   "R"        "w"

vapply(cities, first_and_last, character(2))

New York Paris London Tokyo Rio de Janeiro Cape Town
first   "e"  "a"   "d"    "k"   "a"            "a"
last    "y"  "s"   "o"    "y"   "R"        "w"
</code>```

As we can see the output is identical. I am told that's because the length of the character vector in the vapply function is set manually to 2 and if it was set to 1 we would encounter an error.

I'm not sure I understand, these are single letters so why would we need a character vector with length 2?

答:
When you specify the return shape in vapply (in your case a character vector of length 2), it needs to match the return type of the function you are calling (first_and_last).

It actually doesn't matter if they are single letters or very long words, what matters is that first_and_last is returning a character vector with two elements in it.

Body:
Again I'm confounded by my datacamp R tutorial. A video presentation tries to explain the  difference between vapply and sapply, and presents the following code and outputs:

first_and_last <-function(name) {
  name <- gsub(" ", "", name)
  letters <- strsplit(name, split = "")[[1]]
  return(c(first = min(letters), last = max(letters))))
}

sapply(cities, first_and_last)

New York Paris London Tokyo Rio de Janeiro Cape Town
first   "e"  "a"   "d"    "k"   "a"            "a"
last    "y"  "s"   "o"    "y"   "R"        "w"

vapply(cities, first_and_last, character(2))

New York Paris London Tokyo Rio de Janeiro Cape Town
first   "e"  "a"   "d"    "k"   "a"            "a"
last    "y"  "s"   "o"    "y"   "R"        "w"

As we can see the output is identical. I am told that's because the length of the character vector in the vapply function is set manually to 2 and if it was set to 1 we would encounter an error.

I'm not sure I understand, these are single letters so why would we need a character vector with length 2?


问:
tried to connect a ModelForm
i am reciving a "value error"
because of "ModelForm has no model class specified."

i tried to check the : models.py forms.py and views.py but all looks pretty good for me

views.py :

```<code>class CreatePostView(LoginRequiredMixin,CreateView):
   login_url='/login/'
   redirect_field_name='Myblog/post_detail.html'
   form_class = PostForm
   model = Post
</code>```

models.py:

```<code>class Post(models.Model):
   author = models.ForeignKey('auth.User',on_delete=models.CASCADE)
   title = models.CharField(max_length=200)
   text = models.TextField()
   created_date = models.DateTimeField(default=timezone.now)
   published_date = models.DateTimeField(blank=True,null=True)
</code>```

forms.py:

```<code>class PostForm(ModelForm):
   class meta:
       model = Post
       fields = ('author','title','text')
</code>```

from app.urls.py
url(r'^post/new/$',views.CreatePostView.as_view(),name='post_new'),

答:
Meta is with an uppercase, according to PEP-8 the names of classes all start with an uppercase. In your form, you should write:

```<code># app/forms.py

class PostForm(ModelForm):

    class <b>Meta</b>:
        model = Post
        fields = ('author','title','text')</code>```

Since you wrote it as <s>meta</s>, Django indeed did not understand what model you were using.

If you however do not write a form with specific items, you can - like @DanielRoseman says, just define this at the CreateView [Django-doc]:

```<code>class CreatePostView(LoginRequiredMixin,CreateView):
    login_url='/login/'
    redirect_field_name='Myblog/post_detail.html'
    model = Post
    <b>fields = ('author', 'title', 'text')</b></code>```

Django can construct a form class through the modelform_factory [Django-doc].

Title: tried to connect a ModelForm

Body:
i am reciving a "value error"
because of "ModelForm has no model class specified."

i tried to check the : models.py forms.py and views.py but all looks pretty good for me

views.py :

class CreatePostView(LoginRequiredMixin,CreateView):
   login_url='/login/'
   redirect_field_name='Myblog/post_detail.html'
   form_class = PostForm
   model = Post

models.py:

class Post(models.Model):
   author = models.ForeignKey('auth.User',on_delete=models.CASCADE)
   title = models.CharField(max_length=200)
   text = models.TextField()
   created_date = models.DateTimeField(default=timezone.now)
   published_date = models.DateTimeField(blank=True,null=True)

forms.py:

class PostForm(ModelForm):
   class meta:
       model = Post
       fields = ('author','title','text')

from app.urls.py
url(r'^post/new/$',views.CreatePostView.as_view(),name='post_new'),

Body:
Meta is with an uppercase, according to PEP-8 the names of classes all start with an uppercase. In your form, you should write:

# app/forms.py

class PostForm(ModelForm):

    class Meta:
        model = Post
        fields = ('author','title','text')

Since you wrote it as <s>meta</s>, Django indeed did not understand what model you were using.

If you however do not write a form with specific items, you can - like @DanielRoseman says, just define this at the CreateView [Django-doc]:

class CreatePostView(LoginRequiredMixin,CreateView):
    login_url='/login/'
    redirect_field_name='Myblog/post_detail.html'
    model = Post
    fields = ('author', 'title', 'text')

Django can construct a form class through the modelform_factory [Django-doc].


问:
Tool for generating a call flow graph [C C++ solaris linux]
I'm quite fond of IDA, but I'm working in Solaris on this project.  I do have a linux machine, and if nothing is in the same league as IDA then I'll convince management to purchase a license for it.

Barring that, I'm looking for alternative suggestions.  Some of the other features in IDA would be handy, but the main thing I need at the moment is a call flow graph generator not based on source code.  If it needs extra output from the build step, that's fine, but some of the libraries I need to look at I don't have source for.

So far, it looks like my best choices are Valgrind's Callgrind, lida, and gprof.  Any further suggestions are welcome.

re: gprof, the GNU compiler set provided to us by Windriver is missing some libraries that would normally be supplied with a GNU compiler to provide (among other things) facilities for profiling.  It's a good solution to the more general problem, but for now I'm opting to try other solutions first.

edit Some of the Rational tools (Purify, Quantify, etc) might also work well for this.  I'm in the same boat as with IDA with that, but I figure someone googling might find the suggestion helpful.

edit2 Valgrind hasn't been ported to solaris/sparc ;p

答: You can generate a call graph with Gprof. It can be visualized with Kprof.</p>


问:
Mean absolute error in TensorFlow without built-in functions
I have to implement a loss function using mean absolute error without calling the built-in function. Is the code below correct? Because my loss value goes from 28.xx to 0.00028 quickly.

Meanwhile, other loss function like RMSE has a more standard loss curve

```<code>loss = tf.reduce_sum(tf.abs(y_pred - Y) / nFeatures)
</code>```

答:
You can implement your own lost function base on MAE formula:

import tensorflow as tf
MAE = tf.reduce_mean(tf.abs(y_true - y_pred))
```

<p>Also you can check customized loss function in this answer</p>

<p>or</p>

<pre class="lang-py prettyprint-override"><code>import numpy as np
MAE = np.average(np.abs(y_true - y_pred), weights=sample_weight, axis=0)
</code>```

or

from tensorflow.python.ops import math_ops
MAE = math_ops.abs(y_true - y_pred)
```

Body:
I have to implement a loss function using mean absolute error without calling the built-in function. Is the code below correct? Because my loss value goes from 28.xx to 0.00028 quickly.

Meanwhile, other loss function like RMSE has a more standard loss curve

loss = tf.reduce_sum(tf.abs(y_pred - Y) / nFeatures)

Body:
You can implement your own lost function base on MAE formula:

import tensorflow as tf
MAE = tf.reduce_mean(tf.abs(y_true - y_pred))

Also you can check customized loss function in this answer

or

import numpy as np
MAE = np.average(np.abs(y_true - y_pred), weights=sample_weight, axis=0)

or

from tensorflow.python.ops import math_ops
MAE = math_ops.abs(y_true - y_pred)


问:
dataframe apply function error when calling function from external py file
dataframe apply function operates differently when I use functions from external .py file as arguments in the apply function.

In jupyter notebook, my code is working well when I define function in the same .ipynb file. However, when I import a function from .py file, I get errors like ("name 'pd' is not defined", 'occurred at index 0').

```<code>import pandas as pd
import ind_assign as ind
def ffi48(x):
    if (3000<=x['sic'] <= 4000):
        ffi48 = 1
    if (4000<x['sic'] <= 5000):
        ffi48 = 2
    return pd.Series({'sic':x['sic'], 'ffi48': ffi48})

d = {'sic': [3725, 4920]}
df = pd.DataFrame(data=d)

df.apply(ffi48, axis=1)
or
df.apply(ind.ffi48, axis=1)
</code>```

df.apply(ffi48, axis=1) works well. However, when I make ind_assign.py file with ffi48 function and call like df.apply(ind.ffi48, axis=1), I got errors such as
("name 'pd' is not defined", 'occurred at index 0').

答:
I just recreated your error. You need to import pandas as pd in the ind_assign.py file as suggested, then save ind_assign.py, but then you also need to restart your kernel within the notebook. After restarting the kernel, it works as expected.

https://support.enthought.com/hc/en-us/articles/204469240-Jupyter-IPython-After-editing-a-module-changes-are-not-effective-without-kernel-restart?mobile_site=true

Body:
dataframe apply function operates differently when I use functions from external .py file as arguments in the apply function.

In jupyter notebook, my code is working well when I define function in the same .ipynb file. However, when I import a function from .py file, I get errors like ("name 'pd' is not defined", 'occurred at index 0').

import pandas as pd
import ind_assign as ind
def ffi48(x):
    if (3000<=x['sic'] <= 4000):
        ffi48 = 1
    if (4000<x['sic'] <= 5000):
        ffi48 = 2
    return pd.Series({'sic':x['sic'], 'ffi48': ffi48})

d = {'sic': [3725, 4920]}
df = pd.DataFrame(data=d)

df.apply(ffi48, axis=1)
or
df.apply(ind.ffi48, axis=1)

df.apply(ffi48, axis=1) works well. However, when I make ind_assign.py file with ffi48 function and call like df.apply(ind.ffi48, axis=1), I got errors such as
("name 'pd' is not defined", 'occurred at index 0').


问:
string editing in ios swift
I am having a string in that I have getting a tag
 and I want to append  ahead of

```<code>let str = "<p>A new week-long event is kicking off soon in <a href="/pokemon-go/" data-ref-id="5000-449545">Pokemon Go</a>. Niantic is holding another Adventure Week beginning Tuesday, June 4, and it'll give players a chance to earn extra rewards, catch some rare Rock-types, and even find a couple of new Shiny Pokemon.</p><p>During Adventure Week, Geodude, Rhyhorn, Omanyte, Aron, Lileep, Anorith, and other Rock Pokemon will appear in the wild much more frequently than normal.</p>"
</code>```

I want this string as:

```<code>let newStr = #"<b><p>A new week-long event is kicking off soon in <a href="/pokemon-go/" data-ref-id="5000-449545">Pokemon Go</a>. Niantic is holding another Adventure Week beginning Tuesday, June 4, and it'll give players a chance to earn extra rewards, catch some rare Rock-types, and even find a couple of new Shiny Pokemon.</p></b><p>During Adventure Week, Geodude, Rhyhorn, Omanyte, Aron, Lileep, Anorith, and other Rock Pokemon will appear in the wild much more frequently than normal.</p>"#
</code>```

答:
Updated due comment (just first tag) -> See history if you want simpler edition

```<code>extension String {

    enum TagRange {
        case first
        case last
        case any
    }

    func addingHTMLTag(_ wrapperTag: String, around tagToWrap: String, witchIs tagRange: TagRange = .any) -> String {

        let range: NSRange?
        let regxPattern = "<\(tagToWrap)>(.+?)</\(tagToWrap)>"
        let regx = try! NSRegularExpression(pattern: regxPattern, options: [])
        let allRange = NSRange(location: 0, length: self.utf8.count)

        switch tagRange {
        case .first: range = regx.rangeOfFirstMatch(in: self, options: [], range: allRange)
        case .last: range = regx.matches(in: self, options: [], range: allRange).last?.range
        case .any: range = nil
        }

        if let range = range {
            let openTagged = (self as NSString).replacingOccurrences(of: "<\(tagToWrap)>", with: "<\(wrapperTag)><\(tagToWrap)>", range: range)

            let offsetRange = NSRange(location: range.location + (wrapperTag.count+2) , length: range.length)

            return (openTagged as NSString).replacingOccurrences(of: "</\(tagToWrap)>", with: "</\(tagToWrap)></\(wrapperTag)>", range: offsetRange)
        } else {
            let openTagged = replacingOccurrences(of: "<\(tagToWrap)>", with: "<\(wrapperTag)><\(tagToWrap)>")
            return openTagged.replacingOccurrences(of: "</\(tagToWrap)>", with: "</\(tagToWrap)></\(wrapperTag)>")
        }
    }
}
</code>```

usage:

```<code>let newStr = str.addingHTMLTag("b", around: "p", witchIs: .first)
</code>```

This method also checks if the tag you want to wrap around is valid. Maybe there is no closing tag or no opening tag or invalid opening and closing tags order. or maybe there is a
 in the text itself! that you don't want to wrap.

Title: string editing in ios swift

Body:
I am having a string in that I have getting a tag
 and I want to append  ahead of

let str = "
A new week-long event is kicking off soon in Pokemon Go. Niantic is holding another Adventure Week beginning Tuesday, June 4, and it'll give players a chance to earn extra rewards, catch some rare Rock-types, and even find a couple of new Shiny Pokemon.

During Adventure Week, Geodude, Rhyhorn, Omanyte, Aron, Lileep, Anorith, and other Rock Pokemon will appear in the wild much more frequently than normal.
"

I want this string as:

let newStr = #"
A new week-long event is kicking off soon in Pokemon Go. Niantic is holding another Adventure Week beginning Tuesday, June 4, and it'll give players a chance to earn extra rewards, catch some rare Rock-types, and even find a couple of new Shiny Pokemon.

During Adventure Week, Geodude, Rhyhorn, Omanyte, Aron, Lileep, Anorith, and other Rock Pokemon will appear in the wild much more frequently than normal.
"#

Body:
Updated due comment (just first tag) -> See history if you want simpler edition

extension String {

    enum TagRange {
        case first
        case last
        case any
    }

    func addingHTMLTag(_ wrapperTag: String, around tagToWrap: String, witchIs tagRange: TagRange = .any) -> String {

        let range: NSRange?
        let regxPattern = "<\(tagToWrap)>(.+?)</\(tagToWrap)>"
        let regx = try! NSRegularExpression(pattern: regxPattern, options: [])
        let allRange = NSRange(location: 0, length: self.utf8.count)

        switch tagRange {
        case .first: range = regx.rangeOfFirstMatch(in: self, options: [], range: allRange)
        case .last: range = regx.matches(in: self, options: [], range: allRange).last?.range
        case .any: range = nil
        }

        if let range = range {
            let openTagged = (self as NSString).replacingOccurrences(of: "<\(tagToWrap)>", with: "<\(wrapperTag)><\(tagToWrap)>", range: range)

            let offsetRange = NSRange(location: range.location + (wrapperTag.count+2) , length: range.length)

            return (openTagged as NSString).replacingOccurrences(of: "</\(tagToWrap)>", with: "</\(tagToWrap)></\(wrapperTag)>", range: offsetRange)
        } else {
            let openTagged = replacingOccurrences(of: "<\(tagToWrap)>", with: "<\(wrapperTag)><\(tagToWrap)>")
            return openTagged.replacingOccurrences(of: "</\(tagToWrap)>", with: "</\(tagToWrap)></\(wrapperTag)>")
        }
    }
}

usage:

let newStr = str.addingHTMLTag("b", around: "p", witchIs: .first)

This method also checks if the tag you want to wrap around is valid. Maybe there is no closing tag or no opening tag or invalid opening and closing tags order. or maybe there is a<p> in the text itself! that you don't want to wrap.


问:
Cube's awkward shape when rendered on a small screen
I'm stacking a series of small divs to show a series of statistics. The problem is to display them correctly on a mobile phone. Can you suggest an alternative for me? It's worth noticing that this design came from an admin template.

This is what you'd see on a bigger screen:

And the following is the way the cubes are displayed while using a cellphone:

```<code><div class="col-2">
            <div class="bg-success p-10 text-white text-center">
                <i class="fas fa-warehouse m-b-5 font-16"></i>
                <h5 class="m-b-0 m-t-5">414</h5>
                <small class="font-light">Bodega stock</small>
            </div>
    </div>
</code>```

I've read about responsive typography but I'm not sure how should I proceed.

答:
In my opinion you have two options :

Display the 'total disponible' and 'total reversa' side by side on big screen, but one under each other on responsive, which can be easily done using flexbox

Like a fellow said above, display the green, black and yellow divs in column, with width set to 100%

Body:
I'm stacking a series of small divs to show a series of statistics. The problem is to display them correctly on a mobile phone. Can you suggest an alternative for me? It's worth noticing that this design came from an admin template.

This is what you'd see on a bigger screen:

And the following is the way the cubes are displayed while using a cellphone:

414

                Bodega stock

I've read about responsive typography but I'm not sure how should I proceed.


问:
How to include "refetchQueries" option into React Apollo Query with Typescript?
I am using typescript in a React project using Apollo client, I have a simple update customer form that requires a mutation inside of a Query for getting the Customer data to show from his/her ID, I have created (as per Apollo Typescript documentation) a specialized query object for this,

//---------------------------------------------------------------------------------
// Imports Section (React/Apollo Libs)
//---------------------------------------------------------------------------------
import { gql }                  from 'apollo-boost';
import { Query }                from 'react-apollo'

import { getCustomerById }            from '../../typeDefs/operations/getCustomerById'
import { getCustomerByIdVariables }   from '../../typeDefs/operations/getCustomerById'

//---------------------------------------------------------------------------------
// GQL Query: Customers
//---------------------------------------------------------------------------------
export const Q_GET_CUSTOMER_BY_ID = gql`
    query getCustomerById($id: ID) {
        getCustomer(id: $id)
        {
            first_name
            last_name
            company
            emails {
                email
            }
            age
            type
        }
    }
`;

//---------------------------------------------------------------------------------
// Query Class: Customers
//---------------------------------------------------------------------------------
export class QueryGetCustomerById extends Query<getCustomerById, getCustomerByIdVariables> { }
```

Everything works as expected... until entering the "Edit Customer" view again after the change, where the data seems unchanged, (this obviously because of Apollo Cache), when trying to use the "refetchQuery" option in the <QueryGetCustomerById> Typescript sends a weird error to my VSCode window.

Reading the Apollo Typescript documentation (very lacking IMHO) I find that there is a reference in its second example to a ChildProps object, now I am not sure if I should declare or create another interface for the QueryGetCustomerById to take together with the Response and Variables ones. Quite honestly I am totally confused at this point, if someone has tried this or knows how to implement it please help. Thanks a lot.

P.S. Using the more generic version <Query<getCustomerById, getCustomerByIdVariables> ... doesn't work either.

答:
My bad...

Doing a more careful revision in the Apollo Docs site, I found the <Query> tag can pass a 'refetch()' method to the query in the returning arrow function, which in turn can be executed after the mutation function. I just tried it and it worked great!  Here is the code for if someone ever falls into the same issue and sees this page..

               <QueryGetCustomerById
                    query={Q_GET_CUSTOMER_BY_ID}
                    variables={{ id: id }}
                >
                    {({ loading, error, data, refetch }) => {
                        if (loading)
                        {
                            return "Put something that looks good for loading here..."
                        }
                        if (error)
                        {
                            return `Error: ${error.message}`
                        }
                        if (data && data.getCustomer)
                        {
                            this.setCustomer(id, data.getCustomer as CustomerInput)
                        }
                        return (

                                <MutationUpdateCustomer
                                    mutation={M_UPDATE_CUSTOMER}
                                    onCompleted={() => this.props.history.push('/')}
                                >
                                {
                                    (updateCustomer) => {
                                        return (
                                            <form name="frmEditCustomer"
                                                className="col-md-8 m-3"
                                                onSubmit={e => this.frmEditCustomer_submit(e, updateCustomer, refetch)}
                                                onChange={e => this.frmEditCustomer_change(e)}
                                            >
...
```

<p>refetch() is sent as another parameter in the form_submit() eventhandler, so it can be later executed...</p>

<pre class="lang-js prettyprint-override"><code>            try
            {
                await updateCustomer({
                    variables: { input }
                })

                await refetch()

                Swal.fire(
                    'Update Customer',
                    'Customer data has been successfully saved.',
                    'success'
                )
            }
            catch (error)
            {
...
</code>```

The lesson today for me has been not to believe any blog post I find in the web without checking the official documentation. I hope this post may be useful to someone.

Body:
I am using typescript in a React project using Apollo client, I have a simple update customer form that requires a mutation inside of a Query for getting the Customer data to show from his/her ID, I have created (as per Apollo Typescript documentation) a specialized query object for this,

//---------------------------------------------------------------------------------
// Imports Section (React/Apollo Libs)
//---------------------------------------------------------------------------------
import { gql }                  from 'apollo-boost';
import { Query }                from 'react-apollo'

import { getCustomerById }            from '../../typeDefs/operations/getCustomerById'
import { getCustomerByIdVariables }   from '../../typeDefs/operations/getCustomerById'

//---------------------------------------------------------------------------------
// GQL Query: Customers
//---------------------------------------------------------------------------------
export const Q_GET_CUSTOMER_BY_ID = gql`
    query getCustomerById($id: ID) {
        getCustomer(id: $id)
        {
            first_name
            last_name
            company
            emails {
                email
            }
            age
            type
        }
    }
`;

//---------------------------------------------------------------------------------
// Query Class: Customers
//---------------------------------------------------------------------------------
export class QueryGetCustomerById extends Query<getCustomerById, getCustomerByIdVariables> { }

Everything works as expected... until entering the "Edit Customer" view again after the change, where the data seems unchanged, (this obviously because of Apollo Cache), when trying to use the "refetchQuery" option in the <QueryGetCustomerById> Typescript sends a weird error to my VSCode window.

Reading the Apollo Typescript documentation (very lacking IMHO) I find that there is a reference in its second example to a ChildProps object, now I am not sure if I should declare or create another interface for the QueryGetCustomerById to take together with the Response and Variables ones. Quite honestly I am totally confused at this point, if someone has tried this or knows how to implement it please help. Thanks a lot.

P.S. Using the more generic version <Query<getCustomerById, getCustomerByIdVariables> ... doesn't work either.

Body:
My bad...

Doing a more careful revision in the Apollo Docs site, I found the <Query> tag can pass a 'refetch()' method to the query in the returning arrow function, which in turn can be executed after the mutation function. I just tried it and it worked great!  Here is the code for if someone ever falls into the same issue and sees this page..

               <QueryGetCustomerById
                    query={Q_GET_CUSTOMER_BY_ID}
                    variables={{ id: id }}
                >
                    {({ loading, error, data, refetch }) => {
                        if (loading)
                        {
                            return "Put something that looks good for loading here..."
                        }
                        if (error)
                        {
                            return `Error: ${error.message}`
                        }
                        if (data && data.getCustomer)
                        {
                            this.setCustomer(id, data.getCustomer as CustomerInput)
                        }
                        return (
                            <div className="row justify-content-center">
                                <MutationUpdateCustomer
                                    mutation={M_UPDATE_CUSTOMER}
                                    onCompleted={() => this.props.history.push('/')}
                                >
                                {
                                    (updateCustomer) => {
                                        return (
                                            <form name="frmEditCustomer"
                                                className="col-md-8 m-3"
                                                onSubmit={e => this.frmEditCustomer_submit(e, updateCustomer, refetch)}
                                                onChange={e => this.frmEditCustomer_change(e)}
                                            >
...

refetch() is sent as another parameter in the form_submit() eventhandler, so it can be later executed...

            try
            {
                await updateCustomer({
                    variables: { input }
                })

                await refetch()

                Swal.fire(
                    'Update Customer',
                    'Customer data has been successfully saved.',
                    'success'
                )
            }
            catch (error)
            {
...

The lesson today for me has been not to believe any blog post I find in the web without checking the official documentation. I hope this post may be useful to someone.


问:
MSBuildWorkspace.OpenSolutionAsync(solutionPath) fails to compile because of processor architecture mismatches
In Visual Studio 2017 I created a Stand-Alone Code Analysis Tool project targeting 4.6.2.  I used the templated code as-is except that I specified the .sln file for the workspace.OpenSolutionAsync() call.

The solution I am attempting to compile with this Roslyn method contains both projects where Platform=Any CPU, and projects where Platform=x64.  The solution compiles fine in VS2017 when set to Mixed Platforms.

However, the OpenSolutionAsync() call generates several of these compile errors:

Msbuild failed when processing the file 'C:\MyProj.csproj' with message: C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets: (2110, 5): There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "C:\MyUnmanagedLibrary.dll", "x86". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.

Why is it complaining about x86 when the MyUnmanagedLibrary project has been set to build using Platform=x64 in the Configuration Manager?  How do I resolve this?  This code was working fine one day ago and to the best of my knowledge nothing has changed except that I copied code to a different directory on my PC.

答: The cause of this behavior was that some of my projects had an output path of bin\Debug\, and others had an output path of bin\x64\Debug.  However, the build process performed when you call OpenSolutionAsync() appears to assume bin\Debug.  It was finding old x86 versions of DLLs in bin\Debug\ folders instead of looking at the DLLs in bin\64\Debug\ folders.  Once I changed all the projects' output paths to bin\Debug\, the OpenSolutionAsync() process worked fine.</p>


问:
Google cloud storage Interoperability with S3 interface failed with SignatureDoesnotmatch
Basically, i try to test GET call to access the bucket ACL by HTTPS url using Developer Keys from S3 browser. Here is the url:
https://mybucket1.storage.googleapis.com/?acl

But I am getting following error:

```<code>SignatureDoesNotMatch: The request signature we calculated does not match the signature you provided.
Check your Google secret key and signing method. TaskID: 108
</code>```

I just following the simple migration process from S3 to GCS found here but I am still facing issues. Can any one of you explain why the above steps are not working with S3 browser? The above link says it will work. To make it work, should I change any HTTP/custom headers here?

Below is my GET call

```<code>GET /?acl HTTP/1.1

 Host: mybucket1.storage.googleapis.com

 User-Agent: curl/7.55.1

 Accept: */*

 Authorization: AWS4-HMAC-SHA256
Credential=GOOGCMZOMXVFOS2EJ4PUP7YR/20190531/us-east1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=5e3c9d4df679b0ea847ff2216842d34ea43c1366e67d6d36b338e59b3c515f73

 x-amz-content-sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

 x-amz-date: 20190531T042146Z
</code>```

答: In your call you still using the AWS keys, you need to replace your Authorization header according this doc Authenticating in a simple migration scenario</p>

Body:
Basically, i try to test GET call to access the bucket ACL by HTTPS url using Developer Keys from S3 browser. Here is the url:
https://mybucket1.storage.googleapis.com/?acl

But I am getting following error:

SignatureDoesNotMatch: The request signature we calculated does not match the signature you provided.
Check your Google secret key and signing method. TaskID: 108

I just following the simple migration process from S3 to GCS found here but I am still facing issues. Can any one of you explain why the above steps are not working with S3 browser? The above link says it will work. To make it work, should I change any HTTP/custom headers here?

Below is my GET call

GET /?acl HTTP/1.1

 Host: mybucket1.storage.googleapis.com

 User-Agent: curl/7.55.1

 Accept: */*

 Authorization: AWS4-HMAC-SHA256
Credential=GOOGCMZOMXVFOS2EJ4PUP7YR/20190531/us-east1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=5e3c9d4df679b0ea847ff2216842d34ea43c1366e67d6d36b338e59b3c515f73

 x-amz-content-sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

 x-amz-date: 20190531T042146Z


问:
Notice: Undefined offset: 2 in
I would like a help, I converted the input string from date to array and if I do not input for example 05/26/2019, all 3 fields did an explode to flip an array, then this error occurs. what can I do?

escola.php

```<code> <form method="POST" class="PesquisarData">
    <h5>Pesquisar Data:</h5>
    <input type="text" id="data" name="data" class="selectData">
    <input type="submit" value="Pesquisar" class="buttonData"><br/>
 </form>

if (!empty($_POST['data'])) {
        $_POST['disciplina'] = "";
        $_POST['professor'] = "";

        $data = explode('/', addslashes($_POST['data']));
        $data = $data[2].'-'.$data[1].'-'.$data[0];
        $sqlm = "SELECT * FROM {$pfx}Material WHERE Data LIKE CONCAT('%',?,'%') ORDER BY Data DESC";
        $qrym = $conn->prepare($sqlm);
        $qrym->bindParam(1, $data);
        $qrym->execute() or die('Ocorreu um erro em uma operação do banco de dados: VL0002.2');
}
</code>```

答: Your programming assumes that the user also uses the slash that you explode! You have to check before the sender whether he slashed these 2 - which you require - also enters</p>

Title: Notice: Undefined offset: 2 in

Body:
I would like a help, I converted the input string from date to array and if I do not input for example 05/26/2019, all 3 fields did an explode to flip an array, then this error occurs. what can I do?

escola.php

 <form method="POST" class="PesquisarData">

Pesquisar Data:

    <input type="text" id="data" name="data" class="selectData">
    <input type="submit" value="Pesquisar" class="buttonData">

 </form>

if (!empty($_POST['data'])) {
        $_POST['disciplina'] = "";
        $_POST['professor'] = "";

        $data = explode('/', addslashes($_POST['data']));
        $data = $data[2].'-'.$data[1].'-'.$data[0];
        $sqlm = "SELECT * FROM {$pfx}Material WHERE Data LIKE CONCAT('%',?,'%') ORDER BY Data DESC";
        $qrym = $conn->prepare($sqlm);
        $qrym->bindParam(1, $data);
        $qrym->execute() or die('Ocorreu um erro em uma operação do banco de dados: VL0002.2');
}


问:
How to pass parameters by POST to Azure Functions 2
I want to pass parameters to HttpTrigger Type in Azure Function 2. I see an answer for Azure function 1 in below link.

How to pass parameters by POST to an Azure function?

Answer in the above link is await req.Content.ReadAsAsync<>();
I am looking the similar answer for Azure Function 2.

Here we are using HttpRequest class instead of HttpRequestMessage class.

Below is the code.

```<code>public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            string data = .............;
        }
</code>```

答:
```<code>public static async void Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
            HttpRequest req,
            ILogger log)
        {
            var content = await new StreamReader(req.Body).ReadToEndAsync();

            MyClass myClass = JsonConvert.DeserializeObject<MyClass>(content);

        }
</code>```

You can have a custom class which can be sent in the form of JSON from the post request.

Body:
I want to pass parameters to HttpTrigger Type in Azure Function 2. I see an answer for Azure function 1 in below link.

How to pass parameters by POST to an Azure function?

Answer in the above link is await req.Content.ReadAsAsync<>();
I am looking the similar answer for Azure Function 2.

Here we are using HttpRequest class instead of HttpRequestMessage class.

Below is the code.

public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            string data = .............;
        }

Body:
public static async void Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
            HttpRequest req,
            ILogger log)
        {
            var content = await new StreamReader(req.Body).ReadToEndAsync();

            MyClass myClass = JsonConvert.DeserializeObject<MyClass>(content);

        }

You can have a custom class which can be sent in the form of JSON from the post request.


问:
R: change round brace interval number by subtracting 1 from the value
I have a data which is like this:

```<code>abc <- data.frame( a = c("[100-150)", "[150, 200)"))
</code>```

I want to alter it to make it like this:

```<code>abc <- data.frame(a = c("100-149", "150-199"))
</code>```

I know how to replace the brackets:

```<code>abc$a <- lapply(abc$a, gsub, pattern = "[", replacement = "", fixed = TRUE)
abc$a <- lapply(abc$a, gsub, pattern = "]", replacement = "", fixed = TRUE)
abc$a <- lapply(abc$a, gsub, pattern = ")", replacement = "", fixed = TRUE)

</code>```

It is the subtraction of 1 number from the end that is the problem.

Is there a way to do this?

Please note this is just an example, in reality my data has a column like this which is about 2000 rows.

答:
An option with gsubfn.  We extract the numbers (\\d+) after the - or , convert it to numeric subtract 1 and paste with -

```<code>library(gsubfn)
gsubfn("[-,] ?(\\d+)",  ~ paste0("-", as.numeric(x) - 1) , as.character(abc$a))
#[1] "[100-149)" "[150-199)"
</code>```

Body:
I have a data which is like this:

abc <- data.frame( a = c("[100-150)", "[150, 200)"))

I want to alter it to make it like this:

abc <- data.frame(a = c("100-149", "150-199"))

I know how to replace the brackets:

abc$a <- lapply(abc$a, gsub, pattern = "[", replacement = "", fixed = TRUE)
abc$a <- lapply(abc$a, gsub, pattern = "]", replacement = "", fixed = TRUE)
abc$a <- lapply(abc$a, gsub, pattern = ")", replacement = "", fixed = TRUE)

It is the subtraction of 1 number from the end that is the problem.

Is there a way to do this?

Please note this is just an example, in reality my data has a column like this which is about 2000 rows.

Body:
An option with gsubfn.  We extract the numbers (\\d+) after the - or , convert it to numeric subtract 1 and paste with -

library(gsubfn)
gsubfn("[-,] ?(\\d+)",  ~ paste0("-", as.numeric(x) - 1) , as.character(abc$a))
#[1] "[100-149)" "[150-199)"


问:
Is it safe to use JDBC setString() to store CLOB data type with Oracle database?
I have a need to store a large string into Oracle database the length of which would be at most 10000 bytes. I understand that there is some configuration in Oracle 12c that can increase the 4000 byte limit of varchar2.  But I do not have the option to use that configuration.

So I am inclined to use the CLOB data type.  I have no previous experience in using CLOB.  So I have my concerns.

I saw the following on SO

Java: How to insert CLOB into oracle database

I did not want to use any oracle package to handle the CLOB type.  My question is, is the following safe enough for my purpose?

To store:

```<code>try {
    String myclobstring = "xx ........";
    String sql = "Insert into mytable (clobfield) values (?)";
    Statement stmt = conn.prepareStatement(sql);
    stmt.setString(1, myclobstring);
    .
    .
}
</code>```

To Retrieve:

```<code>try {
    String sql = "select clobfield from mytable";
    stmt = conn.createStatement();
    ResultSet result = stmt.executeQuery(sql);
    String s = result.getString ("clobfield');
    .
    .
}
</code>```

答:
I thought I will post an answer as I did not see an explicit answer.  So far setString()/setString() is storing up to 10K characters into the CLOB field.  I am getting back what I am storing without a problem.

I did see the following related SO post that gives me a bit more confidence.

How to use setClob() in PreparedStatement inJDBC

Body:
I have a need to store a large string into Oracle database the length of which would be at most 10000 bytes. I understand that there is some configuration in Oracle 12c that can increase the 4000 byte limit of varchar2.  But I do not have the option to use that configuration.

So I am inclined to use the CLOB data type.  I have no previous experience in using CLOB.  So I have my concerns.

I saw the following on SO

Java: How to insert CLOB into oracle database

I did not want to use any oracle package to handle the CLOB type.  My question is, is the following safe enough for my purpose?

To store:

try {
    String myclobstring = "xx ........";
    String sql = "Insert into mytable (clobfield) values (?)";
    Statement stmt = conn.prepareStatement(sql);
    stmt.setString(1, myclobstring);
    .
    .
}

To Retrieve:

try {
    String sql = "select clobfield from mytable";
    stmt = conn.createStatement();
    ResultSet result = stmt.executeQuery(sql);
    String s = result.getString ("clobfield');
    .
    .
}


问:
My scanner's nextLine() method isn't working all inputs, how do I fix it?
I'm attempting to write a super simple code where given an integer, the length of that integer (total # of digits) is printed out after being inputted into the console. My code is printing all of the numbers successfully except for the last one. I've encountered this problem frequently and unable to get a solution that works for me.

From a lot of my research so far into people who've answered this question, I've seen that it's typically suggested for a user to add a "nextLine()" statement in order to skip over the /n character at the end of each line, however this has not completely solved the problem for me and I still get a runtime error at the end.

```<code>    int num = Integer.parseInt(q.next()); // First line of input is # of independent digits that follow, each listed on a line by themselves
    q.nextLine();

    while(num > 0)
    {
        System.out.println(q.next().length());
        q.nextLine();
        num--;
    }
</code>```

I seem to be getting an infinite loop at the end as the program never stops running. The code snippet above with input:
5

200

1

3051

....prints out:
3

1

...while there should be a 4 printed at the end for the number of 3051's digits.

答:
Well your program works as expected, but it could be simplified and catch bad input.

```<code>Scanner s = new Scanner(System.in);
final int numberOfIterations = Integer.parseInt(s.next());
for (int i = 0; i < numberOfIterations; i++) {
    System.out.println(s.next().length());
}
s.close();
</code>```

However this will not fail for a String that isn't even a number, so this case could be catched:

```<code>Scanner s = new Scanner(System.in);
try {
    final int numberOfIterations = Integer.parseInt(s.next());
    for (int i = 0; i < numberOfIterations; i++) {
        final String input = s.next();
        Integer.parseInt(input);
        System.out.println(input.length());
    }
    s.close();
} catch (NumberFormatException e) {
    System.out.println("Bad input!");
}
</code>```

There is also mathemical approach to calculating the number of digits using the modulo-operator.

Body:
I'm attempting to write a super simple code where given an integer, the length of that integer (total # of digits) is printed out after being inputted into the console. My code is printing all of the numbers successfully except for the last one. I've encountered this problem frequently and unable to get a solution that works for me.

From a lot of my research so far into people who've answered this question, I've seen that it's typically suggested for a user to add a "nextLine()" statement in order to skip over the /n character at the end of each line, however this has not completely solved the problem for me and I still get a runtime error at the end.

    int num = Integer.parseInt(q.next()); // First line of input is # of independent digits that follow, each listed on a line by themselves
    q.nextLine();

    while(num > 0)
    {
        System.out.println(q.next().length());
        q.nextLine();
        num--;
    }

I seem to be getting an infinite loop at the end as the program never stops running. The code snippet above with input:
5

200

1

3051

....prints out:
3

1

...while there should be a 4 printed at the end for the number of 3051's digits.

Body:
Well your program works as expected, but it could be simplified and catch bad input.

Scanner s = new Scanner(System.in);
final int numberOfIterations = Integer.parseInt(s.next());
for (int i = 0; i < numberOfIterations; i++) {
    System.out.println(s.next().length());
}
s.close();

However this will not fail for a String that isn't even a number, so this case could be catched:

Scanner s = new Scanner(System.in);
try {
    final int numberOfIterations = Integer.parseInt(s.next());
    for (int i = 0; i < numberOfIterations; i++) {
        final String input = s.next();
        Integer.parseInt(input);
        System.out.println(input.length());
    }
    s.close();
} catch (NumberFormatException e) {
    System.out.println("Bad input!");
}

There is also mathemical approach to calculating the number of digits using the modulo-operator.


问:
Problem with scaling drawing objects inside movieclip
So I've got problem with some drawing objects inside movieclip in my flash file... Setting width and height of flash to match browser's w&h got my movie clip to get correct values, but unfortunately drawing objects inside of it are not scaled as movieclip. Those object are just random stripes that got some tween on it acting as somekind of preloader... All graphics are pulled from ai file, so no AS was used to manipulate them, just pure tweening in design mode...

So if my stage w & h are lets say 720 x 50, graphics inside movieclip are 1600 x 900 which match my monitor's resolution.

How can I fix this?

Thx for all help! :)

答: try setting scaleX and scaleY instead of width/height


问:
Right way to use Metal
I have different types of drawings that I do in my app. For example, I draw shapes and grids.

For each type of drawing I have a custom vertex and fragment shader and a class that inherits from MTKViewDelegate. Each of these classes deals with the processing needed to calculate the inputs and a method that looks like this and is called on init:

```<code>private func loadMetal(_ mtkView: MTKView) {
    mtkView.colorPixelFormat = .bgra8Unorm_srgb

    let defaultLibrary = device.makeDefaultLibrary()!
    let vertexProgram = defaultLibrary.makeFunction(name: "grid_vertex")
    let fragmentProgram = defaultLibrary.makeFunction(name: "grid_fragment")

    let pipelineStateDescriptor = MTLRenderPipelineDescriptor()
    pipelineStateDescriptor.vertexFunction = vertexProgram
    pipelineStateDescriptor.fragmentFunction = fragmentProgram
    pipelineStateDescriptor.colorAttachments[0].pixelFormat = mtkView.colorPixelFormat

    pipelineState = try! device.makeRenderPipelineState(descriptor: pipelineStateDescriptor)

    commandQueue = device.makeCommandQueue()

    vertexBuffer = device.makeBuffer(length: bufferCapacity * MemoryLayout<GridVertex>.stride, options: [])

    vertexIndices = device.makeBuffer(length: bufferCapacity * MemoryLayout<UInt16>.size,
                                      options: [])
}
</code>```

So for each pair of vertex/frag shaders I'm creating the pipelineDescriptor and a commandQueue. This works ok, but I was wondering if this is ok or should I reuse the commandQueue/pipeline?

答:
You should reuse the command queue. Except for special cases, there's usually a single command queue per device.

There's no need to reuse the pipeline descriptor object. Those are cheap to create and intended to be transitory. (Pipeline state objects are expensive to create and should be created once and reused, as you appear to be doing.)

See the Transient and Non-transient Objects in Metal section of the Metal Programming Guide.

Title: Right way to use Metal

Body:
I have different types of drawings that I do in my app. For example, I draw shapes and grids.

For each type of drawing I have a custom vertex and fragment shader and a class that inherits from MTKViewDelegate. Each of these classes deals with the processing needed to calculate the inputs and a method that looks like this and is called on init:

private func loadMetal(_ mtkView: MTKView) {
    mtkView.colorPixelFormat = .bgra8Unorm_srgb

    let defaultLibrary = device.makeDefaultLibrary()!
    let vertexProgram = defaultLibrary.makeFunction(name: "grid_vertex")
    let fragmentProgram = defaultLibrary.makeFunction(name: "grid_fragment")

    let pipelineStateDescriptor = MTLRenderPipelineDescriptor()
    pipelineStateDescriptor.vertexFunction = vertexProgram
    pipelineStateDescriptor.fragmentFunction = fragmentProgram
    pipelineStateDescriptor.colorAttachments[0].pixelFormat = mtkView.colorPixelFormat

    pipelineState = try! device.makeRenderPipelineState(descriptor: pipelineStateDescriptor)

    commandQueue = device.makeCommandQueue()

    vertexBuffer = device.makeBuffer(length: bufferCapacity * MemoryLayout<GridVertex>.stride, options: [])

    vertexIndices = device.makeBuffer(length: bufferCapacity * MemoryLayout<UInt16>.size,
                                      options: [])
}

So for each pair of vertex/frag shaders I'm creating the pipelineDescriptor and a commandQueue. This works ok, but I was wondering if this is ok or should I reuse the commandQueue/pipeline?


问:
Type Mismatch - 1st argument to sandbox is not what I expect
I am trying to add subscriptions as I have a dropdown, this helps ensure that the dropdowns automatically close when you click outside of them. On doing so, I had to change the model as well as my update.

This link (will take you to the Elm Bootstrap site) is the dropdown I am working with which is using Bootstrap 4.

Error I am getting

The 1st argument to sandbox is not what I expect:

295|     Browser.sandbox 296|>        { init = initialModel 297|>

  , update = update 298|>        , view = view 299|>        }

This argument is a record of type:

```<code>{ init : ( Model, Cmd Msg )
, update : Msg -> Model -> ( Model, Cmd Msg )
, view : Model -> Html Msg
}
</code>```

But sandbox needs the 1st argument to be:

```<code>{ init : ( Model, Cmd Msg )
, update : Msg -> ( Model, Cmd Msg ) -> ( Model, Cmd Msg )
, view : ( Model, Cmd Msg ) -> Html Msg
}
</code>```

Alias Model

```<code>type alias Model =
    { currentNumber : Int, clicks : Int, outputList : List(String), uniqueValues : Dict Int Int, firstNumber : String, secondNumber : String, myDropState : Dropdown.State, items : List String, selectedItem : String, dictKeyToRemove : String,
    modalVisibility : Modal.Visibility  }
</code>```

Initial Model

```<code>initialModel : (Model, Cmd Msg)
initialModel =
    ({ currentNumber = 0, clicks = 0, outputList = [""], uniqueValues = Dict.empty, firstNumber = "", secondNumber = "", myDropState = Dropdown.initialState, items = ["Small", "Medium", "Large"], selectedItem = "Small", dictKeyToRemove = "",
    modalVisibility = Modal.hidden }, Cmd.none)
</code>```

Main

```<code>main : Program () Model Msg
main =
    Browser.sandbox
        { init = initialModel
        , update = update
        , view = view
        }
</code>```

Subscriptions

```<code>subscriptions : Model -> Sub Msg
subscriptions model =
    Sub.batch
        [ Dropdown.subscriptions model.myDropState DropMsg ]
</code>```

Update

```<code>update : Msg -> Model -> ( Model, Cmd Msg)
update msg model =
    case msg of
        DropMsg state ->
            ({model | myDropState = state }, Cmd.none)
</code>```

I am not sure what I am missing at this point, I have tried changing the argument with no luck.

答:
Browser.sandbox will create a simple and very limited program. The dropdown requires capabilities beyond that, namely subscriptions, which means you need to use either Browser.element or Browser.document instead.

The type of Browser.element is:

element :
    { init : flags -> ( model, Cmd msg )
    , view : model -> Html msg
    , update : msg -> model -> ( model, Cmd msg )
    , subscriptions : model -> Sub msg
    }
    -> Program flags model msg
```

<p>Compared to <code>Browser.sandbox</code>:</p>

<pre class="lang-elm prettyprint-override"><code>sandbox :
    { init : model
    , view : model -> Html msg
    , update : msg -> model -> model
    }
    -> Program () model msg
</code>```

There are three differences here:

init takes an argument, flags, which can be anything and will be interpreted by the runtime according to its type. For your purpose just using () should be enough (which is essentially what sandbox does), but see the flags section of the guide for more details.

init and update returns ( model, Cmd msg ) instead of just model.  This is the root cause of your error, because you have update and init functions which return ( model, Cmd msg ) as element would expect, but try to feed them to sandbox. This makes the compiler unhappy, because it thinks that model should be ( Model, Cmd msg ) instead of just Model.

element expects an additional subscriptions function, which you have defined but currently aren't doing anything with since sandbox doesn't accept it.

Putting this all together, substituting the following main function should work for you:

```<code>main : Program () Model Msg
main =
    Browser.element
        { init = \() -> initialModel
        , update = update
        , view = view
        , subscriptions = subscriptions
        }
</code>```

Body:
I am trying to add subscriptions as I have a dropdown, this helps ensure that the dropdowns automatically close when you click outside of them. On doing so, I had to change the model as well as my update.

This link (will take you to the Elm Bootstrap site) is the dropdown I am working with which is using Bootstrap 4.

Error I am getting

The 1st argument to sandbox is not what I expect:

295|     Browser.sandbox 296|>        { init = initialModel 297|>

  , update = update 298|>        , view = view 299|>        }

This argument is a record of type:

{ init : ( Model, Cmd Msg )
, update : Msg -> Model -> ( Model, Cmd Msg )
, view : Model -> Html Msg
}

But sandbox needs the 1st argument to be:

{ init : ( Model, Cmd Msg )
, update : Msg -> ( Model, Cmd Msg ) -> ( Model, Cmd Msg )
, view : ( Model, Cmd Msg ) -> Html Msg
}

Alias Model

type alias Model =
    { currentNumber : Int, clicks : Int, outputList : List(String), uniqueValues : Dict Int Int, firstNumber : String, secondNumber : String, myDropState : Dropdown.State, items : List String, selectedItem : String, dictKeyToRemove : String,
    modalVisibility : Modal.Visibility  }

Initial Model

initialModel : (Model, Cmd Msg)
initialModel =
    ({ currentNumber = 0, clicks = 0, outputList = [""], uniqueValues = Dict.empty, firstNumber = "", secondNumber = "", myDropState = Dropdown.initialState, items = ["Small", "Medium", "Large"], selectedItem = "Small", dictKeyToRemove = "",
    modalVisibility = Modal.hidden }, Cmd.none)

Main

main : Program () Model Msg
main =
    Browser.sandbox
        { init = initialModel
        , update = update
        , view = view
        }

Subscriptions

subscriptions : Model -> Sub Msg
subscriptions model =
    Sub.batch
        [ Dropdown.subscriptions model.myDropState DropMsg ]

Update

update : Msg -> Model -> ( Model, Cmd Msg)
update msg model =
    case msg of
        DropMsg state ->
            ({model | myDropState = state }, Cmd.none)

I am not sure what I am missing at this point, I have tried changing the argument with no luck.

Body:
Browser.sandbox will create a simple and very limited program. The dropdown requires capabilities beyond that, namely subscriptions, which means you need to use either Browser.element or Browser.document instead.

The type of Browser.element is:

element :
    { init : flags -> ( model, Cmd msg )
    , view : model -> Html msg
    , update : msg -> model -> ( model, Cmd msg )
    , subscriptions : model -> Sub msg
    }
    -> Program flags model msg

Compared to Browser.sandbox:

sandbox :
    { init : model
    , view : model -> Html msg
    , update : msg -> model -> model
    }
    -> Program () model msg

There are three differences here:

init takes an argument, flags, which can be anything and will be interpreted by the runtime according to its type. For your purpose just using () should be enough (which is essentially what sandbox does), but see the flags section of the guide for more details.

init and update returns ( model, Cmd msg ) instead of just model.  This is the root cause of your error, because you have update and init functions which return ( model, Cmd msg ) as element would expect, but try to feed them to sandbox. This makes the compiler unhappy, because it thinks that model should be ( Model, Cmd msg ) instead of just Model.

element expects an additional subscriptions function, which you have defined but currently aren't doing anything with since sandbox doesn't accept it.

Putting this all together, substituting the following main function should work for you:

main : Program () Model Msg
main =
    Browser.element
        { init = \() -> initialModel
        , update = update
        , view = view
        , subscriptions = subscriptions
        }


问:
How to persist data between CircleCI Jobs using workflows? Specifically gcloud-cli using orbs
I'm looking to run a gcloud command as part of one of my jobs. Of course, when I initially ran the job I got the error 'command not found'. CircleCI suggests using the gcloud-cli orb to install and initialise the gcloud cli.

My workflow looks like this:

```<code>workflows:
  build and deploy:
    jobs:
      - gcp-cli/install_and_initialize_cli:
          gcloud-service-key: insert_key_as_env_variable
          google-project-id: my_project_id
          google-compute-zone: my_compute_zone
      - build_job:
          requires:
            - gcp-cli/install_and_initialize_cli
</code>```

The gcp-cli/install_and_initialize_cli step works perfectly well but when I run the build_job it says gcloud command not found. I assumed that running the gcp-cli orb would make the gcloud-cli available for all downstream jobs.

Is there a way to make the gcloud-cli available to downstream jobs? I have tried to persist/attach workspaces but with no success (doesn't mean this isn't a possible solution).
The other possible solution is to find a way to run the gcp-cli orb as part of my build_job, but I can't quite figure out how to do that either.

For reference my (very stripped down) build_job:

```<code>build_job:
    docker:
      - image: circleci/node
    steps:
      - run: gcloud auth configure-docker // FAILS HERE - moved to top on purpose

      - checkout

      - restore_cache:
          keys:
            - v1-dependencies-{{ checksum "package.json" }}
            # fallback to using the latest cache if no exact match is found
            - v1-dependencies-

      - run:
          name: Install Docker Compose
          command: |
            curl -L https://github.com/docker/compose/releases/download/1.19.0/docker-compose-`uname -s`-`uname -m` > ~/docker-compose
            chmod +x ~/docker-compose
            sudo mv ~/docker-compose /usr/local/bin/docker-compose

      - setup_remote_docker

....
</code>```

答:
Assuming you are using circleci/node as a base image in all jobs, and assuming you want gcloud to be available in all of them, I would do the following:

Create a new pipeline to build a Docker image, so that when you push to it in version control, it builds the image and pushes the image to a Docker registry. Use FROM circleci/node at the start of the Dockerfile and then install gcloud as you would normally in Linux. Tag it with the URL of your registry, e.g. like registry.gitlab.com/grant-isdale/gcloud-node, so that you can push and pull it (substituting your username and registry name as appropriate, of course).

Then, in your CircleCI jobs, use registry.gitlab.com/grant-isdale/gcloud-node instead of circleci/node. You can add authentication details here if the registry requires authentication.

Body:
I'm looking to run a gcloud command as part of one of my jobs. Of course, when I initially ran the job I got the error 'command not found'. CircleCI suggests using the gcloud-cli orb to install and initialise the gcloud cli.

My workflow looks like this:

workflows:
  build and deploy:
    jobs:
      - gcp-cli/install_and_initialize_cli:
          gcloud-service-key: insert_key_as_env_variable
          google-project-id: my_project_id
          google-compute-zone: my_compute_zone
      - build_job:
          requires:
            - gcp-cli/install_and_initialize_cli

The gcp-cli/install_and_initialize_cli step works perfectly well but when I run the build_job it says gcloud command not found. I assumed that running the gcp-cli orb would make the gcloud-cli available for all downstream jobs.

Is there a way to make the gcloud-cli available to downstream jobs? I have tried to persist/attach workspaces but with no success (doesn't mean this isn't a possible solution).
The other possible solution is to find a way to run the gcp-cli orb as part of my build_job, but I can't quite figure out how to do that either.

For reference my (very stripped down) build_job:

build_job:
    docker:
      - image: circleci/node
    steps:
      - run: gcloud auth configure-docker // FAILS HERE - moved to top on purpose

      - checkout

      - restore_cache:
          keys:
            - v1-dependencies-{{ checksum "package.json" }}
            # fallback to using the latest cache if no exact match is found
            - v1-dependencies-

      - run:
          name: Install Docker Compose
          command: |
            curl -L https://github.com/docker/compose/releases/download/1.19.0/docker-compose-`uname -s`-`uname -m` > ~/docker-compose
            chmod +x ~/docker-compose
            sudo mv ~/docker-compose /usr/local/bin/docker-compose

      - setup_remote_docker

....


问:
Summing values of an object by first filtering other unique values of the same object
Let's say I have a list of an object lets call this object Order which has a quantity and price as fields.

for example as below:

Object Order (fields quantity and price) list contains the below values:

```<code>Quantity  Price

5         200
6         100
3         200
1         300
</code>```

Now I want to use Java-8 to fetch this list filtered in below way:

```<code>Quantity  Price

8         200
6         100
1         300
</code>```

Price being the unique value to filter from and summing any quantity that the price has, I want to form a new list based on this.

Please suggest how i can do this with java 8 lambda expression, thanks.

答:
The following Stream does the trick:

```<code>List<Order> o  = orders.stream().collect(
    Collectors.collectingAndThen(
        Collectors.groupingBy(Order::getPrice,Collectors.summingInt(Order::getQuantity)),
        map -> map.entrySet().stream()
                             .map(e -> new Order(e.getKey(), e.getValue()))
                             .collect(Collectors.toList())));
</code>```

Let's break this down:

The following code returns a Map<Integer, Integer> which contains price as a key (the unique value you want to base the summing on) and its summed quantities. The key method is Collectors.groupingBy with classifier describing the key and the downstream defining a value, which would be a sum of quantities, hence Collectors.summingInt (depends on the quantity type):

```<code>Map<Integer, Integer> map = orders.stream().collect(
    Collectors.groupingBy(                            // I want a Map<Integer, Integer>
        Order::getPrice,                              // price is the key
        Collectors.summingInt(Order::getQuantity))    // sum of quantities is the value
</code>```

The desired structure is List<Order>, therefore you want to use the Collectors.collectingAndThen method with a Collector<T, A, R> downstream and Function<R, RR> finisher. The downstream is the grouping from the first point, the finisher will be a conversion of Map<Integer, Integer> back to List<Order>:

```<code>List<Order> o  = orders.stream().collect(
Collectors.collectingAndThen(
    grouping,                                                 // you know this one ;)
    map -> map.entrySet()
              .stream()                                       // iterate entries
              .map(e -> new Order(e.getKey(), e.getValue()))  // new Order(qty, price)
              .collect(Collectors.toList())));                // as a List<Order>
</code>```

Body:
Let's say I have a list of an object lets call this object Order which has a quantity and price as fields.

for example as below:

Object Order (fields quantity and price) list contains the below values:

Quantity  Price

5         200
6         100
3         200
1         300

Now I want to use Java-8 to fetch this list filtered in below way:

Quantity  Price

8         200
6         100
1         300

Price being the unique value to filter from and summing any quantity that the price has, I want to form a new list based on this.

Please suggest how i can do this with java 8 lambda expression, thanks.

Body:
The following Stream does the trick:

List<Order> o  = orders.stream().collect(
    Collectors.collectingAndThen(
        Collectors.groupingBy(Order::getPrice,Collectors.summingInt(Order::getQuantity)),
        map -> map.entrySet().stream()
                             .map(e -> new Order(e.getKey(), e.getValue()))
                             .collect(Collectors.toList())));

Let's break this down:

The following code returns a Map<Integer, Integer> which contains price as a key (the unique value you want to base the summing on) and its summed quantities. The key method is Collectors.groupingBy with classifier describing the key and the downstream defining a value, which would be a sum of quantities, hence Collectors.summingInt (depends on the quantity type):

Map<Integer, Integer> map = orders.stream().collect(
    Collectors.groupingBy(                            // I want a Map<Integer, Integer>
        Order::getPrice,                              // price is the key
        Collectors.summingInt(Order::getQuantity))    // sum of quantities is the value

The desired structure is List<Order>, therefore you want to use the Collectors.collectingAndThen method with a Collector<T, A, R> downstream and Function<R, RR> finisher. The downstream is the grouping from the first point, the finisher will be a conversion of Map<Integer, Integer> back to List<Order>:

List<Order> o  = orders.stream().collect(
Collectors.collectingAndThen(
    grouping,                                                 // you know this one ;)
    map -> map.entrySet()
              .stream()                                       // iterate entries
              .map(e -> new Order(e.getKey(), e.getValue()))  // new Order(qty, price)
              .collect(Collectors.toList())));                // as a List<Order>


问:
How to close IPython Notebook properly?
How to close IPython Notebook properly?

Currently, I just close the browser tabs and then use Ctrl+C in the terminal.

Unfortunately, neither exit() nor ticking Kill kernel upon exit does help (they do kill the kernel they but don't exit the iPython).

答:
Step 1 - On shell just do control+z (control+c)
Step 2 _ close the web browser</p>

Title: How to close IPython Notebook properly?


问:
What are the proper dimensions for a background image in an android app?
I would like to create a background image for my app in Photoshop. I understand that I will need to create three different files at the appropriate dpi for ldpi, mdpi and hdpi. But what are the appropriate dimensions and resolutions for each?</p>

答: Dimension varies by phone. Android will scale them slightly. Check out Android Developer's site.</p>