问:
How to create a custom checkbox in css

I want to create a checkbox like this. with a white tick and transparent background. Can someone help me on how to do it
I tried
 input[type="checkbox"]{
background-color:rgba(255,255,255,0.1);
color:white;
}

But doesnt work as in this
codepen

答:
please see this

HTML

```<code> <div>
   <input id="option" type="checkbox" name="field" value="option">
    <label for="option"><span><span></span></span>Value</label>
 </div>
</code>```

CSS

```<code>    input[type=checkbox]:not(old),
    input[type=radio   ]:not(old){
      width     : 2em;
      margin    : 0;
      padding   : 0;
      font-size : 1em;
      opacity   : 0;
    }
    input[type=checkbox]:not(old) + label,
    input[type=radio   ]:not(old) + label{
      display      : inline-block;
      margin-left  : -2em;
      line-height  : 1.5em;
    }
    input[type=checkbox]:not(old) + label > span,
    input[type=radio   ]:not(old) + label > span{
       display          : inline-block;
       width            : 0.875em;
       height           : 0.875em;
       margin           : 0.25em 0.5em 0.25em 0.25em;
       border           : 0.0625em solid rgb(192,192,192);
       border-radius    : 0.25em;
       background       : rgb(224,224,224);
       background-image :    -moz-linear-gradient(rgb(240,240,240),rgb(224,224,224));
       background-image :     -ms-linear-gradient(rgb(240,240,240),rgb(224,224,224));
       background-image :      -o-linear-gradient(rgb(240,240,240),rgb(224,224,224));
       background-image : -webkit-linear-gradient(rgb(240,240,240),rgb(224,224,224));
       background-image :         linear-gradient(rgb(240,240,240),rgb(224,224,224));
       vertical-align   : bottom;
    }

    input[type=checkbox]:not(old):checked + label > span,
    input[type=radio   ]:not(old):checked + label > span{
      background-image :    -moz-linear-gradient(rgb(224,224,224),rgb(240,240,240));
      background-image :     -ms-linear-gradient(rgb(224,224,224),rgb(240,240,240));
      background-image :      -o-linear-gradient(rgb(224,224,224),rgb(240,240,240));
      background-image : -webkit-linear-gradient(rgb(224,224,224),rgb(240,240,240));
      background-image :         linear-gradient(rgb(224,224,224),rgb(240,240,240));
    }
    input[type=checkbox]:not(old):checked + label > span:before{
      content     : '✓';
      display     : block;
      width       : 1em;
      color       : rgb(153,204,102);
      font-size   : 0.875em;
      line-height : 1em;
      text-align  : center;
      text-shadow : 0 0 0.0714em rgb(115,153,77);
      font-weight : bold;
     }
</code>```

Also check out here

Title: How to create a custom checkbox in css

Body:
please see this

HTML

 <div>
   <input id="option" type="checkbox" name="field" value="option">
    <label for="option"><span><span></span></span>Value</label>
 </div>

CSS

    input[type=checkbox]:not(old),
    input[type=radio   ]:not(old){
      width     : 2em;
      margin    : 0;
      padding   : 0;
      font-size : 1em;
      opacity   : 0;
    }
    input[type=checkbox]:not(old) + label,
    input[type=radio   ]:not(old) + label{
      display      : inline-block;
      margin-left  : -2em;
      line-height  : 1.5em;
    }
    input[type=checkbox]:not(old) + label > span,
    input[type=radio   ]:not(old) + label > span{
       display          : inline-block;
       width            : 0.875em;
       height           : 0.875em;
       margin           : 0.25em 0.5em 0.25em 0.25em;
       border           : 0.0625em solid rgb(192,192,192);
       border-radius    : 0.25em;
       background       : rgb(224,224,224);
       background-image :    -moz-linear-gradient(rgb(240,240,240),rgb(224,224,224));
       background-image :     -ms-linear-gradient(rgb(240,240,240),rgb(224,224,224));
       background-image :      -o-linear-gradient(rgb(240,240,240),rgb(224,224,224));
       background-image : -webkit-linear-gradient(rgb(240,240,240),rgb(224,224,224));
       background-image :         linear-gradient(rgb(240,240,240),rgb(224,224,224));
       vertical-align   : bottom;
    }

    input[type=checkbox]:not(old):checked + label > span,
    input[type=radio   ]:not(old):checked + label > span{
      background-image :    -moz-linear-gradient(rgb(224,224,224),rgb(240,240,240));
      background-image :     -ms-linear-gradient(rgb(224,224,224),rgb(240,240,240));
      background-image :      -o-linear-gradient(rgb(224,224,224),rgb(240,240,240));
      background-image : -webkit-linear-gradient(rgb(224,224,224),rgb(240,240,240));
      background-image :         linear-gradient(rgb(224,224,224),rgb(240,240,240));
    }
    input[type=checkbox]:not(old):checked + label > span:before{
      content     : '✓';
      display     : block;
      width       : 1em;
      color       : rgb(153,204,102);
      font-size   : 0.875em;
      line-height : 1em;
      text-align  : center;
      text-shadow : 0 0 0.0714em rgb(115,153,77);
      font-weight : bold;
     }

Also check out here


来源: stackexchange

问:
Minimal difference between biggest and smallest value in any path of x length in matrix
I have a kattis task that I'm struggling with to complete.
The task is to "find a set of at least k connected entries in a matrix, such that the difference between the largest and smallest entry in the set was minimized".

The input is first the size of the matrix:

```5 10```

Then the values of the matrix:

```0  0  3  46 0  46 0  0  12 12

0  0  13 50 49 46 11 10 10 11

0  51 51 49 99 99 89 0  0  10

0  0  48 82 70 99 0  52 13 14

51 50 50 51 70 35 70 10 14 11
```

After that there's the ammount of k values:

``` 6 ```

And then the actual values on k:

```
1

5

10

12

47

50
```

The task states that: "An entry in the matrix, a(i,j), is adjacent to the entries a(i,j+1), a(i+1,j), a(i,j-1) and a(i-1,j). A set of entries are connected if for every pair of entries in the set, there is a connecting path of adjacent entries in it.".

For the values given the output should be:

```
0

0

3

4

89

99
```

I have written the code to take all the inputs:

```<code>  Scanner sc = new Scanner(System.in);
  int r = sc.nextInt();
  int c = sc.nextInt();

  // fill with values
  int[][] dimMat = new int[r][c];
  for (int i = 0; i < dimMat.length; i++) {
     for (int j = 0; j < dimMat[i].length; j++) {
        dimMat[i][j] = sc.nextInt();
     }
  }

  int n = sc.nextInt();
  int[] myK = new int[n];

  // fill k
  for(int k= 0; k< myK.length; k++){
     myK[k] = sc.nextInt();
  }
</code>```

But have no idea how to traverse the matrix, get all the different paths or find the value they ask for. I've been googling dynamic programming and other stuff for days without any result.

Thanks in advance for any help.

答:
I might be able to get you started. A good way to approach these problems is to first come up with a naive solution and then optimize. A naive approach to this problem might look like this:

```<code>k = desired size of region;
minValue = infinity;
for every node in your graph {
  S = an empty set of nodes;
  add current node to s;
  while(S.size < k) {
    nextNode = infinity;
    for every node in S called s {
      N = the smallest connected node to s;
      if N < nextNode
        nextNode = n;
    }
    add nextNode to S;
  }
  find greatest difference between nodes in your set;
  if greatestDifference < minValue
    minValue = greatestDifference;
}
</code>```

This algorithm loops over every node in your graph, builds a region of smallest distance from that node, sees if the max distance between those nodes is currently globally optimal, and if it is, stores the max distance. You can take this pseudo-code, type it up, and then optimize it. I hope that is enough of a start for you. This algorithm is pretty unoptimized.

ContentLicense: CC BY-SA 3.0

Body:
I have a kattis task that I'm struggling with to complete.
The task is to "find a set of at least k connected entries in a matrix, such that the difference between the largest and smallest entry in the set was minimized".

The input is first the size of the matrix:

5 10

Then the values of the matrix:

0  0  3  46 0  46 0  0  12 12

0  0  13 50 49 46 11 10 10 11

0  51 51 49 99 99 89 0  0  10

0  0  48 82 70 99 0  52 13 14

51 50 50 51 70 35 70 10 14 11

After that there's the ammount of k values:

 6

And then the actual values on k:

1

5

10

12

47

50

The task states that: "An entry in the matrix, a(i,j), is adjacent to the entries a(i,j+1), a(i+1,j), a(i,j-1) and a(i-1,j). A set of entries are connected if for every pair of entries in the set, there is a connecting path of adjacent entries in it.".

For the values given the output should be:

0

0

3

4

89

99

I have written the code to take all the inputs:

  Scanner sc = new Scanner(System.in);
  int r = sc.nextInt();
  int c = sc.nextInt();

  // fill with values
  int[][] dimMat = new int[r][c];
  for (int i = 0; i < dimMat.length; i++) {
     for (int j = 0; j < dimMat[i].length; j++) {
        dimMat[i][j] = sc.nextInt();
     }
  }

  int n = sc.nextInt();
  int[] myK = new int[n];

  // fill k
  for(int k= 0; k< myK.length; k++){
     myK[k] = sc.nextInt();
  }

But have no idea how to traverse the matrix, get all the different paths or find the value they ask for. I've been googling dynamic programming and other stuff for days without any result.

Thanks in advance for any help.

Body:
I might be able to get you started. A good way to approach these problems is to first come up with a naive solution and then optimize. A naive approach to this problem might look like this:

k = desired size of region;
minValue = infinity;
for every node in your graph {
  S = an empty set of nodes;
  add current node to s;
  while(S.size < k) {
    nextNode = infinity;
    for every node in S called s {
      N = the smallest connected node to s;
      if N < nextNode
        nextNode = n;
    }
    add nextNode to S;
  }
  find greatest difference between nodes in your set;
  if greatestDifference < minValue
    minValue = greatestDifference;
}

This algorithm loops over every node in your graph, builds a region of smallest distance from that node, sees if the max distance between those nodes is currently globally optimal, and if it is, stores the max distance. You can take this pseudo-code, type it up, and then optimize it. I hope that is enough of a start for you. This algorithm is pretty unoptimized.


问:
ajax doesn't work on localhost
I have a simple Ajax calculation but it doesn't work

that's the JavaScript Code

```<code><script>

   function showFees() {
        e.preventDefault();
        var weight = ('weight').val;
        var ship_type== ('ship_type').val;
        var eol== ('eol').val;
        if (weight == 0) {
            document.getElementById("txtHint").innerHTML = "";
            return;
        } else {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
         document.getElementById("txtHint").innerHTML =this.responseText;
                }
            };
            xmlhttp.open("GET", "sdr.php?weight=" + weight "ship_type" + ship_type + "eol" + eol, true);
            xmlhttp.send();
        }
    }
</code>```

that's my form

```<code><form>

 <label>weight:</label>

 <input type="number" name="weight" min="0" value="0">

 Ship Type:

 <select name="ship_type">

        <option value="1">Tankers of Crude Oil</option>
        <option value="2">Tankers of Petroleum Products</option>

      </select>
      Laden Or Ballast:
      <select name="eol">
                <option value="0">Ballast</option>
                <option value="1">Laden</option>
              </select>
      <input type="submit" onclick="showFees()" value="calc">
      </form>
      <p>Suggestions: <span id="txtHint"></span></p>
</code>```

and my sdr page to calculate the final result

```<code>$weight;
$i=0;
$wpt=0/*weight per ton result*/;
$ship_type;
$eol;/*empty or loaded*/
$channel_weights=array(5,5,10,20,30,50,10000);

$weight = $_REQUEST['weight'];
$ship_type = $_REQUEST['ship_type'];
$eol = $_REQUEST['eol'];
while($weight!=0){
    if($weight>=$channel_weights[$i]){
        $wpt+=$channel_weights[$i]*$ship_load_vlues[$eol][$ship_type][$i];
        $weight-=$channel_weights[$i];
    }
    else{
        $wpt+=$weight*$ship_load_vlues[$eol][$ship_type][$i];
        $weight=0;
    }

    $i++;
}

$final = $wpt*$float_sdr*1000;
echo $final === "0" ? "wrong data" : $final;
 ?>
</code>```

I think echo must return to span with ID 'txtHint' but it doesn't return any and if I tried to put alert in java script doesn't work either and I tried to add ajax library and doesn't work also

答:
You're missing an '+' sign, and '&=' signs:

xmlhttp.open("GET", "sdr.php?weight=" + weight "ship_type" + ship_type + "eol" + eol, true);

Should be

xmlhttp.open("GET", "sdr.php?weight=" + weight + "&ship_type=" + ship_type + "&eol=" + eol, true);

Title: ajax doesn't work on localhost


问:
How to Export JSON to CSV or Excel - Angular 2
Say my json is like this:

```<code>var readyToExport = [
   {id: 1, name: 'a'},
   {id: 2, name: 'b'},
   {id: 3, name: 'c'}
];
</code>```

How can I export this JSON into CSV or Excel file in Angular2?

The browser that I'm using is Chrome.

Maybe Angular2 is not relevant, however, is there any third party plugin that can be injected in Angular2 and perform this task?

答:
I used the angular2-csv library for this: https://www.npmjs.com/package/angular2-csv

This worked very well for me with one exception.  There is a known issue (https://github.com/javiertelioz/angular2-csv/issues/10) with the BOM character getting inserted at the start of the file which causes a garbage character to display with my version of Excel.

Body:
Say my json is like this:

var readyToExport = [
   {id: 1, name: 'a'},
   {id: 2, name: 'b'},
   {id: 3, name: 'c'}
];

How can I export this JSON into CSV or Excel file in Angular2?

The browser that I'm using is Chrome.

Maybe Angular2 is not relevant, however, is there any third party plugin that can be injected in Angular2 and perform this task?


问:
Redis Chain Commands
I'm wondering what is the best way to chain together a series of commands so that they all execute on redis before returning the final result? All of my data is stored in Sets.

```<code>data1 = [ a, b, c, d, e]
data2 = [b, c]
</code>```

How would I go about getting the intersection of data1 and data2 (result=b,c) and then call SRANDMEMBER on the result? In a series it would look like:

```<code>redis> SINTER data1 data2
redis> SRANDMEMBER <previous result>
</code>```

There could of course be other operations to chain together like SDIFF and SADD but choosing a random item from an intersection seems like the simplest example.

I tries creating a lua script but I received the message "Lua redis() command arguments must be strings or integers" when I attempted to execute the following code:

```<code>local k1, k2 = KEYS[1], KEYS[2]
local intersect, single_record

if not redis.call("exists", k1) then return 0 end

intersect_data = redis.call("SINTER", k1, k2)
single_record = redis.call("SRANDMEMBER", intersect_data)

return single_record
</code>```

答:
tl;dr - you're passing a Lua table (intersect_data) instead of a string and an optional number to SRANDMEMBER.

SINTER may return 0 or more results as a Lua table. SRANDMEMBER requires a single key name that is a Redis Set and an optional count (integer) argument.

The biggest issue I see with the above logic is that it appears to assume that the intersect yields exactly one result. It doesn't care about 0 or more than 1...

Assuming that a single result is always returned from the intersect, you should call SRANDMEMBER with intersect_data[1] (the first element in the table).

Title: Redis Chain Commands

Body:
I'm wondering what is the best way to chain together a series of commands so that they all execute on redis before returning the final result? All of my data is stored in Sets.

data1 = [ a, b, c, d, e]
data2 = [b, c]

How would I go about getting the intersection of data1 and data2 (result=b,c) and then call SRANDMEMBER on the result? In a series it would look like:

redis> SINTER data1 data2
redis> SRANDMEMBER <previous result>

There could of course be other operations to chain together like SDIFF and SADD but choosing a random item from an intersection seems like the simplest example.

I tries creating a lua script but I received the message "Lua redis() command arguments must be strings or integers" when I attempted to execute the following code:

local k1, k2 = KEYS[1], KEYS[2]
local intersect, single_record

if not redis.call("exists", k1) then return 0 end

intersect_data = redis.call("SINTER", k1, k2)
single_record = redis.call("SRANDMEMBER", intersect_data)

return single_record


答:
A first algorithm in O((RC)^3):

Considering the small size of the matrices, you might be able to go for a very naive approach that runs in time O((RC)^3), which is :

Store all the values of altitudes alts in a separate array and sort them

Now for all pairs (L,H), L <= H, of values of this array alts :

Consider the matrix B such that b(i,j) = 1 if L <= a(i,j) <= H, b(i,j) = 0 otherwise.

Use several BFS or a union-find structure to find the size of the largest 1-valued connected component in B.

You now know for each pair (L,H), k(L,H), the size of the largest connected component of values between L and H. Now, to find the lowest altitude difference for a given k, you just have to compute the minimum of H-L for all pairs (L,H) such that k(L,H) >= k.

A variation in O((RC)^2 log(RC)) per request:

For any given k, for all possible values of L (the lowest point), do a dichotomic search over H (the value of the highest point) to find the lowest H such that k(L,H) >= k. This is possible because H1 >= H2 implies k(L,H1) >= k(L,H2) for all L.

Finally, a solution in O((RC)^2 log(RC))

For all points of the matrix, start a Dijkstra search (priority is the altitude, and you never go to points that are above your starting altitude). The assumption behind each search is that you start your search from the peak, and only go down from there, slowly increasing the altitude difference.

As before, during this computation you get connected components of given (L,H) of which you know the size k(L,H). This allows you to compute the lowest difference H-L that achieves a given k for all k, and thus answer all the questions (you can store all the minimal H-L for k from 0 to RC in a (RC+1)-sized array).

Title: Minimal difference between biggest and smallest value in any path of x length in matrix


问:
Converting SQL to LINQ
I'm trying to convert a SQL query to a LINQ query. Any help would be appreciated.
Here is my SQL query:</p>

```<code>SELECT DISTINCT
 U.UserID,
 U.LoginID,
 U.FirstName,
 U.LastName,
 U.IsActive,
 U.IsApproved,
 U.Email,
 U.DateLastLogin,
 CONVERT(VARCHAR, U.DateLastLogin, 101) AS LastLogin,
 U.JobTitle,
 U.AgencyName,
 U.WorkPhone,
 U.Fax,
 U.MobilePhone,
 U.Satellite,
 U.Blackberry,
 U.Pager,
 U.Address1,
 U.Address2,
 U.City,
 U.StateAbbr,
 U.ZipCode,
 G.[Name] AS GroupName,
 COALESCE( B.UserID, 0 ) AS BTC

 FROM dbo.Users U

 INNER JOIN dbo.Users_Grantee UG ON U.UserID = UG.UserID

 INNER JOIN dbo.Users_Groups UGRP ON UG.UserID = UGRP.UserID
 INNER JOIN dbo.Groups G ON UGRP.GroupID = G.GroupID

 --Flag for BTC Users
 LEFT OUTER JOIN (
      SELECT UG2.UserID
      FROM dbo.Users_Groups UG2
      INNER JOIN dbo.Groups G2 ON UG2.GroupID = G2.GroupID
      WHERE G2.GroupClass_ID = 44
 ) B ON U.UserID = B.UserID

 WHERE U.IsAdminUser = 0
 AND  U.IsActive = @IsActive
 AND  UG.GranteeID = @GranteeID
 AND  G.GroupClass_ID = 1 --Grantee GroupClass
 AND  (U.LastName  LIKE @LastName
  OR   U.FirstName LIKE @FirstName
  OR   U.Email     LIKE @Email
  OR   U.LoginID = @LoginID)

 --Exclude PO users who have grantee access.
 AND NOT EXISTS(
     SELECT 1
     FROM dbo.Users_Groups UG1
     INNER JOIN dbo.Groups G1 ON UG1.GroupID = G1.GroupID
     WHERE UG1.UserID = UG.UserID
     AND  G1.GroupClass_ID <> 1
     AND  G1.GroupClass_ID <> 44
      )
</code>```

答:
Somehow I did it with the following query:</p>

```<code>(from u in Users
     from ugrt in Users_Grantees where (u.UserID == ugrt.UserID)
     from ugrp in Users_Groups where (ugrt.UserID == ugrp.UserID)
     from g in Groups where (ugrp.GroupID == g.GroupID)
    from ug in
        (from  ug2 in Users_Groups
            join g2 in Groups on ug2.GroupID equals g2.GroupID
                where (g2.GroupClass_ID == 44)
            select new {ug2.UserID}).Where(ug=>ug.UserID == u.UserID).DefaultIfEmpty()
            where
            u.IsAdminUser == false
            && u.IsActive == true
            && ugrt.GranteeID == 1
            && g.GroupClass_ID == 1
            orderby u.LastName
            select u)
            .Where (t1 => !(from ugrp1 in Users_Groups
                join g1 in Groups on ugrp1.GroupID equals g1.GroupID
                where (g1.GroupClass_ID != 1
                    && g1.GroupClass_ID != 44)
                    select new {ugrp1.UserID})
                    .Any(t2 => t2.UserID == t1.UserID))
</code>```

ContentLicense: CC BY-SA 2.5

Title: Converting SQL to LINQ

Body:
I'm trying to convert a SQL query to a LINQ query. Any help would be appreciated.
Here is my SQL query:

SELECT DISTINCT
 U.UserID,
 U.LoginID,
 U.FirstName,
 U.LastName,
 U.IsActive,
 U.IsApproved,
 U.Email,
 U.DateLastLogin,
 CONVERT(VARCHAR, U.DateLastLogin, 101) AS LastLogin,
 U.JobTitle,
 U.AgencyName,
 U.WorkPhone,
 U.Fax,
 U.MobilePhone,
 U.Satellite,
 U.Blackberry,
 U.Pager,
 U.Address1,
 U.Address2,
 U.City,
 U.StateAbbr,
 U.ZipCode,
 G.[Name] AS GroupName,
 COALESCE( B.UserID, 0 ) AS BTC

 FROM dbo.Users U

 INNER JOIN dbo.Users_Grantee UG ON U.UserID = UG.UserID

 INNER JOIN dbo.Users_Groups UGRP ON UG.UserID = UGRP.UserID
 INNER JOIN dbo.Groups G ON UGRP.GroupID = G.GroupID

 --Flag for BTC Users
 LEFT OUTER JOIN (
      SELECT UG2.UserID
      FROM dbo.Users_Groups UG2
      INNER JOIN dbo.Groups G2 ON UG2.GroupID = G2.GroupID
      WHERE G2.GroupClass_ID = 44
 ) B ON U.UserID = B.UserID

 WHERE U.IsAdminUser = 0
 AND  U.IsActive = @IsActive
 AND  UG.GranteeID = @GranteeID
 AND  G.GroupClass_ID = 1 --Grantee GroupClass
 AND  (U.LastName  LIKE @LastName
  OR   U.FirstName LIKE @FirstName
  OR   U.Email     LIKE @Email
  OR   U.LoginID = @LoginID)

 --Exclude PO users who have grantee access.
 AND NOT EXISTS(
     SELECT 1
     FROM dbo.Users_Groups UG1
     INNER JOIN dbo.Groups G1 ON UG1.GroupID = G1.GroupID
     WHERE UG1.UserID = UG.UserID
     AND  G1.GroupClass_ID <> 1
     AND  G1.GroupClass_ID <> 44
      )

Body:
Somehow I did it with the following query:

(from u in Users
     from ugrt in Users_Grantees where (u.UserID == ugrt.UserID)
     from ugrp in Users_Groups where (ugrt.UserID == ugrp.UserID)
     from g in Groups where (ugrp.GroupID == g.GroupID)
    from ug in
        (from  ug2 in Users_Groups
            join g2 in Groups on ug2.GroupID equals g2.GroupID
                where (g2.GroupClass_ID == 44)
            select new {ug2.UserID}).Where(ug=>ug.UserID == u.UserID).DefaultIfEmpty()
            where
            u.IsAdminUser == false
            && u.IsActive == true
            && ugrt.GranteeID == 1
            && g.GroupClass_ID == 1
            orderby u.LastName
            select u)
            .Where (t1 => !(from ugrp1 in Users_Groups
                join g1 in Groups on ugrp1.GroupID equals g1.GroupID
                where (g1.GroupClass_ID != 1
                    && g1.GroupClass_ID != 44)
                    select new {ugrp1.UserID})
                    .Any(t2 => t2.UserID == t1.UserID))


问:
Unable to fetch data in Codeigniter PHP
developing quiz in Codeigniter PHP, unable to fetch data its's showing like this, its the field name "quizID" , "question" for every question displaying like this

'quizID'?>.'question'?>

Quiz Model File Code

```<code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class quizmodel extends CI_Model {

public function getQuestions()
{
    $this->db->select("quizID, question, choice1, choice2, choice3,
answer");
    $this->db->from("QuizQuestion");

    $query = $this->db->get();

    return $query->result();

    $num_data_returned = $query->num_rows;

    if ($num_data_returned < 1) {
      echo "There is no data in the database";
      exit();
    }
}
}
</code>```

Question File Code

```<code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Questions extends CI_Controller {

function __construct() {
    parent::__construct();
    $this->load->database();
}

public function quizdisplay()
{
    $this->load->model('quizmodel');
    $this->data['questions'] = $this->quizmodel->getQuestions();
    $this->load->view('play_quiz', $this->data);
 }

    public function resultdisplay()
 {
    $this->data['checks'] = array(
         'ques1' => $this->input->post('quizid1'),
         'ques2' => $this->input->post('quizid2'),
         'ques3' => $this->input->post('quizid3'),
         'ques4' => $this->input->post('quizid4'),
         'ques5' => $this->input->post('quizid5'),
         'ques6' => $this->input->post('quizid6'),
         'ques7' => $this->input->post('quizid7'),
         'ques8' => $this->input->post('quizid8'),
         'ques9' => $this->input->post('quizid9'),
         'ques10' => $this->input->post('quizid10'),
    );

    $this->load->model('quizmodel');
    $this->data['results'] = $this->quizmodel->getQuestions();
    $this->load->view('result_display', $this->data);
}
}
</code>```

Play Quiz File Code

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Play Quiz</title>

</head>
<body>

<div id="container">
<h1>Play the Quiz!</h1>

<form method="post" action="<?php echo base_url();?
>index.php/Questions/resultdisplay">

<?php foreach($questions as $row) { ?>

<?php $ans_array = array($row->choice1, $row->choice2, $row->choice3, $row-
>answer);
shuffle($ans_array); ?>

<p><?=$row->quizID?>.<?=$row->question?></p>

<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[0]?
>" required> <?=$ans_array[0]?><br>
<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[1]?
>"> <?=$ans_array[1]?><br>
<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[2]?
>"> <?=$ans_array[2]?><br>
<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[3]?
>"> <?=$ans_array[3]?><br>

<?php } ?>

<br><br>
<input type="submit" value="Submit!">

</form>

</div>

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

答:
change your model like this and try </p>

```<code>class quizmodel extends CI_Model {

    public function getQuestions()
    {
        $this->db->select("quizID, question, choice1, choice2, choice3,
    answer");
        $this->db->from("QuizQuestion");

        $query = $this->db->get();

        $result = $query->result_array();

        $num_data = $query->num_rows();

         if ($num_data ==0) {
           return false;
         }else{
           return $result;
         }
       }
    }
</code>```

Title: Unable to fetch data in Codeigniter PHP

Body:
developing quiz in Codeigniter PHP, unable to fetch data its's showing like this, its the field name "quizID" , "question" for every question displaying like this

'quizID'?>.'question'?>

Quiz Model File Code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class quizmodel extends CI_Model {

public function getQuestions()
{
    $this->db->select("quizID, question, choice1, choice2, choice3,
answer");
    $this->db->from("QuizQuestion");

    $query = $this->db->get();

    return $query->result();

    $num_data_returned = $query->num_rows;

    if ($num_data_returned < 1) {
      echo "There is no data in the database";
      exit();
    }
}
}

Question File Code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Questions extends CI_Controller {

function __construct() {
    parent::__construct();
    $this->load->database();
}

public function quizdisplay()
{
    $this->load->model('quizmodel');
    $this->data['questions'] = $this->quizmodel->getQuestions();
    $this->load->view('play_quiz', $this->data);
 }

    public function resultdisplay()
 {
    $this->data['checks'] = array(
         'ques1' => $this->input->post('quizid1'),
         'ques2' => $this->input->post('quizid2'),
         'ques3' => $this->input->post('quizid3'),
         'ques4' => $this->input->post('quizid4'),
         'ques5' => $this->input->post('quizid5'),
         'ques6' => $this->input->post('quizid6'),
         'ques7' => $this->input->post('quizid7'),
         'ques8' => $this->input->post('quizid8'),
         'ques9' => $this->input->post('quizid9'),
         'ques10' => $this->input->post('quizid10'),
    );

    $this->load->model('quizmodel');
    $this->data['results'] = $this->quizmodel->getQuestions();
    $this->load->view('result_display', $this->data);
}
}

Play Quiz File Code

<!DOCTYPE html>

<meta charset="utf-8">
<title>Play Quiz</title>

Play the Quiz!

<form method="post" action="<?php echo base_url();?
>index.php/Questions/resultdisplay">

<?php foreach($questions as $row) { ?>

<?php $ans_array = array($row->choice1, $row->choice2, $row->choice3, $row-
>answer);
shuffle($ans_array); ?>

<?=$row->quizID?>.<?=$row->question?>

<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[0]?
>" required> <?=$ans_array[0]?>

<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[1]?
>"> <?=$ans_array[1]?>

<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[2]?
>"> <?=$ans_array[2]?>

<input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[3]?
>"> <?=$ans_array[3]?>

<?php } ?>

<input type="submit" value="Submit!">

</form>

Body:
change your model like this and try

class quizmodel extends CI_Model {

    public function getQuestions()
    {
        $this->db->select("quizID, question, choice1, choice2, choice3,
    answer");
        $this->db->from("QuizQuestion");

        $query = $this->db->get();

        $result = $query->result_array();

        $num_data = $query->num_rows();

         if ($num_data ==0) {
           return false;
         }else{
           return $result;
         }
       }
    }


问:
convert text file into dictionary -Python
I am given a .txt file which looks like this..

2:rain
3:odd
5:yes
6:go

I need to convert it into a dictionary.

This is what I have done so far.

```<code> words_dict = {}
 file = open(filename, "r")
 for word in file:
      k, v = word.split(":")
      words_dict[k.strip()] = v.strip()
 file.close()
 return words_dict
</code>```

However, when i go and print the dictionary it does not match my expected output of {2: 'rain', 3: 'odd', 5: 'yes', 6: 'go'}

Body:
I am given a .txt file which looks like this..

2:rain
3:odd
5:yes
6:go

I need to convert it into a dictionary.

This is what I have done so far.

 words_dict = {}
 file = open(filename, "r")
 for word in file:
      k, v = word.split(":")
      words_dict[k.strip()] = v.strip()
 file.close()
 return words_dict

However, when i go and print the dictionary it does not match my expected output of {2: 'rain', 3: 'odd', 5: 'yes', 6: 'go'}

Body:
l="2:rain 3:odd 5:yes 6:go".split()
{x.split(":")[0]:x.split(":")[1]  for x in l}


问:
replace part of href between 2 words jquery
This is simple and I have done it before but can't make it work right now.

I need to change the name of the image in below href

var href="https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-1654-45654.jpg"

$('.share, .share-2').prop('href', function () {
    $(this).replace(/(picture=).*?(&)/,'$1' + imgNew + '$2');
});
```

答:
The replace function is a method of string, so you can't call replace from $(this) because it is a jQuery object, not a string.

If you need to change the href attribute, just use this.href = ....

EDIT: As you are using jQuery.prop method you should use it as docs proposes.

```<code>$(".some-element").prop('some-prop', function(index, old_value){
    // do something
    return new_value;
});
</code>```

Snippet updated:

var new_img = "http://my.domain.com/img/my_new_image.jpg";
var regex_img = /\bpicture=[^&]*/

$('.share, .share-2').prop('href', function (index, old_href) {
    var new_href = old_href.replace(regex_img, 'picture=' + new_img);
    console.log(new_href);
    return new_href;
}); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Test
<br>
Test-2</code>```

Body:
The replace function is a method of string, so you can't call replace from $(this) because it is a jQuery object, not a string.

If you need to change the href attribute, just use this.href = ....

EDIT: As you are using jQuery.prop method you should use it as docs proposes.

$(".some-element").prop('some-prop', function(index, old_value){
    // do something
    return new_value;
});

Snippet updated:

var new_img = "http://my.domain.com/img/my_new_image.jpg";
var regex_img = /\bpicture=[^&]*/

$('.share, .share-2').prop('href', function (index, old_href) {
    var new_href = old_href.replace(regex_img, 'picture=' + new_img);
    console.log(new_href);
    return new_href;
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-1654-45654.jpg" class="share">Test</a>
<br>
<a href="https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&picture=http://myurl.com/img/name-1654-45654.jpg&description='tets'" class="share-2">Test-2</a>


问:
Loop through all my worksheets VBA with For Each
Why this macro doesn't change the color of all my worksheets?

It only works for the first worksheet of my active workbook.

I want it to go through all my worksheets of my workbook.
thanx

```<code>Option Explicit

Private Sub CheckBox13_Click()
    Dim I As Long, j As Long
    Dim ws As Worksheet

    For Each ws In ActiveWorkbook.Worksheets
        If CheckBox13.Value = True Then
            For I = 1 To 700
                For j = 1 To 10
                    If Cells(I, j).Interior.Color = RGB(252, 252, 250) Then
                        Cells(I, j).Interior.Color = RGB(217, 217, 217)
                    End If
                Next j
            Next I
        End If

        If CheckBox13.Value = False Then
            For I = 1 To 700
                For j = 1 To 10
                    If Cells(I, j).Interior.Color = RGB(217, 217, 217) Then
                        Cells(I, j).Interior.Color = RGB(252, 252, 250)
                    End If
                Next j
            Next I
        End If
    Next
End Sub
</code>```

答:
when you use Cells(I, j) that refers to the active worksheet. You will want to use the ws object in your reference like this:

```<code>ws.Cells(I, j)
</code>```

Body:
Why this macro doesn't change the color of all my worksheets?

It only works for the first worksheet of my active workbook.

I want it to go through all my worksheets of my workbook.
thanx

Option Explicit

Private Sub CheckBox13_Click()
    Dim I As Long, j As Long
    Dim ws As Worksheet

    For Each ws In ActiveWorkbook.Worksheets
        If CheckBox13.Value = True Then
            For I = 1 To 700
                For j = 1 To 10
                    If Cells(I, j).Interior.Color = RGB(252, 252, 250) Then
                        Cells(I, j).Interior.Color = RGB(217, 217, 217)
                    End If
                Next j
            Next I
        End If

        If CheckBox13.Value = False Then
            For I = 1 To 700
                For j = 1 To 10
                    If Cells(I, j).Interior.Color = RGB(217, 217, 217) Then
                        Cells(I, j).Interior.Color = RGB(252, 252, 250)
                    End If
                Next j
            Next I
        End If
    Next
End Sub

Body:
when you use Cells(I, j) that refers to the active worksheet. You will want to use the ws object in your reference like this:

ws.Cells(I, j)


问:
VB - Import CSV in excel with end line in same cell
Ok, this gonna be long.

I have a csv file that I want to import in a excel.

This is the CSV file.

```<code>"NIP";"Date start";"Date end";"Reason";"coment"
"1";"06/06/17 09:55";"";"test";"asdasd ad ,a dasds asd;asdfasfasdfad ,
asdfasdfda a
asffasd , asdf asf asfad; asfasfasfa ;sadfdasds
,adasdsa ,asdassda,adadasddasd, asd asdasdad
;;;;adasdasdsa ,,,,sfdafas"
</code>```

This is how looks on excel.

When this CSV is imported on excel using VB (the excel will import a lot of csv files), this is how it looks.

This is my VB code to import CSV

```<code>Option Explicit

Sub ImportFiles()
Dim sPath As String

sPath = ThisWorkbook.Path & "\data\1.csv"
'copyDataFromCsvFileToSheet sPath, ";", "1"

sPath = ThisWorkbook.Path & "\data\2.csv"
'copyDataFromCsvFileToSheet sPath, ";", "2"

sPath = ThisWorkbook.Path & "\data\3.csv"
'copyDataFromCsvFileToSheet sPath, ";", "3"

sPath = ThisWorkbook.Path & "\data\4.csv"
'copyDataFromCsvFileToSheet sPath, ";", "4"

sPath = ThisWorkbook.Path & "\data\5.csv"
'copyDataFromCsvFileToSheet sPath, ";", "5"

sPath = ThisWorkbook.Path & "\data\6.csv"
'copyDataFromCsvFileToSheet sPath, ";", "6"

sPath = ThisWorkbook.Path & "\data\7.csv"
'copyDataFromCsvFileToSheet sPath, ";", "7"

sPath = ThisWorkbook.Path & "\data\8.csv"
'copyDataFromCsvFileToSheet sPath, ";", "8"

sPath = ThisWorkbook.Path & "\data\9.csv"
'copyDataFromCsvFileToSheet sPath, ";", "9"

sPath = ThisWorkbook.Path & "\data\10.csv"
'copyDataFromCsvFileToSheet sPath, ";", "10"

sPath = ThisWorkbook.Path & "\data\11.csv"
'copyDataFromCsvFileToSheet sPath, ";", "11"

sPath = ThisWorkbook.Path & "\data\12.csv"
copyDataFromCsvFileToSheet sPath, ";", "12"

sPath = ThisWorkbook.Path & "\data\13.csv"
'copyDataFromCsvFileToSheet sPath, ";", "13"

Dim aux As String
aux = FindReplaceAll()

End Sub

Private Sub copyDataFromCsvFileToSheet(parFileName As String, _
parDelimiter As String, parSheetName As String)

    Dim Data As Variant

    Data = getDataFromFile(parFileName, parDelimiter)

If Not isArrayEmpty(Data) Then
  If SheetExists(parSheetName) Then
    With Sheets(parSheetName)
      .Range("A1:OO2000").ClearContents
      .Cells(1, 1).Resize(UBound(Data, 1), UBound(Data, 2)) = Data
    End With
  Else
    Dim warning
    warning = MsgBox("no existing sheet'" & parSheetName, vbOKOnly, "Warning")
  End If
End If
End Sub

 Function SheetExists(shtName As String, Optional wb As Workbook) As Boolean
Dim sht As Worksheet

 If wb Is Nothing Then Set wb = ThisWorkbook
 On Error Resume Next
 Set sht = wb.Sheets(shtName)
 On Error GoTo 0
 SheetExists = Not sht Is Nothing
 End Function

Function FindReplaceAll()

Dim sht As Worksheet
Dim fnd As Variant
Dim rplc As Variant

For Each sht In ActiveWorkbook.Worksheets
  sht.Cells.Replace what:=Chr(34), Replacement:="", _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False
Next sht

End Function

Public Function isArrayEmpty(parArray As Variant) As Boolean

If IsArray(parArray) = False Then isArrayEmpty = True
On Error Resume Next
If UBound(parArray) < LBound(parArray) Then
   isArrayEmpty = True
   Exit Function
    Else
   isArrayEmpty = False
End If

End Function

Private Function getDataFromFile(parFileName As String, _
parDelimiter As String, _
Optional parExcludeCharacter As String = "") As Variant

Dim locLinesList() As Variant
Dim locData As Variant
Dim i As Long
Dim j As Long
Dim lim As Long
Dim locNumRows As Long
Dim locNumCols As Long
Dim fso As Variant
Dim ts As Variant
Const REDIM_STEP = 10000

Set fso = CreateObject("Scripting.FileSystemObject")

On Error GoTo error_open_file

Set ts = fso.OpenTextFile(parFileName)
On Error GoTo unhandled_error

ReDim locLinesList(1 To 1) As Variant
i = 0
Do While Not ts.AtEndOfStream
  Dim aux As String
  aux = ts.ReadLine
  If i Mod REDIM_STEP = 0 Then
    ReDim Preserve locLinesList _
    (1 To UBound(locLinesList, 1) + REDIM_STEP) As Variant
    lim = UBound(Split(aux, parDelimiter)) + 1
  End If
  locLinesList(i + 1) = Split(aux, """+parDelimiter+""")
  j = UBound(locLinesList(i + 1), 1)

  If locNumCols < j Then locNumCols = j
  i = i + 1
Loop

ts.Close
locNumRows = i

If locNumRows = 0 Then Exit Function

ReDim locData(1 To locNumRows, 1 To locNumCols + 1) As Variant

If parExcludeCharacter <> "" Then
  For i = 1 To locNumRows
    For j = 0 To UBound(locLinesList(i), 1)
      If Left(locLinesList(i)(j), 1) = parExcludeCharacter Then
        If Right(locLinesList(i)(j), 1) = parExcludeCharacter Then
      locLinesList(i)(j) = _
      Mid(locLinesList(i)(j), 2, Len(locLinesList(i)(j)) - 2)
    Else
      locLinesList(i)(j) = _
      Right(locLinesList(i)(j), Len(locLinesList(i)(j)) - 1)
    End If
  ElseIf Right(locLinesList(i)(j), 1) = parExcludeCharacter Then
    locLinesList(i)(j) = _
    Left(locLinesList(i)(j), Len(locLinesList(i)(j)) - 1)
  End If
  locData(i, j + 1) = locLinesList(i)(j)
    Next j
  Next i
Else
  For i = 1 To locNumRows
    For j = 0 To UBound(locLinesList(i), 1)
  locData(i, j + 1) = locLinesList(i)(j)
    Next j
  Next i
End If

getDataFromFile = locData

Exit Function

error_open_file:
unhandled_error:

End Function
</code>```

I want that in the excel to look like when you open the csv in excel.

答:
This was my solution.

First I added two new functions.

```<code>Public Function mergeArrays(arr1 As Variant, arr2 As Variant) As Variant
 Dim i As Integer
 Dim sizeArr1 As Integer
 Dim arr3() As String
 ReDim arr3(UBound(arr1) + UBound(arr2) + 1)

 sizeArr1 = UBound(arr1) + 1
 For i = 0 To UBound(arr1)
     arr3(i) = arr1(i)
 Next i
 For i = 0 To UBound(arr2)
     arr3(i + sizeArr1) = arr2(i)
 Next i
 mergeArrays = arr3

End Function

Public Function DeleteElementAt(inArray As Variant) As Variant
    Dim index As Integer
    Dim aux() As String
    ReDim aux(UBound(inArray) - 1)

    For index = 1 To UBound(inArray)
        aux(index - 1) = inArray(index)
    Next index

    DeleteElementAt = aux
End Function
</code>```

Also I modified getDataFromFile

```<code>Private Function getDataFromFile(parFileName As String, _
parDelimiter As String, _
Optional parExcludeCharacter As String = "") As Variant

Dim locLinesList() As Variant
Dim locData As Variant
Dim linea() As String
Dim i As Long
Dim j As Long
Dim lim As Long
Dim locNumRows As Long
Dim locNumCols As Long
Dim fso As Variant
Dim ts As Variant
Const REDIM_STEP = 10000

Set fso = CreateObject("Scripting.FileSystemObject")

On Error GoTo error_open_file

Set ts = fso.OpenTextFile(parFileName)
On Error GoTo unhandled_error

ReDim locLinesList(1 To 1) As Variant
i = 0
Do While Not ts.AtEndOfStream
  Dim aux As String
  aux = ts.ReadLine
  aux = Replace(aux, Chr(34) & ";" & Chr(34), Chr(34) & "#@#" & Chr(34))
  linea = Split(aux, "#@#")
  If i Mod REDIM_STEP = 0 Then
    ReDim Preserve locLinesList _
    (1 To UBound(locLinesList, 1) + REDIM_STEP) As Variant
    lim = UBound(linea) + 1
    locNumCols = lim
    locLinesList(i + 1) = linea
    i = i + 1
  Else
  locLinesList(i + 1) = linea

    If UBound(locLinesList(i)) + 1 < lim Then
      locLinesList(i)(UBound(locLinesList(i))) = locLinesList(i)
   (UBound(locLinesList(i))) & vbCrLf & linea(0)
  linea = DeleteElementAt(linea)
  locLinesList(i) = mergeArrays(locLinesList(i), linea)
Else
If UBound(linea) + 1 = 1 Then
    locLinesList(i)(UBound(locLinesList(i))) = locLinesList(i)
(UBound(locLinesList(i))) & vbCrLf & linea(0)
 Else
'Linea es un salto de linea a secas
 If UBound(linea) = -1 Then
    locLinesList(i)(UBound(locLinesList(i))) = locLinesList(i)
(UBound(locLinesList(i))) & vbCrLf
     Else
        i = i + 1
     End If
    End If

    End If
  End If
Loop

Dim endVector() As Variant
ReDim endVector(i)
Dim index As Integer

For index = 0 To i - 1
    endVector(index) = locLinesList(index + 1)
Next index

ts.Close
locNumRows = i

If locNumRows = 0 Then Exit Function

ReDim locData(1 To locNumRows, 1 To locNumCols) As Variant

If parExcludeCharacter <> "" Then
  For i = 1 To locNumRows
    For j = 0 To UBound(endVector(i), 1)
      If Left(endVector(i)(j), 1) = parExcludeCharacter Then
        If Right(endVector(i)(j), 1) = parExcludeCharacter Then
          endVector(i)(j) = _
          Mid(endVector(i)(j), 2, Len(endVector(i)(j)) - 2)
        Else
          endVector(i)(j) = _
          Right(endVector(i)(j), Len(endVector(i)(j)) - 1)
        End If
      ElseIf Right(endVector(i)(j), 1) = parExcludeCharacter Then
        endVector(i)(j) = _
        Left(endVector(i)(j), Len(endVector(i)(j)) - 1)
      End If
      locData(i, j + 1) = endVector(i)(j)
    Next j
  Next i
Else
  For i = 0 To locNumRows - 1
    For j = 0 To UBound(endVector(i), 1)
      locData(i + 1, j + 1) = endVector(i)(j)
    Next j
  Next i
End If

getDataFromFile = locData

Exit Function
</code>```

I know that this code can optimized but for now It works

Body:
Ok, this gonna be long.

I have a csv file that I want to import in a excel.

This is the CSV file.

"NIP";"Date start";"Date end";"Reason";"coment"
"1";"06/06/17 09:55";"";"test";"asdasd ad ,a dasds asd;asdfasfasdfad ,
asdfasdfda a
asffasd , asdf asf asfad; asfasfasfa ;sadfdasds
,adasdsa ,asdassda,adadasddasd, asd asdasdad
;;;;adasdasdsa ,,,,sfdafas"

This is how looks on excel.

When this CSV is imported on excel using VB (the excel will import a lot of csv files), this is how it looks.

This is my VB code to import CSV

Option Explicit

Sub ImportFiles()
Dim sPath As String

sPath = ThisWorkbook.Path & "\data\1.csv"
'copyDataFromCsvFileToSheet sPath, ";", "1"

sPath = ThisWorkbook.Path & "\data\2.csv"
'copyDataFromCsvFileToSheet sPath, ";", "2"

sPath = ThisWorkbook.Path & "\data\3.csv"
'copyDataFromCsvFileToSheet sPath, ";", "3"

sPath = ThisWorkbook.Path & "\data\4.csv"
'copyDataFromCsvFileToSheet sPath, ";", "4"

sPath = ThisWorkbook.Path & "\data\5.csv"
'copyDataFromCsvFileToSheet sPath, ";", "5"

sPath = ThisWorkbook.Path & "\data\6.csv"
'copyDataFromCsvFileToSheet sPath, ";", "6"

sPath = ThisWorkbook.Path & "\data\7.csv"
'copyDataFromCsvFileToSheet sPath, ";", "7"

sPath = ThisWorkbook.Path & "\data\8.csv"
'copyDataFromCsvFileToSheet sPath, ";", "8"

sPath = ThisWorkbook.Path & "\data\9.csv"
'copyDataFromCsvFileToSheet sPath, ";", "9"

sPath = ThisWorkbook.Path & "\data\10.csv"
'copyDataFromCsvFileToSheet sPath, ";", "10"

sPath = ThisWorkbook.Path & "\data\11.csv"
'copyDataFromCsvFileToSheet sPath, ";", "11"

sPath = ThisWorkbook.Path & "\data\12.csv"
copyDataFromCsvFileToSheet sPath, ";", "12"

sPath = ThisWorkbook.Path & "\data\13.csv"
'copyDataFromCsvFileToSheet sPath, ";", "13"

Dim aux As String
aux = FindReplaceAll()

End Sub

Private Sub copyDataFromCsvFileToSheet(parFileName As String, _
parDelimiter As String, parSheetName As String)

    Dim Data As Variant

    Data = getDataFromFile(parFileName, parDelimiter)

If Not isArrayEmpty(Data) Then
  If SheetExists(parSheetName) Then
    With Sheets(parSheetName)
      .Range("A1:OO2000").ClearContents
      .Cells(1, 1).Resize(UBound(Data, 1), UBound(Data, 2)) = Data
    End With
  Else
    Dim warning
    warning = MsgBox("no existing sheet'" & parSheetName, vbOKOnly, "Warning")
  End If
End If
End Sub

 Function SheetExists(shtName As String, Optional wb As Workbook) As Boolean
Dim sht As Worksheet

 If wb Is Nothing Then Set wb = ThisWorkbook
 On Error Resume Next
 Set sht = wb.Sheets(shtName)
 On Error GoTo 0
 SheetExists = Not sht Is Nothing
 End Function

Function FindReplaceAll()

Dim sht As Worksheet
Dim fnd As Variant
Dim rplc As Variant

For Each sht In ActiveWorkbook.Worksheets
  sht.Cells.Replace what:=Chr(34), Replacement:="", _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False
Next sht

End Function

Public Function isArrayEmpty(parArray As Variant) As Boolean

If IsArray(parArray) = False Then isArrayEmpty = True
On Error Resume Next
If UBound(parArray) < LBound(parArray) Then
   isArrayEmpty = True
   Exit Function
    Else
   isArrayEmpty = False
End If

End Function

Private Function getDataFromFile(parFileName As String, _
parDelimiter As String, _
Optional parExcludeCharacter As String = "") As Variant

Dim locLinesList() As Variant
Dim locData As Variant
Dim i As Long
Dim j As Long
Dim lim As Long
Dim locNumRows As Long
Dim locNumCols As Long
Dim fso As Variant
Dim ts As Variant
Const REDIM_STEP = 10000

Set fso = CreateObject("Scripting.FileSystemObject")

On Error GoTo error_open_file

Set ts = fso.OpenTextFile(parFileName)
On Error GoTo unhandled_error

ReDim locLinesList(1 To 1) As Variant
i = 0
Do While Not ts.AtEndOfStream
  Dim aux As String
  aux = ts.ReadLine
  If i Mod REDIM_STEP = 0 Then
    ReDim Preserve locLinesList _
    (1 To UBound(locLinesList, 1) + REDIM_STEP) As Variant
    lim = UBound(Split(aux, parDelimiter)) + 1
  End If
  locLinesList(i + 1) = Split(aux, """+parDelimiter+""")
  j = UBound(locLinesList(i + 1), 1)

  If locNumCols < j Then locNumCols = j
  i = i + 1
Loop

ts.Close
locNumRows = i

If locNumRows = 0 Then Exit Function

ReDim locData(1 To locNumRows, 1 To locNumCols + 1) As Variant

If parExcludeCharacter <> "" Then
  For i = 1 To locNumRows
    For j = 0 To UBound(locLinesList(i), 1)
      If Left(locLinesList(i)(j), 1) = parExcludeCharacter Then
        If Right(locLinesList(i)(j), 1) = parExcludeCharacter Then
      locLinesList(i)(j) = _
      Mid(locLinesList(i)(j), 2, Len(locLinesList(i)(j)) - 2)
    Else
      locLinesList(i)(j) = _
      Right(locLinesList(i)(j), Len(locLinesList(i)(j)) - 1)
    End If
  ElseIf Right(locLinesList(i)(j), 1) = parExcludeCharacter Then
    locLinesList(i)(j) = _
    Left(locLinesList(i)(j), Len(locLinesList(i)(j)) - 1)
  End If
  locData(i, j + 1) = locLinesList(i)(j)
    Next j
  Next i
Else
  For i = 1 To locNumRows
    For j = 0 To UBound(locLinesList(i), 1)
  locData(i, j + 1) = locLinesList(i)(j)
    Next j
  Next i
End If

getDataFromFile = locData

Exit Function

error_open_file:
unhandled_error:

End Function

I want that in the excel to look like when you open the csv in excel.

Body:
This was my solution.

First I added two new functions.

Public Function mergeArrays(arr1 As Variant, arr2 As Variant) As Variant
 Dim i As Integer
 Dim sizeArr1 As Integer
 Dim arr3() As String
 ReDim arr3(UBound(arr1) + UBound(arr2) + 1)

 sizeArr1 = UBound(arr1) + 1
 For i = 0 To UBound(arr1)
     arr3(i) = arr1(i)
 Next i
 For i = 0 To UBound(arr2)
     arr3(i + sizeArr1) = arr2(i)
 Next i
 mergeArrays = arr3

End Function

Public Function DeleteElementAt(inArray As Variant) As Variant
    Dim index As Integer
    Dim aux() As String
    ReDim aux(UBound(inArray) - 1)

    For index = 1 To UBound(inArray)
        aux(index - 1) = inArray(index)
    Next index

    DeleteElementAt = aux
End Function

Also I modified getDataFromFile

Private Function getDataFromFile(parFileName As String, _
parDelimiter As String, _
Optional parExcludeCharacter As String = "") As Variant

Dim locLinesList() As Variant
Dim locData As Variant
Dim linea() As String
Dim i As Long
Dim j As Long
Dim lim As Long
Dim locNumRows As Long
Dim locNumCols As Long
Dim fso As Variant
Dim ts As Variant
Const REDIM_STEP = 10000

Set fso = CreateObject("Scripting.FileSystemObject")

On Error GoTo error_open_file

Set ts = fso.OpenTextFile(parFileName)
On Error GoTo unhandled_error

ReDim locLinesList(1 To 1) As Variant
i = 0
Do While Not ts.AtEndOfStream
  Dim aux As String
  aux = ts.ReadLine
  aux = Replace(aux, Chr(34) & ";" & Chr(34), Chr(34) & "#@#" & Chr(34))
  linea = Split(aux, "#@#")
  If i Mod REDIM_STEP = 0 Then
    ReDim Preserve locLinesList _
    (1 To UBound(locLinesList, 1) + REDIM_STEP) As Variant
    lim = UBound(linea) + 1
    locNumCols = lim
    locLinesList(i + 1) = linea
    i = i + 1
  Else
  locLinesList(i + 1) = linea

    If UBound(locLinesList(i)) + 1 < lim Then
      locLinesList(i)(UBound(locLinesList(i))) = locLinesList(i)
   (UBound(locLinesList(i))) & vbCrLf & linea(0)
  linea = DeleteElementAt(linea)
  locLinesList(i) = mergeArrays(locLinesList(i), linea)
Else
If UBound(linea) + 1 = 1 Then
    locLinesList(i)(UBound(locLinesList(i))) = locLinesList(i)
(UBound(locLinesList(i))) & vbCrLf & linea(0)
 Else
'Linea es un salto de linea a secas
 If UBound(linea) = -1 Then
    locLinesList(i)(UBound(locLinesList(i))) = locLinesList(i)
(UBound(locLinesList(i))) & vbCrLf
     Else
        i = i + 1
     End If
    End If

    End If
  End If
Loop

Dim endVector() As Variant
ReDim endVector(i)
Dim index As Integer

For index = 0 To i - 1
    endVector(index) = locLinesList(index + 1)
Next index

ts.Close
locNumRows = i

If locNumRows = 0 Then Exit Function

ReDim locData(1 To locNumRows, 1 To locNumCols) As Variant

If parExcludeCharacter <> "" Then
  For i = 1 To locNumRows
    For j = 0 To UBound(endVector(i), 1)
      If Left(endVector(i)(j), 1) = parExcludeCharacter Then
        If Right(endVector(i)(j), 1) = parExcludeCharacter Then
          endVector(i)(j) = _
          Mid(endVector(i)(j), 2, Len(endVector(i)(j)) - 2)
        Else
          endVector(i)(j) = _
          Right(endVector(i)(j), Len(endVector(i)(j)) - 1)
        End If
      ElseIf Right(endVector(i)(j), 1) = parExcludeCharacter Then
        endVector(i)(j) = _
        Left(endVector(i)(j), Len(endVector(i)(j)) - 1)
      End If
      locData(i, j + 1) = endVector(i)(j)
    Next j
  Next i
Else
  For i = 0 To locNumRows - 1
    For j = 0 To UBound(endVector(i), 1)
      locData(i + 1, j + 1) = endVector(i)(j)
    Next j
  Next i
End If

getDataFromFile = locData

Exit Function

I know that this code can optimized but for now It works


问:
Run ChromeDrive on WebSphere Application Server(WAS)
I am followinggetting-started  with ChromeDrive and before diving into the code, is it possible to use this component(with Java) on WAS(WebSphere Appliction Server) running on unix/Linux? there some issues or limitions I need to know about?

Thanks.

答: It may be possible, but it seems like a bad idea to depend on WebSphere for a non-interactive test framework. It seems trivial to test the API's they provide in a JSP.</p>


问:
Understanding Example 12 All Permutations of a string from Big O notation - Cracking the Coding Interview
I'm stuck understanding how the author got the complexity of O(n^2 * n!)  of the following procedure which generates all permutation of a string.

```<code>void permutation(String str){
   permutation(str,"");
}
void permutation(String str, String prefix){
  if(str.length()==0){
    System.out.println(prefix);
  } else{
    for(int i=0;i<str.length();i++){
        String rem=str.substring(0,i)+str.substring(i+1);
         permutation(rem,prefix+str.charAt(i));
    }
  }
}
</code>```

答:
The complexity of the method is O(n^2 *n!) because of the else path cost:

First notice that each call to String rem=str.substring(0,i)+str.substring(i+1); is O(n),
 in the else path we compute it n times together with a call to permutation which has complexity T(n-1).

Computing the complexity of this is equivalent to solving: T(n) = n[n+T(n-1)]; n times (the for loop) a work of (n+T(n-1))

Solving this recurrence is not that easy, If I'm not wrong it should boil down to solving:

But let's try to approximate.
Each permutation (base case) represent a node in the recursion tree. This tree has n! leaf. Each leaf has a path to the root of length n. So It is safe to assume there are not more than n*n! nodes in the tree.

This is an upper bound on the number of calls to permutation. Since each of this call costs n then the overall upper bound on the complexity is O(n^2*n!)

Hope this helps.

Body:
I'm stuck understanding how the author got the complexity of O(n^2 * n!)  of the following procedure which generates all permutation of a string.

void permutation(String str){
   permutation(str,"");
}
void permutation(String str, String prefix){
  if(str.length()==0){
    System.out.println(prefix);
  } else{
    for(int i=0;i<str.length();i++){
        String rem=str.substring(0,i)+str.substring(i+1);
         permutation(rem,prefix+str.charAt(i));
    }
  }
}


问:
Cannot change data I get from API, ERROR: Cannot assign to read only property
I get some data via an API call

```<code> getPosts(postRequest: PostRequest): void {
    this._postService.getPosts(postRequest).subscribe(result => {
      const postList = result as PostList
      this.posts = postList.posts
    });
  }
</code>```

the this.posts, contain an array of post objects.
That in this case look like this:

```<code>{
    id: 123
    rating: {
      datetime: 1496782640,
      down:0,
      hot:8061.5151856,
      id:344,
      up:2
    }
}
</code>```

Later I want to change the item

```<code>  incrementVote(post: Post) {
      post.rating.up++;
  }
</code>```

ERROR:

```<code>main-browser.min.js:2 ERROR TypeError: Cannot assign to read only property 'up' of object '[object Object]'
    at PostListComponent.incrementVote (main-browser.min.js:34)
    at PostListComponent.vote (main-browser.min.js:34)
    at Object.handleEvent (main-browser.min.js:54)
    at Object.handleEvent (main-browser.min.js:6)
    at Object.handleEvent (main-browser.min.js:7)
    at dispatchEvent (main-browser.min.js:5)
    at main-browser.min.js:5
    at HTMLButtonElement.<anonymous> (main-browser.min.js:21)
    at ZoneDelegate.invokeTask (main-browser.min.js:67)
    at Object.onInvokeTask (main-browser.min.js:3)
</code>```

Why is the this.posts object read-only?

This suddenly happen seemingly without any changes to the code. I also have the same problem in another project, and then it works if I compile with --aot and not when I compile in dev mode.

How can I fix this? I need to be able to change values from the API. Why does this happen?

PS. The object is also used in the HTML, like so:

```<code> <div class="row" *ngFor="let post of posts; let postIndex = index">
      <div class="col-md-12">

        <app-post [post]="post" [fontSize]="30"></app-post>
</code>```

答:
Ok, try not incrementing but assigning. Such as:

```<code>incrementVote(post: Post) {
      let newVal = post.rating.up + 1;
      post.rating.up = newVal;
  }
</code>```

Maybe the post object has been created with one of these:

Object.defineProperty()

Object.freeze()

Meaning that has been created as a read-only.

Here I found out that replacing the value with another object works. I'm not sure though if it can be applied in your case.

UPDATE:

Another solution would be to actually force the property to be writable, example:

```<code>up: {
    value: 2,
    writable: true
},
</code>```

Body:
I get some data via an API call

 getPosts(postRequest: PostRequest): void {
    this._postService.getPosts(postRequest).subscribe(result => {
      const postList = result as PostList
      this.posts = postList.posts
    });
  }

the this.posts, contain an array of post objects.
That in this case look like this:

{
    id: 123
    rating: {
      datetime: 1496782640,
      down:0,
      hot:8061.5151856,
      id:344,
      up:2
    }
}

Later I want to change the item

  incrementVote(post: Post) {
      post.rating.up++;
  }

ERROR:

main-browser.min.js:2 ERROR TypeError: Cannot assign to read only property 'up' of object '[object Object]'
    at PostListComponent.incrementVote (main-browser.min.js:34)
    at PostListComponent.vote (main-browser.min.js:34)
    at Object.handleEvent (main-browser.min.js:54)
    at Object.handleEvent (main-browser.min.js:6)
    at Object.handleEvent (main-browser.min.js:7)
    at dispatchEvent (main-browser.min.js:5)
    at main-browser.min.js:5
    at HTMLButtonElement.<anonymous> (main-browser.min.js:21)
    at ZoneDelegate.invokeTask (main-browser.min.js:67)
    at Object.onInvokeTask (main-browser.min.js:3)

Why is the this.posts object read-only?

This suddenly happen seemingly without any changes to the code. I also have the same problem in another project, and then it works if I compile with --aot and not when I compile in dev mode.

How can I fix this? I need to be able to change values from the API. Why does this happen?

PS. The object is also used in the HTML, like so:

        <app-post [post]="post" [fontSize]="30"></app-post>

Body:
Ok, try not incrementing but assigning. Such as:

incrementVote(post: Post) {
      let newVal = post.rating.up + 1;
      post.rating.up = newVal;
  }

Maybe the post object has been created with one of these:

Object.defineProperty()

Object.freeze()

Meaning that has been created as a read-only.

Here I found out that replacing the value with another object works. I'm not sure though if it can be applied in your case.

UPDATE:

Another solution would be to actually force the property to be writable, example:

up: {
    value: 2,
    writable: true
},


问:
How to find lantronix devices in the local network by Java.io API
I'm trying to find lantronix devices on a LAN through Java using the Java.io. * API

I need to use an UDP protocol in order to broadcast al pcs in the network by the port 30718. When I broadcast them I'll get a response from the devices on the network.

I need some way to make a UDP broadcast an retrieve the pc's responses on the network.

Thanks in advance.

答:
Solution:</p>

```<code>package testbroadcastudp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

/**
* @since 03-05-2017
* @author jsanchez
*/
public class UDPBroadcastToLantronixDevices {
    public static void main(String[] args){
        //Port 30718 for sent at Lantronix devices
        try (DatagramSocket serverSocket = new DatagramSocket(30718))
        {//30718 50000
            byte[] queryMsg = new byte[4];
            queryMsg[0] = (byte)0x00;
            queryMsg[1] = (byte)0x00;
            queryMsg[2] = (byte)0x00;
            queryMsg[3] = (byte)0xF6;//Dec 246
            String testByte = new String(queryMsg,StandardCharsets.ISO_8859_1);

            serverSocket.setBroadcast(true);
            DatagramPacket datagramPacket = new DatagramPacket(
                queryMsg,
                queryMsg.length,
                InetAddress.getByName("192.168.1.255"),//192.168.1.201
                30718
            );
            //Send broadcast
            serverSocket.send(datagramPacket);
            //Close Broadcast socket to close the 30718 port.
            serverSocket.close();
            //Start the listening from the server
            receive();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static void receive(){
        //Port 30718 for listen Lantronix devices
        try (DatagramSocket clientSocket = new DatagramSocket(30718)) {
            byte[] buffer = new byte[4];

            // Set a timeout of 3000 ms to listen in the server side
            clientSocket.setSoTimeout(3000);
            while (true) {
                DatagramPacket datagramPacket = new DatagramPacket(buffer, 0,             buffer.length);

                /**
                * The receive method will wait for 3000 ms for data.
                * After that, the server will throw a timeout exception.
                */
                clientSocket.receive(datagramPacket);
                System.out.println("Listen on " + datagramPacket.getAddress() + " from " + datagramPacket.getData().toString() + " port " + datagramPacket.getPort());
                String receivedMessage = new String(datagramPacket.getData());
                //Decode to get the 0xF7 or '÷' in the byte[4] for a Lantronix Devices in the LAN
                receivedMessage = new String(datagramPacket.getData(), StandardCharsets.ISO_8859_1);
                System.out.println(receivedMessage);
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Timeout. Client is closing.");
        }
    }
}
</code>```

Body:
Solution:

package testbroadcastudp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

/**
* @since 03-05-2017
* @author jsanchez
*/
public class UDPBroadcastToLantronixDevices {
    public static void main(String[] args){
        //Port 30718 for sent at Lantronix devices
        try (DatagramSocket serverSocket = new DatagramSocket(30718))
        {//30718 50000
            byte[] queryMsg = new byte[4];
            queryMsg[0] = (byte)0x00;
            queryMsg[1] = (byte)0x00;
            queryMsg[2] = (byte)0x00;
            queryMsg[3] = (byte)0xF6;//Dec 246
            String testByte = new String(queryMsg,StandardCharsets.ISO_8859_1);

            serverSocket.setBroadcast(true);
            DatagramPacket datagramPacket = new DatagramPacket(
                queryMsg,
                queryMsg.length,
                InetAddress.getByName("192.168.1.255"),//192.168.1.201
                30718
            );
            //Send broadcast
            serverSocket.send(datagramPacket);
            //Close Broadcast socket to close the 30718 port.
            serverSocket.close();
            //Start the listening from the server
            receive();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static void receive(){
        //Port 30718 for listen Lantronix devices
        try (DatagramSocket clientSocket = new DatagramSocket(30718)) {
            byte[] buffer = new byte[4];

            // Set a timeout of 3000 ms to listen in the server side
            clientSocket.setSoTimeout(3000);
            while (true) {
                DatagramPacket datagramPacket = new DatagramPacket(buffer, 0,             buffer.length);

                /**
                * The receive method will wait for 3000 ms for data.
                * After that, the server will throw a timeout exception.
                */
                clientSocket.receive(datagramPacket);
                System.out.println("Listen on " + datagramPacket.getAddress() + " from " + datagramPacket.getData().toString() + " port " + datagramPacket.getPort());
                String receivedMessage = new String(datagramPacket.getData());
                //Decode to get the 0xF7 or '÷' in the byte[4] for a Lantronix Devices in the LAN
                receivedMessage = new String(datagramPacket.getData(), StandardCharsets.ISO_8859_1);
                System.out.println(receivedMessage);
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Timeout. Client is closing.");
        }
    }
}


问:
Stop PyCharm's completion from replacing word right of the cursor when tab completing
In PyCharm, tab completion replaces the word right of the cursor by default. This happens to me often when I insert some function into existing code. For example, if I want to add a call to foobar around an existing x+1 expression, I would type

which brings up the completion options. The result after tab-completing is

with x having been overwritten. Is there a way to make PyCharm's completion stop removing words right to the cursor?

答:
Have you tried pressing Enter instead of Tab? It should do exactly what you want: put corresponding function after cursor without replacing other code.

By the way, recently other guy was asking how to do opposite thing :)


问:
Making an application run in multiple zones
I am currently revising for exam 70-536. Is there a sample of how to configure an application to run in multiple environments? E.g. intranet and internet.

I can't find a good code sample for this. Anyone have one?

答: I think these exam questions are about CAS. Make sure you understand the concept behind it. You will have to know how to configure the policies for your app, etc.</p>

OwnerDisplayName: GSS

OwnerDisplayName: driAn


问:
How to get data from API using curl?
(I am new to curl and also apigee)

I am trying to get the Body data from API

"https://staging.api.pearson.com/content/scapi/urn:pearson:manifestation:014f333d-ceda-476f-81f2-d3d6c89ace42"

using curl with following command but unable to get any data than fault string

curl "https://staging.api.pearson.com/content/scapi/urn:pearson:manifestation:014f333d-ceda-476f-81f2-d3d6c89ace42"

Error that I am getting is :

```<code>{"fault":{"faultstring":"Failed to resolve API Key variable request.header.x-api key","detail":"errorcode":"steps.oauth.v2.FailedToResolveAPIKey"}}}
</code>```

but when accessing the URL multiple times in Browser, I can able to get JSON data as desired

CURL woking code

```<code>curl "https://staging.api.pearson.com/content/scapi/urn:pearson:manifestation:014f333d-ceda-476f-81f2-d3d6c89ace42" -H "Accept:application/json"  -H "Accept-Encoding:gzip, deflate, sdch, br" -H "Accept-Language:en-US,en;q=0.8 " -H "Connection:keep-alive" -H "Host:staging.api.pearson.com" -H "X-ApiKey:7ij8zrLkCNR9DtAXx3KJ6yutoYnk4SAx" -H "X-PearsonSSOSession:AQIC5wM2LY4Sfczr6fmuhzvfN4dwnpK3c9K8tyduHkwg7sA.*AAJTSQACMDIAAlNLABQtNTk5Nzg3OTI1MTgxNTYxNjE3MAACUzEAAjAx*"
</code>```

Kindly somebody suggest to get JSON data

Sorry I am new to curl and also apigee

Thanks

答: As you said that in the chrome, it is working, on the successful request, you can copy as curl like below

Title: How to get data from API using curl?

Body:
(I am new to curl and also apigee)

I am trying to get the Body data from API

"https://staging.api.pearson.com/content/scapi/urn:pearson:manifestation:014f333d-ceda-476f-81f2-d3d6c89ace42"

using curl with following command but unable to get any data than fault string

curl "https://staging.api.pearson.com/content/scapi/urn:pearson:manifestation:014f333d-ceda-476f-81f2-d3d6c89ace42"

Error that I am getting is :

{"fault":{"faultstring":"Failed to resolve API Key variable request.header.x-api key","detail":"errorcode":"steps.oauth.v2.FailedToResolveAPIKey"}}}

but when accessing the URL multiple times in Browser, I can able to get JSON data as desired

CURL woking code

curl "https://staging.api.pearson.com/content/scapi/urn:pearson:manifestation:014f333d-ceda-476f-81f2-d3d6c89ace42" -H "Accept:application/json"  -H "Accept-Encoding:gzip, deflate, sdch, br" -H "Accept-Language:en-US,en;q=0.8 " -H "Connection:keep-alive" -H "Host:staging.api.pearson.com" -H "X-ApiKey:7ij8zrLkCNR9DtAXx3KJ6yutoYnk4SAx" -H "X-PearsonSSOSession:AQIC5wM2LY4Sfczr6fmuhzvfN4dwnpK3c9K8tyduHkwg7sA.*AAJTSQACMDIAAlNLABQtNTk5Nzg3OTI1MTgxNTYxNjE3MAACUzEAAjAx*"

Kindly somebody suggest to get JSON data

Sorry I am new to curl and also apigee

Thanks


问:
Read and do something
How do I loop through a directory?I'm doing this to spit out predictions in tensorflow for poets.It usually takes in only a single file and spits out its prediction.
I'm planning to give it the entire directory,and save predictions in some text file.Im doing this through the docker interface,im thinking of writing a script which will go through all the files in the directory one by one and store the predictions in some text file.

Any help would be appreciated.

.

答:
I faced a similar issue while writing a code.
The following code will recurse through all the files in the folder(including subfolders as well) given by folder_name.

```<code>import os

with open('prediction.txt','w') as tf_file:
    for dirPath, dirNames, fileNames in os.walk(folder_name):
        for fileName in fileNames:
            results = perform_tensorflow_stuff(fileName)
            tf_file.writelines('\n'.join(results))
</code>```

Hope this helps!

Title: Read and do something

Body:
I faced a similar issue while writing a code.
The following code will recurse through all the files in the folder(including subfolders as well) given by folder_name.

import os

with open('prediction.txt','w') as tf_file:
    for dirPath, dirNames, fileNames in os.walk(folder_name):
        for fileName in fileNames:
            results = perform_tensorflow_stuff(fileName)
            tf_file.writelines('\n'.join(results))

Hope this helps!


问:
GitLab-CI and CD with .NET
I've been trying to wrap my head around how it would be possible to implement Continuous Integration and Continuous Delivery with GitLab CI for .NET web-applications such as ASP.MVC as well as WEB API2 etc.

Unfortunately I have no clue how to jumpstart into this issue and will be therefore very thankful for advices or maybe samples.

答:
This really isn't a question, but if you want advice on where to start with gitlab CI/CD and .net...

install gitlab runner on the appropriate server

setup a gitlab-ci.yml in the root of your repository

use gitlab's Lint to check your .yml to avoid some headaches on syntax

make sure you register your runner with your Gitlab instance

configure your .yml to either use or call cmd commands (or scripts)
https://docs.gitlab.com/ce/ci/yaml/

setup some 'environments if you think they'd work for you
https://docs.gitlab.com/ce/ci/environments.html

here is a sample .net .yml I made
GitLab CI. Path in yml for different users

Title: GitLab-CI and CD with .NET


问:
How to sum value of two json object key?
```<code>"bills": [
    {
        "refNo": 17,
        "billDate": "1-apr-2016",
        "dueDate": "30-apr-2016",
        "pendingAmount": 4500,
        "overdueDays": 28
    },
    {
        "refNo": 20,
        "billDate": "15-apr-2016",
        "dueDate": "3-may-2016",
        "pendingAmount": 56550,
        "overdueDays": 15
    }
]
</code>```

I want to sum "pendingAmount" field.
It should be return like pendingAmount: 61050

答:
A one-liner with some ES2015 destructuring:</p>

```<code>json.bills.reduce(({pendingAmount: a}, {pendingAmount: b})=> a+b)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
"bills": [
    {
        "refNo": 17,
        "billDate": "1-apr-2016",
        "dueDate": "30-apr-2016",
        "pendingAmount": 4500,
        "overdueDays": 28
    },
    {
        "refNo": 20,
        "billDate": "15-apr-2016",
        "dueDate": "3-may-2016",
        "pendingAmount": 56550,
        "overdueDays": 15
    }
]

I want to sum "pendingAmount" field.
It should be return like pendingAmount: 61050

Body:
A one-liner with some ES2015 destructuring:

json.bills.reduce(({pendingAmount: a}, {pendingAmount: b})=> a+b)


问:
How to hash some String with SHA-256 in Java?
How can I hash some String with SHA-256 in Java?

答:
You can use MessageDigest in the following way:</p>

```<code>public static String getSHA256(String data){
    StringBuffer sb = new StringBuffer();
    try{
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(data.getBytes());
        byte byteData[] = md.digest();

        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
    } catch(Exception e){
        e.printStackTrace();
    }
    return sb.toString();
}
</code>```

Body:
You can use MessageDigest in the following way:

public static String getSHA256(String data){
    StringBuffer sb = new StringBuffer();
    try{
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(data.getBytes());
        byte byteData[] = md.digest();

        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
    } catch(Exception e){
        e.printStackTrace();
    }
    return sb.toString();
}


问:
Executing an EXE in your $PATH, which starts with a numeric value, in Powershell?
So 7z.exe is in my $PATH environment variable.

```<code>PS C:\Users\jimmeh> 7z.exe
Bad numeric constant: 7.
At line:1 char:2
+ 7 <<<< z.exe
    + CategoryInfo          : ParserError: (7:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : BadNumericConstant
</code>```

Besides renaming the EXE, is there a way to do this, or is it a bug in Powershell?

答:
It work like

```<code>& '.\7z.exe'
</code>```

if you want to specify an archive to extract

& '.\7z.exe' e your.zip

Body:
So 7z.exe is in my $PATH environment variable.

PS C:\Users\jimmeh> 7z.exe
Bad numeric constant: 7.
At line:1 char:2
+ 7 <<<< z.exe
    + CategoryInfo          : ParserError: (7:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : BadNumericConstant

Besides renaming the EXE, is there a way to do this, or is it a bug in Powershell?

Body:
It work like

& '.\7z.exe'

if you want to specify an archive to extract

& '.\7z.exe' e your.zip


问:
How to run a .bat (that runs an .exe that is in the same directory) as administrator from a pendrive?
I'm able to run a .bat (that runs an .exe that is in the same directory) as administrator: I right-click in the bat file and select "Run as administrator".

To be able to do that, I used the following answer: Run exe from current directory in batch

Here's the code:

@echo off
:A
cls
echo This will start the program.
pause
cd %~dp0
start %1myprogram.exe
exit

However, this will only work if the .bat file and the program are in the system drive.

Because if they are, for instance, in a pendrive, and I right-click and select "Run as Administrator", I get the error:

"Windows cannot find 'myprogram.exe'. Make sure you've typed the name correctly, then try again."

Why this happens and how can I fix it?
I thought that by using cd %~dp0 it would always point to the folder in which the bat .file resides.

Thanks in advance.

答:
Solution

Change cd %~dp0 to cd /d %~dp0

Explanation

When you run something with administrator privileges, the working directory changes to:

'C:\Windows\System32'

Although %~dp0 still points to the drive and the directory containing the batch file, cd %~dp0 does not work, because it only changes the directory, but stays on the same drive.

Using the /d parameter, you can tell the cd-command to change the drive, too.


问:
Phonegap Application text and layout too small
I recently build an android app using html, css, javascript and running them through phonegap to create the actual app. One of the problems I encountered in one phone is that the text looks too small. Also some images are a little small as well. I added a viewport meta tag but it doesnt seem to work either. Here are the meta tags:

```<code>    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi" />`
</code>```

This is how it looks

This is how its supposed to look:

答:
Updated answer: for Android

The problem is on Android devices has this Accessibilly settings, You can try to change font-size (search font size on android setting) and run you app again.

So your fonts on app will be changed as your setting

So here is a solution for Cordova

Use : mobile-accessibility to disabling PreferredTextZoom

Install mobile-accessibility on your Cordova project

```<code>$ cordova plugin add https://github.com/phonegap/phonegap-mobile-accessibility.git
</code>```

And JS part is something like :

```<code>document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
   if (window.MobileAccessibility) {
      window.MobileAccessibility.usePreferredTextZoom(false);
   }
}
</code>```

Body:
I recently build an android app using html, css, javascript and running them through phonegap to create the actual app. One of the problems I encountered in one phone is that the text looks too small. Also some images are a little small as well. I added a viewport meta tag but it doesnt seem to work either. Here are the meta tags:

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi" />`

This is how it looks

This is how its supposed to look:

Body:
Updated answer: for Android

The problem is on Android devices has this Accessibilly settings, You can try to change font-size (search font size on android setting) and run you app again.

So your fonts on app will be changed as your setting

So here is a solution for Cordova

Use : mobile-accessibility to disabling PreferredTextZoom

Install mobile-accessibility on your Cordova project

$ cordova plugin add https://github.com/phonegap/phonegap-mobile-accessibility.git

And JS part is something like :

document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
   if (window.MobileAccessibility) {
      window.MobileAccessibility.usePreferredTextZoom(false);
   }
}


问:
I'm trying to make a function (button) to upload images to my database in CodeIgniter (PHP). But I'm getting an error
I'm trying to make a function in CodeIgniter (PHP) so users can add images to my database but I'm getting an error when I try to upload an image..

I'm using phpMyAdmin

Database name: kadokado

Table name: products

Table row name where i want to put these images to: product_foto

image folder: upload

My controller file (Product.php):

```<code>    class Product extends CI_Controller {

    var $data = array();

       public function __construct()
 {
  parent::__construct();
 }

}

     public function index()
 {
  $config = array (
   'upload_path' => 'upload/',
   'allowed_types' => 'jpg|jpeg|png|bmp',
   'max_size' => 0,
   'filename' => url_title($this->input->post('file'))

   );
   $this->load->library('upload', $config);

   if ($this->upload->do_upload('file')) {
    $this->db->insert('products', array(
        'product_foto' => $this->upload->product_foto
     ));
     $this->session->set_flashdata('msg', 'Success');
   }

  $this->load->view('product_form', $this->data);
 }
</code>```

}

This is my view file (product_form.php) :

```<code><?php
echo $this->session->flashdata('msg');
echo form_open_multipart();
echo form_upload('file');
echo form_submit('upload', 'Upload');
echo form_close();
?>
</code>```

And these are the errors I'm getting:`

```<code>  A PHP Error was encountered

Severity: Notice

Message: Undefined property: CI_Upload::$product_foto

Filename: controllers/Product.php

Line Number: 21

Backtrace:

File: /home/ubuntu/workspace/application/controllers/Product.php
Line: 21
Function: _error_handler

File: /home/ubuntu/workspace/index.php
Line: 315
Function: require_once

A Database Error Occurred

Error Number: 1048

Column 'product_foto' cannot be null

INSERT INTO `products` (`product_foto`) VALUES (NULL)

Filename: controllers/Product.php

Line Number: 22
</code>```

答:
change </p>

```<code>if ($this->upload->do_upload('file')) {
    $this->db->insert('products', array(
        'product_foto' => $this->upload->product_foto
     ));
     $this->session->set_flashdata('msg', 'Success');
   }
</code>```

<p>to </p>

```<code> if ($this->upload->do_upload('file')) {
    $this->db->insert('products', array(
        'product_foto' => $this->upload->data['file_name']
     ));
     $this->session->set_flashdata('msg', 'Success');
   }
</code>```

Body:
I'm trying to make a function in CodeIgniter (PHP) so users can add images to my database but I'm getting an error when I try to upload an image..

I'm using phpMyAdmin

Database name: kadokado

Table name: products

Table row name where i want to put these images to: product_foto

image folder: upload

My controller file (Product.php):

    class Product extends CI_Controller {

    var $data = array();

       public function __construct()
 {
  parent::__construct();
 }

}

     public function index()
 {
  $config = array (
   'upload_path' => 'upload/',
   'allowed_types' => 'jpg|jpeg|png|bmp',
   'max_size' => 0,
   'filename' => url_title($this->input->post('file'))

   );
   $this->load->library('upload', $config);

   if ($this->upload->do_upload('file')) {
    $this->db->insert('products', array(
        'product_foto' => $this->upload->product_foto
     ));
     $this->session->set_flashdata('msg', 'Success');
   }

  $this->load->view('product_form', $this->data);
 }

}

This is my view file (product_form.php) :

<?php
echo $this->session->flashdata('msg');
echo form_open_multipart();
echo form_upload('file');
echo form_submit('upload', 'Upload');
echo form_close();
?>

And these are the errors I'm getting:`

  A PHP Error was encountered

Severity: Notice

Message: Undefined property: CI_Upload::$product_foto

Filename: controllers/Product.php

Line Number: 21

Backtrace:

File: /home/ubuntu/workspace/application/controllers/Product.php
Line: 21
Function: _error_handler

File: /home/ubuntu/workspace/index.php
Line: 315
Function: require_once

A Database Error Occurred

Error Number: 1048

Column 'product_foto' cannot be null

INSERT INTO `products` (`product_foto`) VALUES (NULL)

Filename: controllers/Product.php

Line Number: 22

Body:
change

if ($this->upload->do_upload('file')) {
    $this->db->insert('products', array(
        'product_foto' => $this->upload->product_foto
     ));
     $this->session->set_flashdata('msg', 'Success');
   }

to

 if ($this->upload->do_upload('file')) {
    $this->db->insert('products', array(
        'product_foto' => $this->upload->data['file_name']
     ));
     $this->session->set_flashdata('msg', 'Success');
   }


答:
You may need to tell cd to also change drives:</p>

```<code>cd /d %~dp0
</code>```

Title: How to run a .bat (that runs an .exe that is in the same directory) as administrator from a pendrive?

Body:
I'm able to run a .bat (that runs an .exe that is in the same directory) as administrator: I right-click in the bat file and select "Run as administrator".

To be able to do that, I used the following answer: Run exe from current directory in batch

Here's the code:

@echo off
:A
cls
echo This will start the program.
pause
cd %~dp0
start %1myprogram.exe
exit

However, this will only work if the .bat file and the program are in the system drive.

Because if they are, for instance, in a pendrive, and I right-click and select "Run as Administrator", I get the error:

"Windows cannot find 'myprogram.exe'. Make sure you've typed the name correctly, then try again."

Why this happens and how can I fix it?
I thought that by using cd %~dp0 it would always point to the folder in which the bat .file resides.

Thanks in advance.

Body:
You may need to tell cd to also change drives:

cd /d %~dp0


问:
Discover if a variable is a number
Is there a Way To compare nan with a variable?I need this To understand if a variable is a number or Not without using javascript's functions.</p>

答:
You can always test if a value is NaN by checking it for equality to itself:

var foo = NaN;
console.log(foo !== foo); // true

var bar = 4;
console.log(bar !== bar); // false ```
</div>
</div>
</p>

<p>There is a note for this in the ECMAScript specs.</p>

<p>Based on comments, I want to offer such function to detect if variable is a number: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function isNum (candidate) {
  return +(candidate) === +(candidate) && //check for NaN with conversion
          candidate !== (candidate / 0) && //check for Infinity
          candidate !== '' && candidate !== null; //check for empty string and null, since +'' and +null will return 0
}

//returns false
console.log(isNum({ foo: 1 }));
console.log(isNum(''));
console.log(isNum(NaN));
console.log(isNum(undefined));
console.log(isNum(null));
console.log(isNum(Infinity));
console.log(isNum("foo1"));
console.log(isNum([1, 2, 3]));

console.log("------------------------------------------------------------------");

//returns true
console.log(isNum(9999999999));
console.log(isNum(.23));
console.log(isNum(0));
console.log(isNum(1e+30));

//will treat this also as number, since it could be easily converted
//typeof +"112233" === "number"
console.log(isNum("112233"));
//but still you can modify this method to use
//typeof candidate === "string" or (candidate).constructor === String</code>```

Would be great to hear your comments/suggestions.

Title: Discover if a variable is a number

Body:
You can always test if a value is NaN by checking it for equality to itself:

var foo = NaN;
console.log(foo !== foo); // true

var bar = 4;
console.log(bar !== bar); // false

There is a note for this in the ECMAScript specs.

Based on comments, I want to offer such function to detect if variable is a number:

function isNum (candidate) {
  return +(candidate) === +(candidate) && //check for NaN with conversion
          candidate !== (candidate / 0) && //check for Infinity
          candidate !== '' && candidate !== null; //check for empty string and null, since +'' and +null will return 0
}

//returns false
console.log(isNum({ foo: 1 }));
console.log(isNum(''));
console.log(isNum(NaN));
console.log(isNum(undefined));
console.log(isNum(null));
console.log(isNum(Infinity));
console.log(isNum("foo1"));
console.log(isNum([1, 2, 3]));

console.log("------------------------------------------------------------------");

//returns true
console.log(isNum(9999999999));
console.log(isNum(.23));
console.log(isNum(0));
console.log(isNum(1e+30));

//will treat this also as number, since it could be easily converted
//typeof +"112233" === "number"
console.log(isNum("112233"));
//but still you can modify this method to use
//typeof candidate === "string" or (candidate).constructor === String

Would be great to hear your comments/suggestions.


问:
How to check if multiple records exist on database (laravel doctrine)
I want to confirm whether a collection of users exist on the database. So, say I have an array:

```<code>$data = [
    [
        'firstName' => 'Alastair',
        'lastName' => 'Appleby'
    ],
    [
        'firstName' => 'Celine',
        'lastName' => 'Wilkinson'
    ]
];
</code>```

I want to return those two users, if they exist. I can't seem to figure out an efficient way of doing this effectively. I tried running a native query, but that returned nothing and I think it's because of the way I've bound the parameters. My attempt:

```<code>    $where = [];
    $params = [];

    foreach($data as $n => $u) {
        $where[] = '(first_name = ? AND last_name = ?)';
        $params[$n + $n + 1] = $u['firstName'];
        $params[$n + $n + 2] = $u['lastName'];
    }

    $where = implode(' OR ', $where);

    $query = "SELECT * FROM users WHERE $where";

    $q = $this->em->createNativeQuery($query, new ResultSetMapping());
    $q->setParameters($params);

    return $q->getArrayResult();
</code>```

答:
You need to use the query builder expression methods, like so;</p>

```<code>$qb = $this->em->createQueryBuilder();

$where = [];
$params = [];

$qb->select('u')
    ->from(User::class, 'u');

foreach($data as $n => $u) {
    $where[] = $qb->expr()->andX(
        $qb->expr()->eq('u.firstName', ":firstName$n"),
        $qb->expr()->eq('u.lastName', ":lastName$n")
    );

    $params["firstName$n"] = $u['firstName'];
    $params["lastName$n"] = $u['lastName'];
    }

$qb->where($qb->expr()->orX(
    $where
))->setParameters($params);

return $qb->getQuery()->getArrayResult();
</code>```

Body:
I want to confirm whether a collection of users exist on the database. So, say I have an array:

$data = [
    [
        'firstName' => 'Alastair',
        'lastName' => 'Appleby'
    ],
    [
        'firstName' => 'Celine',
        'lastName' => 'Wilkinson'
    ]
];

I want to return those two users, if they exist. I can't seem to figure out an efficient way of doing this effectively. I tried running a native query, but that returned nothing and I think it's because of the way I've bound the parameters. My attempt:

    $where = [];
    $params = [];

    foreach($data as $n => $u) {
        $where[] = '(first_name = ? AND last_name = ?)';
        $params[$n + $n + 1] = $u['firstName'];
        $params[$n + $n + 2] = $u['lastName'];
    }

    $where = implode(' OR ', $where);

    $query = "SELECT * FROM users WHERE $where";

    $q = $this->em->createNativeQuery($query, new ResultSetMapping());
    $q->setParameters($params);

    return $q->getArrayResult();

Body:
You need to use the query builder expression methods, like so;

$qb = $this->em->createQueryBuilder();

$where = [];
$params = [];

$qb->select('u')
    ->from(User::class, 'u');

foreach($data as $n => $u) {
    $where[] = $qb->expr()->andX(
        $qb->expr()->eq('u.firstName', ":firstName$n"),
        $qb->expr()->eq('u.lastName', ":lastName$n")
    );

    $params["firstName$n"] = $u['firstName'];
    $params["lastName$n"] = $u['lastName'];
    }

$qb->where($qb->expr()->orX(
    $where
))->setParameters($params);

return $qb->getQuery()->getArrayResult();


问:
powershell log - new file every day
I log network status (nslookup, ping, tracert) into a log file. The log file size grows and is quite difficult to work with after a while.

I am looking for a way to have a new log file created for every day. I am sure it's easy but I did not find a way.

When I set log file name to $log_file = ".\network_" + (Get-Date -f yyyy-MM-dd) + ".log" hoping it will create a new file when date changes, it does not work. Instead I get Non-authoritative answer:.

Sorry for newbie question but I really did not find any answer. Thx!

edit:

it's really simple script (shortened example below):

```<code>$log_file = ".\network_" + (Get-Date -f yyyy-MM-dd_HH-mm) + ".log"
$server = "server.com"
$gateway = (Get-wmiObject Win32_networkAdapterConfiguration | ?{$_.IPEnabled}).DefaultIPGateway
& ipconfig /all >> $log_file

while($true) {
$timestamp = "rnrn[" + (Get-Date -f yyyy-MM-dd) + " " +(Get-Date -f HH:mm:ss) + "]"
$timestamp >> $log_file
"rnrn" >> $log_file
"ping to $server)" >> $log_file
& ping $server >> $log_file
}
</code>```

答:
Here's what I usually do. </p>

```<code>$Date = get-date -format yyyy-MM-dd
$log_file = "\\Share\folder\folder\FileName-$date.log"
</code>```

Title: powershell log - new file every day

Body:
I log network status (nslookup, ping, tracert) into a log file. The log file size grows and is quite difficult to work with after a while.

I am looking for a way to have a new log file created for every day. I am sure it's easy but I did not find a way.

When I set log file name to $log_file = ".\network_" + (Get-Date -f yyyy-MM-dd) + ".log" hoping it will create a new file when date changes, it does not work. Instead I get Non-authoritative answer:.

Sorry for newbie question but I really did not find any answer. Thx!

edit:

it's really simple script (shortened example below):

$log_file = ".\network_" + (Get-Date -f yyyy-MM-dd_HH-mm) + ".log"
$server = "server.com"
$gateway = (Get-wmiObject Win32_networkAdapterConfiguration | ?{$_.IPEnabled}).DefaultIPGateway
& ipconfig /all >> $log_file

while($true) {
$timestamp = "rnrn[" + (Get-Date -f yyyy-MM-dd) + " " +(Get-Date -f HH:mm:ss) + "]"
$timestamp >> $log_file
"rnrn" >> $log_file
"ping to $server)" >> $log_file
& ping $server >> $log_file
}

Body:
Here's what I usually do.

$Date = get-date -format yyyy-MM-dd
$log_file = "\\Share\folder\folder\FileName-$date.log"