问:
What is this "fixing the build scripts" for compiling x264?
I am trying to compile an all static build of source-customized ffmpeg libraries with the additional codecs from VideoLAN, such as their x264 codec. I am ultimately building for use in Windows with Visual Studio 2015 C++, so I am comparing a few compiling guides for my instructions.

In the guide linked below (I located via Google searches) shows how to compile x264 with the VS2015 toolchain in MSYS2 without any special steps:
https://gist.github.com/RangelReale/3e6392289d8ba1a52b6e70cdd7e10282

While in this other guide, offered by the compiling guide pages from ffmpeg's web site, it includes steps for "fixing the build scripts" for x264:
https://www.roxlu.com/2019/062/compiling-ffmpeg-with-x264-on-windows-10-using-msvc

Problem being, when I "fix the build scripts" the configure script no longer finds a C compiler. Building with the first guide seems to work, but it was also written nearly 2 years ago, so perhaps the ffmpeg guide is doing some important fix? I don't know.

I am:

Running a "VS2015 x64 Native Tools Command Prompt"

launching a pacman loaded msys2 shell via "msys2_shell.cmd -mingw64 -use-full-path"

git cloning http://git.videolan.org/git/x264.git

and at this point the two compiling guides vary, the first guide just cd's into x264 and runs configure while the other guide does some curl download of a config.guess file and then some sed manipulation of ./configure. Considering these instructions are "endorsed" by the ffmpeg site, I am left wondering what that is doing and how critical is it that these "special" steps cause my x264 configure to fail.

答: All this manipulations with "config.guess" and "configure" are only needed because later on they run simple "msys2_shell.cmd" i.e. in MSYS-mode. Correct/supported way in x264 is to run shell in MINGW32 or MINGW64 mode with "-mingw32" and "-mingw64" options like you do (or run mingw32.exe / mingw64.exe instead of msys2_shell.cmd). This change result in different output of "uname" command which is important for x264's configure.</p>


来源: stackexchange

问:
How to unzip cifar10/100 database manually?
i want to train my neural network with cifar10 dataset. i have both datasets on my harddrive and i can unzip the folder and import the bash files, but i want a solution for the import of these data i can understand and learn it!

have anyone a simple, for a newbie "learnable" piece of code ?
you can also explain me line by line what this code does and pls like you speking with a 6 year old child :D

```<code>import pickle
import sys
from keras import backend as K
from keras.utils import to_categorical

def load_batch(fpath, label_key='labels'):

with open(fpath, 'rb') as f:
    if sys.version_info < (3,):
        d = pickle.load(f)
    else:
        d = pickle.load(f, encoding='bytes')
        # decode utf8
        d_decoded = {}
        for k, v in d.items():
            d_decoded[k.decode('utf8')] = v
        d = d_decoded
data = d['data']
labels = d[label_key]

data = data.reshape(data.shape[0], 3, 32, 32)
return data, labels

 def load_data():

path = 'cifar-10-batches-py'

num_train_samples = 50000

x_train_local = np.empty((num_train_samples, 3, 32, 32), dtype='uint8')
y_train_local = np.empty((num_train_samples,), dtype='uint8')

for i in range(1, 6):
    fpath = os.path.join(path, 'data_batch_' + str(i))
    (x_train_local[(i - 1) * 10000: i * 10000, :, :, :],
     y_train_local[(i - 1) * 10000: i * 10000]) = load_batch(fpath)

fpath = os.path.join(path, 'test_batch')
x_test_local, y_test_local = load_batch(fpath)

y_train_local = np.reshape(y_train_local, (len(y_train_local), 1))
y_test_local = np.reshape(y_test_local, (len(y_test_local), 1))

if K.image_data_format() == 'channels_last':
    x_train_local = x_train_local.transpose(0, 2, 3, 1)
    x_test_local = x_test_local.transpose(0, 2, 3, 1)

return (x_train_local, y_train_local), (x_test_local, y_test_local)

  (x_train, x_label), (y_train, y_label) = load_data()
  print('x_train shape:', x_train.shape)
  print('y_train shape:', y_train.shape)
  print(x_train.shape[0], 'train samples')
  print(x_test.shape[0], 'test samples')

  x_label = to_categorical(x_label)
  y_label = to_categorical(y_label)
</code>```

答:
You have the files on your hard drive. Go to that folder, open up a terminal there. Start with from glob import glob. Use glob to get the name of all files. Then, use OpenCV for reading the files using cv2.imread. Then, use numpy to get means, and other things. For viewing the files use:

```<code>import matplotlib.pyplot as plt

plt.imshow(file_object_you_get_from_opencv)
plt.show()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i want to train my neural network with cifar10 dataset. i have both datasets on my harddrive and i can unzip the folder and import the bash files, but i want a solution for the import of these data i can understand and learn it!

have anyone a simple, for a newbie "learnable" piece of code ?
you can also explain me line by line what this code does and pls like you speking with a 6 year old child :D

import pickle
import sys
from keras import backend as K
from keras.utils import to_categorical

def load_batch(fpath, label_key='labels'):

with open(fpath, 'rb') as f:
    if sys.version_info < (3,):
        d = pickle.load(f)
    else:
        d = pickle.load(f, encoding='bytes')
        # decode utf8
        d_decoded = {}
        for k, v in d.items():
            d_decoded[k.decode('utf8')] = v
        d = d_decoded
data = d['data']
labels = d[label_key]

data = data.reshape(data.shape[0], 3, 32, 32)
return data, labels

 def load_data():

path = 'cifar-10-batches-py'

num_train_samples = 50000

x_train_local = np.empty((num_train_samples, 3, 32, 32), dtype='uint8')
y_train_local = np.empty((num_train_samples,), dtype='uint8')

for i in range(1, 6):
    fpath = os.path.join(path, 'data_batch_' + str(i))
    (x_train_local[(i - 1) * 10000: i * 10000, :, :, :],
     y_train_local[(i - 1) * 10000: i * 10000]) = load_batch(fpath)

fpath = os.path.join(path, 'test_batch')
x_test_local, y_test_local = load_batch(fpath)

y_train_local = np.reshape(y_train_local, (len(y_train_local), 1))
y_test_local = np.reshape(y_test_local, (len(y_test_local), 1))

if K.image_data_format() == 'channels_last':
    x_train_local = x_train_local.transpose(0, 2, 3, 1)
    x_test_local = x_test_local.transpose(0, 2, 3, 1)

return (x_train_local, y_train_local), (x_test_local, y_test_local)

  (x_train, x_label), (y_train, y_label) = load_data()
  print('x_train shape:', x_train.shape)
  print('y_train shape:', y_train.shape)
  print(x_train.shape[0], 'train samples')
  print(x_test.shape[0], 'test samples')

  x_label = to_categorical(x_label)
  y_label = to_categorical(y_label)

Body:
You have the files on your hard drive. Go to that folder, open up a terminal there. Start with from glob import glob. Use glob to get the name of all files. Then, use OpenCV for reading the files using cv2.imread. Then, use numpy to get means, and other things. For viewing the files use:

import matplotlib.pyplot as plt

plt.imshow(file_object_you_get_from_opencv)
plt.show()


问:
what is the purpose of using this parameter, int (*cmp) (void*, void*)
in my homework ı couldn't understand this parameter ;

```<code>set_maker(LINKEDSTACK stack, int (*cmp) (void*, void*))
</code>```

can anybody explain this using?

thank you for helping.

答:
In C such functions like bsearch and qsort that deal with ordered sequences need a function that will compare elements of arrays.

A pointer to such a function is declared like

```<code>int ( *cmp )( const void *, const void * )
</code>```

It accepts as arguments pointers to two objects that will be compared. Within the function the pointers after casting to the required type are dereferenced and the pointed objects are compared.

The function shall return an integer less than, equal to, or greater than zero if the first pointed object is considered, respectively, to be less than, to match, or to be greater than the second pointed object.

It seems that the function set_maker uses within its body such a comparison function to make comparison between two objects for example for ordering them.

.

Body:
in my homework ı couldn't understand this parameter ;

set_maker(LINKEDSTACK stack, int (*cmp) (void*, void*))

can anybody explain this using?

thank you for helping.

Body:
In C such functions like bsearch and qsort that deal with ordered sequences need a function that will compare elements of arrays.

A pointer to such a function is declared like

int ( *cmp )( const void *, const void * )

It accepts as arguments pointers to two objects that will be compared. Within the function the pointers after casting to the required type are dereferenced and the pointed objects are compared.

The function shall return an integer less than, equal to, or greater than zero if the first pointed object is considered, respectively, to be less than, to match, or to be greater than the second pointed object.

It seems that the function set_maker uses within its body such a comparison function to make comparison between two objects for example for ordering them.

.


问:
How to add a file extension to file without any
so I've downloaded a few blank HTML files with no file extensions.

(I know these are HTML because if I manually add .HTML to the end and open the file, / the file contains html elements.... like  etc.)

So they're located in my downloads folder. I'm simply trying to add a file extension to each of these files in the dir folder "download".

Here's my code:

```<code>var fs = require('fs');
var files = fs.readdirSync('C:/Users/Nikki/Downloads').forEach(file => {
    console.log(file);

    //There is a file named "desktop.ini", skip this file.
    if (file === "desktop.ini") {
        console.log("desktop file")
    } else {

    //not sure why it doesn't change the file extension. Maybe because there is none!?
    var replaceExt = require('replace-ext');

    var path = 'C:/Users/Nikki/Downloads/' + file;
    var newPath = replaceExt(path, '.html');

    console.log(newPath);

}

/*
fs.rename(file, file+'.html', () => {
    console.log("\nFile Renamed!\n");

// doesnt work... either...
});
*/
});
</code>```

How can I add the HTML file extension to each of these files?

答:
If your file doesn't have a file extension, you can try the following code snippet :</p>

```<code>var pos = file.lastIndexOf(".");
file = file.substr(0, pos < 0 ? file.length : pos) + ".html";
</code>```

Body:
so I've downloaded a few blank HTML files with no file extensions.

(I know these are HTML because if I manually add .HTML to the end and open the file, / the file contains html elements.... like  etc.)

So they're located in my downloads folder. I'm simply trying to add a file extension to each of these files in the dir folder "download".

Here's my code:

var fs = require('fs');
var files = fs.readdirSync('C:/Users/Nikki/Downloads').forEach(file => {
    console.log(file);

    //There is a file named "desktop.ini", skip this file.
    if (file === "desktop.ini") {
        console.log("desktop file")
    } else {

    //not sure why it doesn't change the file extension. Maybe because there is none!?
    var replaceExt = require('replace-ext');

    var path = 'C:/Users/Nikki/Downloads/' + file;
    var newPath = replaceExt(path, '.html');

    console.log(newPath);

}

/*
fs.rename(file, file+'.html', () => {
    console.log("\nFile Renamed!\n");

// doesnt work... either...
});
*/
});

How can I add the HTML file extension to each of these files?

Body:
If your file doesn't have a file extension, you can try the following code snippet :

var pos = file.lastIndexOf(".");
file = file.substr(0, pos < 0 ? file.length : pos) + ".html";


问:
What is the point of Node.js
Ok this is probably a little blunt and to the point, but what is the point/need for Node.js

I've noticed it mainly through CloudFoundry but just not too sure what its supposed to be doing. However I am guessing its probably something pretty big as why else would VMWare be supporting it.

Thanks in advance.

答:
This post might help:

Why Developers Should Pay Attention to Node.js

ContentLicense: CC BY-SA 3.0

Title: What is the point of Node.js


问:
Checking whether a number is prime in Scala
I wanted to check if a number is prime or not. I wrote the following code, but it does not return any value:</p>

```<code> def isprime(x:Int) = {
     | if (x==1) false
     | else {
     | for (i <- 2 to x-1) {
     | if (x % i == 0) false
     | else true
     | }
     | }
     | }
</code>```

答:
That works fine for negative numbers and big numbers too.
Prime numbers start from  2, 3, 5, ...

```<code>def isPrime(n: Int): Boolean = (n > 1) && ! Range(2, n-1).exists(n % _ == 0)
</code>```

Also

```<code>@tailrec
def isPrime(n: Int): Boolean = {
   def isPrimeTailrec(divisor: Int): Boolean = {
     if(divisor > Math.sqrt(Math.abs(n))) true
       else n % divisor != 0 && isPrimeTailrec(divisor + 1)
     }
     if(n < 2) false
     else isPrimeTailrec(2)
   }
}
</code>```

Body:
I wanted to check if a number is prime or not. I wrote the following code, but it does not return any value:

 def isprime(x:Int) = {
     | if (x==1) false
     | else {
     | for (i <- 2 to x-1) {
     | if (x % i == 0) false
     | else true
     | }
     | }
     | }

Body:
That works fine for negative numbers and big numbers too.
Prime numbers start from  2, 3, 5, ...

def isPrime(n: Int): Boolean = (n > 1) && ! Range(2, n-1).exists(n % _ == 0)

Also

@tailrec
def isPrime(n: Int): Boolean = {
   def isPrimeTailrec(divisor: Int): Boolean = {
     if(divisor > Math.sqrt(Math.abs(n))) true
       else n % divisor != 0 && isPrimeTailrec(divisor + 1)
     }
     if(n < 2) false
     else isPrimeTailrec(2)
   }
}


问:
How does enable_if help select specializations of a class template?
I have a basic grasp of SFINAE, and I think I understand many of the examples of how std::enable_if exploits it to select function template specializations, but I'm having a hard time wrapping my head around how it works for class templates.

The following example is from cppreference.com's explanation of std::enable_if:

template<class T, class Enable = void>
class A {}; // primary template

template<class T>
class A<T, typename std::enable_if<std::is_floating_point<T>::value>::type> {
}; // specialization for floating point types
```

I'm having trouble understanding how using std::enable_if in this way helps select the specialization.  (I don't doubt that it does.)

When the compiler sees a declaration like A<float> specialized;, it will see two possible template instantiations that fit:

The "primary template" A<T, Enable> where T is the type float and Enable is the type void (because of the default value).

The specialization A<T, void> where T is the type float and void is the result of the expression with the enable_if.

Aren't those ambiguous?  Both effectively result in A<T, void>, so why is the specialization chosen?

In a different case, like A<int> primary;, the options to the compiler seem to be:

The primary, A<T, Enable>, where T is the type int and Enable is the type void.

The specialization, A<T, ?>, where T is the type int and the ? represents where I'm completely lost.  In this case, the enable_if condition is false, so it doesn't define type, which leaves you with A<int, typename >.  Isn't that a syntax error?  Even in the face of SFINAE?

答:
Aren't those ambiguous? Both effectively result in A<T, void>, so why is the specialization chosen?

No, the specialization is more specialized than the primary template, because it requires the second parameter to be void (assuming the enable_if condition is true), while the primary template doesn't restrict it.

The specialization, A<T, ?>, where T is the type int and the ? represents where I'm completely lost. In this case, the enable_if condition is false, so it doesn't define type, which leaves you with A<int, typename >. Isn't that a syntax error? Even in the face of SFINAE?

Exactly, the second argument in the specialization turns out invalid. But this is a "soft" error, which is detected by SFINAE and makes the compiler discard the specialization. (I don't think a compiler would textually replace enable_if_t<...>::type with an empty string and then analyze A<int, typename >; more likely it would discard the specialization as soon as it notices the lack of ::type in enable_if.)

Body:
I have a basic grasp of SFINAE, and I think I understand many of the examples of how std::enable_if exploits it to select function template specializations, but I'm having a hard time wrapping my head around how it works for class templates.

The following example is from cppreference.com's explanation of std::enable_if:

template<class T, class Enable = void>
class A {}; // primary template

template<class T>
class A<T, typename std::enable_if<std::is_floating_point<T>::value>::type> {
}; // specialization for floating point types

I'm having trouble understanding how using std::enable_if in this way helps select the specialization.  (I don't doubt that it does.)

When the compiler sees a declaration like A<float> specialized;, it will see two possible template instantiations that fit:

The "primary template" A<T, Enable> where T is the type float and Enable is the type void (because of the default value).

The specialization A<T, void> where T is the type float and void is the result of the expression with the enable_if.

Aren't those ambiguous?  Both effectively result in A<T, void>, so why is the specialization chosen?

In a different case, like A<int> primary;, the options to the compiler seem to be:

The primary, A<T, Enable>, where T is the type int and Enable is the type void.

The specialization, A<T, ?>, where T is the type int and the ? represents where I'm completely lost.  In this case, the enable_if condition is false, so it doesn't define type, which leaves you with A<int, typename >.  Isn't that a syntax error?  Even in the face of SFINAE?


问:
Convert a Dictionary with arrays of varying length to Excel
I want to convert a dictionary like;

```<code>{'Application1': [nodename1, nodetier1, nodeid1],
 'Application2': [nodename2, nodetier2, nodeid2, nodename3, nodetier3, nodeid3]}
</code>```

to excel format where the dictionary key is printed multiple times for each 3 items. Ideally it would look like;

```<code>   Application    nodename    nodetier    nodeid
0  Application1   nodename1   nodetier1   nodeid1
1  Application2   nodename2   nodetier2   nodeid2
2  Application2   nodename3   nodetier3   nodeid3
</code>```

答:
check this:

```<code>import pandas as pd

x = {
    'app1': [0, 1, 2],
    'app2': [0, 1, 2, 3, 4, 5],
    'app3': [0, 1, 2, 3, 4, 5, 6, 7, 8]
}

temp = []
for app in x:
    # chunk the list by the length of 3
    chunks = [x[app][i:i+3] for i in range(0, len(x[app]), 3)]
    # for all chunks add the value with the app name
    for chunk in chunks:
        temp.append(
            [app, *chunk]
        )

df = pd.DataFrame(temp, columns=('application', 'nodename', 'nodetier', 'nodeid'))

print(df)
</code>```

gives:

```<code>  application  nodename  nodetier  nodeid
0        app1         0         1       2
1        app2         0         1       2
2        app2         3         4       5
3        app3         0         1       2
4        app3         3         4       5
5        app3         6         7       8
</code>```

And finally write to excel file:

```<code>df.to_excel('excel_file')
</code>```

Body:
I want to convert a dictionary like;

{'Application1': [nodename1, nodetier1, nodeid1],
 'Application2': [nodename2, nodetier2, nodeid2, nodename3, nodetier3, nodeid3]}

to excel format where the dictionary key is printed multiple times for each 3 items. Ideally it would look like;

   Application    nodename    nodetier    nodeid
0  Application1   nodename1   nodetier1   nodeid1
1  Application2   nodename2   nodetier2   nodeid2
2  Application2   nodename3   nodetier3   nodeid3

Body:
check this:

import pandas as pd

x = {
    'app1': [0, 1, 2],
    'app2': [0, 1, 2, 3, 4, 5],
    'app3': [0, 1, 2, 3, 4, 5, 6, 7, 8]
}

temp = []
for app in x:
    # chunk the list by the length of 3
    chunks = [x[app][i:i+3] for i in range(0, len(x[app]), 3)]
    # for all chunks add the value with the app name
    for chunk in chunks:
        temp.append(
            [app, *chunk]
        )

df = pd.DataFrame(temp, columns=('application', 'nodename', 'nodetier', 'nodeid'))

print(df)

gives:

  application  nodename  nodetier  nodeid
0        app1         0         1       2
1        app2         0         1       2
2        app2         3         4       5
3        app3         0         1       2
4        app3         3         4       5
5        app3         6         7       8

And finally write to excel file:

df.to_excel('excel_file')


问:
Javascript, I'm not being able to set focus to html form element
I know that I had to search on google, youtube and stackoverflow before I ask my question on stackoverflow.

But I swear I watched many videos on youtube, And I searched for many ways on google and stackoverflow! to solve my problem.
,

And now i'm stuck with this

```<code><input id="input-sign-in-id" class="uqid-id-input touch-feedback textfield-validate theme-textfield hokkai-text-input insert-dir three-point-leader" dir="auto" placeholder="Email Address" maxlength="64" type="email">
</code>```

I can set any value via this code, And it works.

```<code>var t2 = document.getElementById("input-sign-in-id");
t2.value = "LuxuryUAE2@hotmail.com";
</code>```

But the problem is I can't set focus to the input, I tried this code, And it doesn't work.

```<code>var t2 = document.getElementById("input-sign-in-id");
t2.focus();
t2.click();
t2.select();
</code>```

答:
Your JavaScript looks correct. You should be able to focus on the input element with the following code:

document.getElementById("input-sign-in-id").focus()

There are a lot of CSS classes on that input element that may be affecting the focus styles of that element. Also, there may be ID-specific CSS affecting too.

Try removing all of the classes and if see if it works. Then slowly add them back one by one, until you find the culprit.

Body:
I know that I had to search on google, youtube and stackoverflow before I ask my question on stackoverflow.

But I swear I watched many videos on youtube, And I searched for many ways on google and stackoverflow! to solve my problem.
,

And now i'm stuck with this

<input id="input-sign-in-id" class="uqid-id-input touch-feedback textfield-validate theme-textfield hokkai-text-input insert-dir three-point-leader" dir="auto" placeholder="Email Address" maxlength="64" type="email">

I can set any value via this code, And it works.

var t2 = document.getElementById("input-sign-in-id");
t2.value = "LuxuryUAE2@hotmail.com";

But the problem is I can't set focus to the input, I tried this code, And it doesn't work.

var t2 = document.getElementById("input-sign-in-id");
t2.focus();
t2.click();
t2.select();


问:
(gcloud.app.deploy) Error Response: [7] Access Not Configured. Cloud Build has not been used in project
I am running into this error while deploying my django(2.1) app with python(3.5) to appengine. Before, I was using python 2 and python27 in app.yaml, there was no such error, but now when I have python 3.5.2 and python37 in my app.yaml, I am running into this error after "gcloud app deploy". Do I really have to enable billing or am I doing something wrong? Is there a way out? The full error is

ERROR: (gcloud.app.deploy) Error Response: [7] Access Not Configured. Cloud Build has not been used in project chaipani-217815 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/cloudbuild.googleapis.com/overview?project=chaipani-217815 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.

答:
We ran in to an issue where an incomplete deploy (that hung and had to be aborted) had errors setting some internal service account permissions and kept getting the "Cloud Build has not been used in project before or it is disabled" error despite the Cloud Build API being enabled and a billing account set up.

We solved the issue by disabling the Cloud Build API, waiting a couple hours (to ensure the service accounts were deleted), and then re-enabling.


问:
Lodash create object from array of arrays
I would like to use lodash to generete object from array of arrays. I use for it lodash.zipObject method and map. But it is not 1:1 what I would like to generate:

Input:

```<code> "rows": [
    [
      "stravi/aa",
      "202001",
      "59",
      "51",
      "2558.98",
      "0.5358894453719162",
      "1.9204668112983725",
      "140",
      "2.3466309084813943"
    ],
    [
      "stravi/ab",
      "202003",
      "3591",
      "349",
      "2246.09",
      "0.41838214",
      "3.57603358",
      "50",
      "4.82115474"
    ],
    [
      "stravi/ac",
      "202007",
      "3354",
      "25",
      "1975.76",
      "0.74220667708",
      "1.12321555541",
      "11",
      "0.9324532454"
    ]
  ]

dictionary: ['source', 'sessions', 'adClicks', 'adCost', 'CPC', 'CTR', 'goalCompletionsAll', 'goalConversionRateAll' ], [action.yearReportData]
</code>```

output:

```<code>{
  source: ['stravi/aa', 'stravi/ab', 'stravi/ac'],
  sessions: ['202001', '202003', '202007']
  ...
}
</code>```

I would like to use lodash, and I try by:

```<code>   lodash.map(rows, arr =>
                lodash.zipObject(['source', 'sessions', 'adClicks', 'adCost', 'CPC', 'CTR', 'goalCompletionsAll', 'goalConversionRateAll'], arr))
</code>```

But is not correct... I received multiple object. I would like to have one object with all data. Like my example.

答:
why use third-party library, if may easy do it like so</p>

```<code>let result = rows.reduce((obj, arr) => {
  arr.forEach((item, i) => {
    if (!obj[dictionary[i]]) {
      obj[dictionary[i]] = [];
    }
    obj[dictionary[i]].push(item);
  })
  return obj;
}, {});
</code>```

Body:
I would like to use lodash to generete object from array of arrays. I use for it lodash.zipObject method and map. But it is not 1:1 what I would like to generate:

Input:

 "rows": [
    [
      "stravi/aa",
      "202001",
      "59",
      "51",
      "2558.98",
      "0.5358894453719162",
      "1.9204668112983725",
      "140",
      "2.3466309084813943"
    ],
    [
      "stravi/ab",
      "202003",
      "3591",
      "349",
      "2246.09",
      "0.41838214",
      "3.57603358",
      "50",
      "4.82115474"
    ],
    [
      "stravi/ac",
      "202007",
      "3354",
      "25",
      "1975.76",
      "0.74220667708",
      "1.12321555541",
      "11",
      "0.9324532454"
    ]
  ]

dictionary: ['source', 'sessions', 'adClicks', 'adCost', 'CPC', 'CTR', 'goalCompletionsAll', 'goalConversionRateAll' ], [action.yearReportData]

output:

{
  source: ['stravi/aa', 'stravi/ab', 'stravi/ac'],
  sessions: ['202001', '202003', '202007']
  ...
}

I would like to use lodash, and I try by:

   lodash.map(rows, arr =>
                lodash.zipObject(['source', 'sessions', 'adClicks', 'adCost', 'CPC', 'CTR', 'goalCompletionsAll', 'goalConversionRateAll'], arr))

But is not correct... I received multiple object. I would like to have one object with all data. Like my example.

Body:
why use third-party library, if may easy do it like so

let result = rows.reduce((obj, arr) => {
  arr.forEach((item, i) => {
    if (!obj[dictionary[i]]) {
      obj[dictionary[i]] = [];
    }
    obj[dictionary[i]].push(item);
  })
  return obj;
}, {});


问:
Mimicking VBA Input ListControl in R Shiny
Is it possible to generate VBA List Control input (as shown in the screenshot) in an R Shiny dashboard?

VBA List Input Example Screen Shot

答: There is no reason to mimic that. A selectInput can do that when you set the size argument to a value larger than 1. Check the documentation to see how size works (it has limitations).


问:
What's the best way to download file using urllib3
I would like to download file over HTTP protocol using urllib3.
I have managed to do this using following code:

```<code> url = 'http://url_to_a_file'
 connection_pool = urllib3.PoolManager()
 resp = connection_pool.request('GET',url )
 f = open(filename, 'wb')
 f.write(resp.data)
 f.close()
 resp.release_conn()
</code>```

But I was wondering what is the proper way of doing this.
For example will it work well for big files and If no what to do to make this code more bug tolerant and scalable.

Note. It is important to me to use urllib3 library not urllib2 for example, because I want my code to be thread safe.

答:
Most easy way with urllib3, you can use shutil do auto-manage packages.

import urllib3
import shutil

http = urllib3.PoolManager()
with open(filename, 'wb') as out:
    r = http.request('GET', url, preload_content=False)
    shutil.copyfileobj(r, out)
```

Body:
I would like to download file over HTTP protocol using urllib3.
I have managed to do this using following code:

 url = 'http://url_to_a_file'
 connection_pool = urllib3.PoolManager()
 resp = connection_pool.request('GET',url )
 f = open(filename, 'wb')
 f.write(resp.data)
 f.close()
 resp.release_conn()

But I was wondering what is the proper way of doing this.
For example will it work well for big files and If no what to do to make this code more bug tolerant and scalable.

Note. It is important to me to use urllib3 library not urllib2 for example, because I want my code to be thread safe.


问:
Interesting search question: Find a value that's NOT in a list (Daily coding problem, May 26, 2020)

I was wondering if anyone would be willing to give me some feedback on my solution to today's question from the Daily Coding problem email list. It's an interesting question about finding the first value that's NOT present in a list, as opposed to finding a value that IS there.

This problem was asked by Stripe.

Given an array of integers, find the first missing positive integer in linear time and
constant space.
In other words, find the lowest positive integer that does not exist in the array.
The array can contain duplicates and negative numbers as well.

For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.

You can modify the input array in-place.

My main question is that I'm not sure if I've met the O(n) time and O(1) space requirements. Here is my solution using Groovy:

```<code>def find_first( Xs ) {
  ys = []
  szXs = Xs.size()
  // First, transfer Xs list to a set ys.
  szXs.times { // this loop is O(n)
    if ( (hd = Xs.head()) > 0 ) { ys << hd; } // We only need to keep val if it's positive.
    Xs = Xs.drop(1); // Remove val from Xs in order to meet O(1) space requirement.
  }
  ys = ys.toSet() // converting list to set is O(n)
  sz = ys.size()  // ys.size() might be same as Xs.size(), but it could be smaller, so give it a new var.
  for (int i = 1; i < sz; ++i) { // this loop is O(n)
    if ( !ys.contains(i) ) return i // Testing a hash set for set membership is O(1)
  }
  return sz + 1 // if this point is reached, ys had all values [1..sz] already
} // end find_first

def test(Xs) {
  println "\nstarting with Xs = " + Xs
  ans1 = find_first( Xs )
  println "first missing = " + ans1
}

xs1 = [ 3,4,-1,1 ]
xs2 = [ 1, 2, 0 ]
xs3 = [ 7, 8 ]
xs4 = [ 1,1,2,1 ]
xs5 = [ -4, -1 ]

test(xs1)
test(xs2)
test(xs3)
test(xs4)
</code>```

    test(xs5)

And here is the output:

starting with Xs = [3, 4, -1, 1]
first missing = 2

starting with Xs = [1, 2, 0]
first missing = 3

starting with Xs = [7, 8]
first missing = 1

starting with Xs = [1, 1, 2, 1]
first missing = 3

starting with Xs = [-4, -1]
first missing = 1

So it's correct on that limited set of values, just want to be sure that it's O(n) time and O(1) space. Any advice is appreciated!
Hank

答:
I am not familiar with groovy, but it seems like your code is O(n) space, since you create an additional hash set (ys).

Note that the question has a hint:

You can modify the input array in-place.

This can be done in O(n) time with O(1) space, by first sorting the array inplace with radix sort, and then iterating over the values to find first missing one.

Body:
I was wondering if anyone would be willing to give me some feedback on my solution to today's question from the Daily Coding problem email list. It's an interesting question about finding the first value that's NOT present in a list, as opposed to finding a value that IS there.

This problem was asked by Stripe.

Given an array of integers, find the first missing positive integer in linear time and
constant space.
In other words, find the lowest positive integer that does not exist in the array.
The array can contain duplicates and negative numbers as well.

For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.

You can modify the input array in-place.

My main question is that I'm not sure if I've met the O(n) time and O(1) space requirements. Here is my solution using Groovy:

def find_first( Xs ) {
  ys = []
  szXs = Xs.size()
  // First, transfer Xs list to a set ys.
  szXs.times { // this loop is O(n)
    if ( (hd = Xs.head()) > 0 ) { ys << hd; } // We only need to keep val if it's positive.
    Xs = Xs.drop(1); // Remove val from Xs in order to meet O(1) space requirement.
  }
  ys = ys.toSet() // converting list to set is O(n)
  sz = ys.size()  // ys.size() might be same as Xs.size(), but it could be smaller, so give it a new var.
  for (int i = 1; i < sz; ++i) { // this loop is O(n)
    if ( !ys.contains(i) ) return i // Testing a hash set for set membership is O(1)
  }
  return sz + 1 // if this point is reached, ys had all values [1..sz] already
} // end find_first

def test(Xs) {
  println "\nstarting with Xs = " + Xs
  ans1 = find_first( Xs )
  println "first missing = " + ans1
}

xs1 = [ 3,4,-1,1 ]
xs2 = [ 1, 2, 0 ]
xs3 = [ 7, 8 ]
xs4 = [ 1,1,2,1 ]
xs5 = [ -4, -1 ]

test(xs1)
test(xs2)
test(xs3)
test(xs4)

    test(xs5)

And here is the output:

starting with Xs = [3, 4, -1, 1]
first missing = 2

starting with Xs = [1, 2, 0]
first missing = 3

starting with Xs = [7, 8]
first missing = 1

starting with Xs = [1, 1, 2, 1]
first missing = 3

starting with Xs = [-4, -1]
first missing = 1

So it's correct on that limited set of values, just want to be sure that it's O(n) time and O(1) space. Any advice is appreciated!
Hank


问:
Implementing ErrorHandler class in Angular 8+ gives the exception at run time
```
this snippet is from app.module.ts. I just created an angular 9 application <br> and tried to implement ErrorHandler class to catch error but it is showing <br> the error at run time and page does not load.
```

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ErrorHandler } from '@angular/core';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    {provide: ErrorHandler, useClass: MyErrorHandler}
  ],
  bootstrap: [AppComponent]
})

class MyErrorHandler implements ErrorHandler {
  handleError(error) {
    alert(error);
    // do something with the exception
  }
}
export class AppModule { }

</code>```

Exception in browser:

```<code>ASSERTION ERROR: Type passed in is not NgModuleType, it does not have 'ɵmod' property.
    at throwError (core.js:1344)
    at assertNgModuleType (core.js:2951)
    at compileNgModuleFactory__POST_R3__ (core.js:42275)
    at PlatformRef.bootstrapModule (core.js:42663)
    at Module../src/main.ts (main.ts:11)
    at __webpack_require__ (bootstrap:79)
    at Object.0 (main.ts:12)
    at __webpack_require__ (bootstrap:79)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
</code>```

答:
move your MyErrorHandler class to a separate file and import it in your AppModule and it should work.

Angular uses typescript decorators, which are defined above each class they belong to. In your case you were adding a decorator @NgModule to a class MyErrorHandler, that way Angular could not find proper configuration for main AppModule, and that's why you receive such error when compiling.

Body:
this snippet is from app.module.ts. I just created an angular 9 application
 and tried to implement ErrorHandler class to catch error but it is showing
 the error at run time and page does not load.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ErrorHandler } from '@angular/core';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    {provide: ErrorHandler, useClass: MyErrorHandler}
  ],
  bootstrap: [AppComponent]
})

class MyErrorHandler implements ErrorHandler {
  handleError(error) {
    alert(error);
    // do something with the exception
  }
}
export class AppModule { }

Exception in browser:

ASSERTION ERROR: Type passed in is not NgModuleType, it does not have 'ɵmod' property.
    at throwError (core.js:1344)
    at assertNgModuleType (core.js:2951)
    at compileNgModuleFactory__POST_R3__ (core.js:42275)
    at PlatformRef.bootstrapModule (core.js:42663)
    at Module../src/main.ts (main.ts:11)
    at __webpack_require__ (bootstrap:79)
    at Object.0 (main.ts:12)
    at __webpack_require__ (bootstrap:79)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)


问:
can't connect to tsserver
I'm writing a vscode extension that should connect to tsserver in order to provide language support for typescript/javascript.

Here is how i'm doing it (in extension.ts, inside activate):

```<code>const serverModule = path.resolve(
  __dirname,
  "..",
  "node_modules",
  "typescript",
  "lib",
  "tsserver.js"
);

const debugOptions = { execArgv: ["--nolazy", "--inspect=6009"] };

const serverOptions: ServerOptions = {
  run: { module: serverModule, transport: TransportKind.ipc },
  debug: {
    module: serverModule,
    transport: TransportKind.ipc,
    options: debugOptions,
  },
};

const clientOptions = {
  documentSelector: [
    {
      scheme: "file",
      language: "typescript",
    },
  ],
};

client = new LanguageClient(
  "server-id",
  "server-name",
  serverOptions,
  clientOptions
);

context.subscriptions.push(client.start());
</code>```

But when I call client.onReady().then(() => client.sendRequest(...)); the request is not sent. I'm almost sure the problem is that the initialization phase is unsuccessful so the onReady() method is blocking me. How do I get it to work ?

答: tsserver does not use the language server protocol, it has its own json based protocol. You cannot connect to it using the language server protocol apis </p>

Title: can't connect to tsserver

Body:
I'm writing a vscode extension that should connect to tsserver in order to provide language support for typescript/javascript.

Here is how i'm doing it (in extension.ts, inside activate):

const serverModule = path.resolve(
  __dirname,
  "..",
  "node_modules",
  "typescript",
  "lib",
  "tsserver.js"
);

const debugOptions = { execArgv: ["--nolazy", "--inspect=6009"] };

const serverOptions: ServerOptions = {
  run: { module: serverModule, transport: TransportKind.ipc },
  debug: {
    module: serverModule,
    transport: TransportKind.ipc,
    options: debugOptions,
  },
};

const clientOptions = {
  documentSelector: [
    {
      scheme: "file",
      language: "typescript",
    },
  ],
};

client = new LanguageClient(
  "server-id",
  "server-name",
  serverOptions,
  clientOptions
);

context.subscriptions.push(client.start());

But when I call client.onReady().then(() => client.sendRequest(...)); the request is not sent. I'm almost sure the problem is that the initialization phase is unsuccessful so the onReady() method is blocking me. How do I get it to work ?


问:
How to make an API call in solidity?
I have a smart contract that I’m trying to make, it pays out the winners of my League of Legends tournament. However I’m running into an issue. I need to make an API call to get the winner of the match, I have a simple URL that I’ve make.

```<code>"example-winner.com/winner"
</code>```

And it returns simple JSON with the address of the winner:

```<code>{"winner":"0xa7D0......."}
</code>```

However, I’m not sure how to make the API call to the outside function. I know I need to use some sort of oracle technology.

Any thoughts? Below is my code:

```<code>pragma solidity ^0.4.24;
contract LeagueWinners{
    address public manager;
    address[] public players;
    uint256 MINIMUM = 1000000000000000;
    constructor() public{
        manager = msg.sender;
    }
    function enter() public payable{
        assert(msg.value > MINIMUM);
        players.push(msg.sender);
    }
    function getWinner() public{
        assert(msg.sender == manager);
        // TODO
        // Get the winner from the API call
        result = 0; // the result of the API call
        players[result].transfer(address(this).balance);
        // returns an adress object
        // all units of transfer are in wei
        players = new address[](0);
        // this empties the dynamic array
    }
}
</code>```

答:
You can use Chainlink as your Oracle.

As many have mentioned, you will need an oracle to get your API call. Something that is important to note, your contract is actually asking an oracle to make your API call for you, and not making the API call itself. This is because the blockchain is deterministic. For more information see this thread.

To answer your question, you can use the decentralized oracle service Chainlink.

You'd add a function:

```<code>  function getWinner()
    public
    onlyOwner
  {
    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
    req.add("get", "example-winner.com/winner");
    req.add("path", "winner");
    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
  }
</code>```

For the purpose of the following exmaple, we are going to pretend you want to return a uint256 instead of an address. You can return a bytes32 and then convert it to an address, but for simplicity let's say the API returns the index of the winner. You'll have to find a node and jobId that can make a http.get request and return a uint256 object. You can find nodes and jobs from market.link. Each testnet (Ropsten, Mainnet, Kovan, etc) has different node addresses, so make sure you pick the right ones.

For this demo, we are going to use LinkPool's ropsten node

```<code>address ORACLE=0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;
bytes32 JOB= "c179a8180e034cf5a341488406c32827";
</code>```

Ideally, you'd choose a number of nodes to run your job, to make it trustless and decentralized. You can read here for more information on precoordinators and aggregating data. disclosure I am the author of that blog

Your full contract would look like:

```<code>pragma solidity ^0.6.0;

import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol";

contract GetData is ChainlinkClient {
    uint256 indexOfWinner;
    address public manager;
    address payable[] public players;
    uint256 MINIMUM = 1000000000000000;

  // The address of an oracle
    address ORACLE=0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;
    //bytes32 JOB= "93fedd3377a54d8dac6b4ceadd78ac34";
    bytes32 JOB= "c179a8180e034cf5a341488406c32827";
    uint256 ORACLE_PAYMENT = 1 * LINK;

  constructor() public {
    setPublicChainlinkToken();
    manager = msg.sender;
  }

function getWinnerAddress()
    public
    onlyOwner
  {
    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
    req.add("get", "example-winner.com/winner");
    req.add("path", "winner");
    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
  }

  // When the URL finishes, the response is routed to this function
  function fulfill(bytes32 _requestId, uint256 _index)
    public
    recordChainlinkFulfillment(_requestId)
  {
    indexOfWinner = _index;
    assert(msg.sender == manager);
    players[indexOfWinner].transfer(address(this).balance);
    players = new address payable[](0);
  }

  function enter() public payable{
        assert(msg.value > MINIMUM);
        players.push(msg.sender);
    }

  modifier onlyOwner() {
    require(msg.sender == manager);
    _;
  }

    // Allows the owner to withdraw their LINK on this contract
  function withdrawLink() external onlyOwner() {
    LinkTokenInterface _link = LinkTokenInterface(chainlinkTokenAddress());
    require(_link.transfer(msg.sender, _link.balanceOf(address(this))), "Unable to transfer");
  }

}
</code>```

This would do about everything you need.

If you can't adjust the API to return a uint, you can return a bytes32 and then convert it to an address or a string.

```<code> function bytes32ToStr(bytes32 _bytes32) public pure returns (string memory) {
     bytes memory bytesArray = new bytes(32);
     for (uint256 i; i < 32; i++) {
         bytesArray[i] = _bytes32[i];
         }
     return string(bytesArray);
     }
</code>```

Title: How to make an API call in solidity?

Body:
I have a smart contract that I’m trying to make, it pays out the winners of my League of Legends tournament. However I’m running into an issue. I need to make an API call to get the winner of the match, I have a simple URL that I’ve make.

"example-winner.com/winner"

And it returns simple JSON with the address of the winner:

{"winner":"0xa7D0......."}

However, I’m not sure how to make the API call to the outside function. I know I need to use some sort of oracle technology.

Any thoughts? Below is my code:

pragma solidity ^0.4.24;
contract LeagueWinners{
    address public manager;
    address[] public players;
    uint256 MINIMUM = 1000000000000000;
    constructor() public{
        manager = msg.sender;
    }
    function enter() public payable{
        assert(msg.value > MINIMUM);
        players.push(msg.sender);
    }
    function getWinner() public{
        assert(msg.sender == manager);
        // TODO
        // Get the winner from the API call
        result = 0; // the result of the API call
        players[result].transfer(address(this).balance);
        // returns an adress object
        // all units of transfer are in wei
        players = new address[](0);
        // this empties the dynamic array
    }
}

Body:
You can use Chainlink as your Oracle.

As many have mentioned, you will need an oracle to get your API call. Something that is important to note, your contract is actually asking an oracle to make your API call for you, and not making the API call itself. This is because the blockchain is deterministic. For more information see this thread.

To answer your question, you can use the decentralized oracle service Chainlink.

You'd add a function:

  function getWinner()
    public
    onlyOwner
  {
    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
    req.add("get", "example-winner.com/winner");
    req.add("path", "winner");
    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
  }

For the purpose of the following exmaple, we are going to pretend you want to return a uint256 instead of an address. You can return a bytes32 and then convert it to an address, but for simplicity let's say the API returns the index of the winner. You'll have to find a node and jobId that can make a http.get request and return a uint256 object. You can find nodes and jobs from market.link. Each testnet (Ropsten, Mainnet, Kovan, etc) has different node addresses, so make sure you pick the right ones.

For this demo, we are going to use LinkPool's ropsten node

address ORACLE=0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;
bytes32 JOB= "c179a8180e034cf5a341488406c32827";

Ideally, you'd choose a number of nodes to run your job, to make it trustless and decentralized. You can read here for more information on precoordinators and aggregating data. disclosure I am the author of that blog

Your full contract would look like:

pragma solidity ^0.6.0;

import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol";

contract GetData is ChainlinkClient {
    uint256 indexOfWinner;
    address public manager;
    address payable[] public players;
    uint256 MINIMUM = 1000000000000000;

  // The address of an oracle
    address ORACLE=0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;
    //bytes32 JOB= "93fedd3377a54d8dac6b4ceadd78ac34";
    bytes32 JOB= "c179a8180e034cf5a341488406c32827";
    uint256 ORACLE_PAYMENT = 1 * LINK;

  constructor() public {
    setPublicChainlinkToken();
    manager = msg.sender;
  }

function getWinnerAddress()
    public
    onlyOwner
  {
    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
    req.add("get", "example-winner.com/winner");
    req.add("path", "winner");
    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
  }

  // When the URL finishes, the response is routed to this function
  function fulfill(bytes32 _requestId, uint256 _index)
    public
    recordChainlinkFulfillment(_requestId)
  {
    indexOfWinner = _index;
    assert(msg.sender == manager);
    players[indexOfWinner].transfer(address(this).balance);
    players = new address payable[](0);
  }

  function enter() public payable{
        assert(msg.value > MINIMUM);
        players.push(msg.sender);
    }

  modifier onlyOwner() {
    require(msg.sender == manager);
    _;
  }

    // Allows the owner to withdraw their LINK on this contract
  function withdrawLink() external onlyOwner() {
    LinkTokenInterface _link = LinkTokenInterface(chainlinkTokenAddress());
    require(_link.transfer(msg.sender, _link.balanceOf(address(this))), "Unable to transfer");
  }

}

This would do about everything you need.

If you can't adjust the API to return a uint, you can return a bytes32 and then convert it to an address or a string.

 function bytes32ToStr(bytes32 _bytes32) public pure returns (string memory) {
     bytes memory bytesArray = new bytes(32);
     for (uint256 i; i < 32; i++) {
         bytesArray[i] = _bytes32[i];
         }
     return string(bytesArray);
     }


问:
working with high precision timestamps in python
Hey I am working in python with datetime and I am wondering what the best way to parse this timestamp is.

The timestamps are ISO standard, here is an example "2010-06-19T08:17:14.078685237Z"

Now so far I have used

```<code>time = datetime.datetime.strptime(timestamp.split(".")[0], "%Y-%m-%dT%H:%M:%S")
precisetime = time + datetime.timedelta(0,float("." + timestamp[:-1].split(".")[0]))
</code>```

This kind of works, but I feel like there should be a more streamlined way (I am very new to python, and I am sure I am doing this like an ass). Also, I have nanoseconds in my timestamp, but only microseconds in my datetime object, is there a better module to work with? I need to be able to do operations on the time such as subtracting times and putting them in the scheduler.

Any better way to go about this?

答: There's nothing inherently ass-like with your approach, but you may like to try pyiso8601 or dateutil</p>

Body:
Hey I am working in python with datetime and I am wondering what the best way to parse this timestamp is.

The timestamps are ISO standard, here is an example "2010-06-19T08:17:14.078685237Z"

Now so far I have used

time = datetime.datetime.strptime(timestamp.split(".")[0], "%Y-%m-%dT%H:%M:%S")
precisetime = time + datetime.timedelta(0,float("." + timestamp[:-1].split(".")[0]))

This kind of works, but I feel like there should be a more streamlined way (I am very new to python, and I am sure I am doing this like an ass). Also, I have nanoseconds in my timestamp, but only microseconds in my datetime object, is there a better module to work with? I need to be able to do operations on the time such as subtracting times and putting them in the scheduler.

Any better way to go about this?


问:
Laravel 5 - env() always returns null
I try to find out why my env() helper always returns null. This causes trouble especially in app.php file, where are env() helpers widely used by default. Perhaps any mysterious server setting?

My env file:

```<code>APP_ENV=production
APP_KEY=base64:mymagickey=
APP_DEBUG=false
APP_LOG_LEVEL=info
APP_URL=http://www.example.com

etc...
</code>```

EDIT - I tried following:

```<code>php artisan cache:clear
php artisan view:clear
php artisan config:cache
</code>```

and ofcourse, i am using env helper like this: env('APP_ENV')

But still no success. The wierd part is, that $_ENV php variable contains every single variable from .env file.

答: If the accepted answer doesn't fix the issue check if .env file has correct read and write permission given. If the file cannot be read by the framework / library then the values will always be null. I've come across this issue on one of my Lumen projects but after changing the file permissions it worked.</p>

Title: Laravel 5 - env() always returns null

Body:
I try to find out why my env() helper always returns null. This causes trouble especially in app.php file, where are env() helpers widely used by default. Perhaps any mysterious server setting?

My env file:

APP_ENV=production
APP_KEY=base64:mymagickey=
APP_DEBUG=false
APP_LOG_LEVEL=info
APP_URL=http://www.example.com

etc...

EDIT - I tried following:

php artisan cache:clear
php artisan view:clear
php artisan config:cache

and ofcourse, i am using env helper like this: env('APP_ENV')

But still no success. The wierd part is, that $_ENV php variable contains every single variable from .env file.


问:
CSS changes on MVC App not working
I created an MVC app using VS Express for web.  It it will only use the default built in CSS file that VS Express comes with.

Example:  If I modify the bootstrap.css file (change jumbotron color), and run locally from VS, the changes are apparent, however when i web deploy, none of those changes are apparent.  I also noticed when I modify the web.config file to Debug=false, the CSS changes I've made are not apparent when I run it locally from VS (and on web deploy).

CSS is still being applied, however any changes I make are not applied.  The site shows the old default jumbotron color.  If I change debug=true in the web.config then the jumbotron shows my updated color.  When I web deploy my site none of the CSS changes are applied, it still uses the default CSS file, I even checked bootstrap.css on the server and it shows the updated jumbotron color, but the jumbotron is still the default color on the web??  Super confusing.

I have done a lot of reading, tried adding the following to my web.config:

```<code><remove name="BundleModule" />
<add name="BundleModule" type="System.Web.Optimization.BundleModule" />
</code>```

but that doesnt fix it.  I tried removing .css from my file names, this fixed the problem when I run it locally from VS using debug=false, however when I publish the website the site shows no CSS styles at all.  It is not a caching issue.  It is something to do with bundling and debug=false, but I do not know what.  I am still quite new to web/MVC development.  I've updated my web.optimization and microsoft.aspnet, etc with NuGet.

I am having a really hard time with this, if anyone has a suggestion and it works I will be very happy!  There are lots of posts about this on Stack Overflow but none of the suggestions have worked for me yet.

This is my bundle.config.cs:

```<code>using System.Web;
using System.Web.Optimization;

namespace HFHYYC
{
        public class BundleConfig
        {

        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*"));

            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.js",
                  "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css",
                  "~/Content/site.css"));
        }
    }
}
</code>```

答: I did none of the above and also had the same issue with when publishing Asp.net project , what worked for me was as simple as right click on the css.file and click on include in project and publish that worked for me. </p>

Title: CSS changes on MVC App not working

Body:
I created an MVC app using VS Express for web.  It it will only use the default built in CSS file that VS Express comes with.

Example:  If I modify the bootstrap.css file (change jumbotron color), and run locally from VS, the changes are apparent, however when i web deploy, none of those changes are apparent.  I also noticed when I modify the web.config file to Debug=false, the CSS changes I've made are not apparent when I run it locally from VS (and on web deploy).

CSS is still being applied, however any changes I make are not applied.  The site shows the old default jumbotron color.  If I change debug=true in the web.config then the jumbotron shows my updated color.  When I web deploy my site none of the CSS changes are applied, it still uses the default CSS file, I even checked bootstrap.css on the server and it shows the updated jumbotron color, but the jumbotron is still the default color on the web??  Super confusing.

I have done a lot of reading, tried adding the following to my web.config:

<remove name="BundleModule" />
<add name="BundleModule" type="System.Web.Optimization.BundleModule" />

but that doesnt fix it.  I tried removing .css from my file names, this fixed the problem when I run it locally from VS using debug=false, however when I publish the website the site shows no CSS styles at all.  It is not a caching issue.  It is something to do with bundling and debug=false, but I do not know what.  I am still quite new to web/MVC development.  I've updated my web.optimization and microsoft.aspnet, etc with NuGet.

I am having a really hard time with this, if anyone has a suggestion and it works I will be very happy!  There are lots of posts about this on Stack Overflow but none of the suggestions have worked for me yet.

This is my bundle.config.cs:

using System.Web;
using System.Web.Optimization;

namespace HFHYYC
{
        public class BundleConfig
        {

        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*"));

            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.js",
                  "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css",
                  "~/Content/site.css"));
        }
    }
}


问:
Encrypting files with php/mcrypt is corrupting docx (and other Microsoft Office 2007) files but others are fine
I'm working with a CodeIgniter application to encrypt uploaded files then decrypt them when downloaded so they can be stored safely (alongside other security measures). This is all working fine, apart from docx (and other Microsoft Office 2007+) files. When these are downloaded they are successfully decrypted but Office detects them as corrupt. These can be repaired, so they're not totally corrupted, but something has changed in the file from the original version which is making Office see them as corrupt. As I mentioned, this doesn't seem to be happening to any other file types (that I have noticed). The docx files are also slightly different in size (only a matter of bytes), whereas other types are not.

To encrypt, I upload the file, read the contents into a string with file_get_contents(), then run the string through CodeIgniter's encode() in the encrypt library then save the file back to disk, deleting the original:

```<code>function mcrypt_encode($data, $key)
{
    $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
    $init_vect = mcrypt_create_iv($init_size, MCRYPT_RAND);
    return $this->_add_cipher_noise($init_vect.mcrypt_encrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), $key);
}
</code>```

and to decode:

```<code>function mcrypt_decode($data, $key)
{
    $data = $this->_remove_cipher_noise($data, $key);
    $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());

    if ($init_size > strlen($data))
    {
        return FALSE;
    }

    $init_vect = substr($data, 0, $init_size);
    $data = substr($data, $init_size);
    return rtrim(mcrypt_decrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), "\0");
}
</code>```

Then run the decoded string through CodeIgniter's force_download()

The default cipher is MCRYPT_RIJNDAEL_256 and mode is MCRYPT_MODE_CBC. Mcrypt is enabled on my server along with MCRYPT_RIJNDAEL_256.

If anyone could point me in the right direction as to why this might be happening it would be greatly appreciated.

Many thanks

答:
base64_encode() the file_get_contents() of file, then encrypt.

base64_decode() the decrypted file_get_contents() of encrypted file before downloading.

Body:
I'm working with a CodeIgniter application to encrypt uploaded files then decrypt them when downloaded so they can be stored safely (alongside other security measures). This is all working fine, apart from docx (and other Microsoft Office 2007+) files. When these are downloaded they are successfully decrypted but Office detects them as corrupt. These can be repaired, so they're not totally corrupted, but something has changed in the file from the original version which is making Office see them as corrupt. As I mentioned, this doesn't seem to be happening to any other file types (that I have noticed). The docx files are also slightly different in size (only a matter of bytes), whereas other types are not.

To encrypt, I upload the file, read the contents into a string with file_get_contents(), then run the string through CodeIgniter's encode() in the encrypt library then save the file back to disk, deleting the original:

function mcrypt_encode($data, $key)
{
    $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
    $init_vect = mcrypt_create_iv($init_size, MCRYPT_RAND);
    return $this->_add_cipher_noise($init_vect.mcrypt_encrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), $key);
}

and to decode:

function mcrypt_decode($data, $key)
{
    $data = $this->_remove_cipher_noise($data, $key);
    $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());

    if ($init_size > strlen($data))
    {
        return FALSE;
    }

    $init_vect = substr($data, 0, $init_size);
    $data = substr($data, $init_size);
    return rtrim(mcrypt_decrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), "\0");
}

Then run the decoded string through CodeIgniter's force_download()

The default cipher is MCRYPT_RIJNDAEL_256 and mode is MCRYPT_MODE_CBC. Mcrypt is enabled on my server along with MCRYPT_RIJNDAEL_256.

If anyone could point me in the right direction as to why this might be happening it would be greatly appreciated.

Many thanks


问:
String manipulation within a column (pandas): split, replace, join
I'd like to create a new column based on the following conditions:

if the row contains dogs/dog/chien/chiens, then add -00

if the row contains cats/cat/chat/chats, then add 00-

A sample of data is as follows:

```<code>Animal

22 dogs
1 dog
1 cat
3 dogs
32 chats
</code>```

and so far.

I'd like as output a column with only numbers (numerical):

```<code>Animal        New column

22 dogs       22-00
1 dog         1-00
1 cat         00-1
3 dogs        3-00
32 chats      00-32
</code>```

I think I should use an if condition to check the words, then .split and .join . It's about string manipulation but I'm having trouble breaking down this problem.

答:
Create tuple of search words

```<code>dog = ('dogs', 'dog', 'chien', 'chiens')
cat = ('cats', 'cat', 'chat', 'chats')
</code>```

Create conditions for each tuple created with corresponding replacements and apply the conditions to the column, using numpy select :

```<code>num = df.Animal.str.split().str[0] #the numbers
#conditions
cond1 = df.Animal.str.endswith(dog)
cond2 = df.Animal.str.endswith(cat)
condlist = [cond1,cond2]
#what should be returned for each successful condition
choicelist = [num+"-00","00-"+num]

df['New Column'] = np.select(condlist,choicelist)
df

    Animal    New Column
0   22 dogs     22-00
1   1 dog       1-00
2   1 cat       00-1
3   3 dogs      3-00
4   32 chats    00-32
</code>```

Body:
I'd like to create a new column based on the following conditions:

if the row contains dogs/dog/chien/chiens, then add -00

if the row contains cats/cat/chat/chats, then add 00-

A sample of data is as follows:

Animal

22 dogs
1 dog
1 cat
3 dogs
32 chats

and so far.

I'd like as output a column with only numbers (numerical):

Animal        New column

22 dogs       22-00
1 dog         1-00
1 cat         00-1
3 dogs        3-00
32 chats      00-32

I think I should use an if condition to check the words, then .split and .join . It's about string manipulation but I'm having trouble breaking down this problem.

Body:
Create tuple of search words

dog = ('dogs', 'dog', 'chien', 'chiens')
cat = ('cats', 'cat', 'chat', 'chats')

Create conditions for each tuple created with corresponding replacements and apply the conditions to the column, using numpy select :

num = df.Animal.str.split().str[0] #the numbers
#conditions
cond1 = df.Animal.str.endswith(dog)
cond2 = df.Animal.str.endswith(cat)
condlist = [cond1,cond2]
#what should be returned for each successful condition
choicelist = [num+"-00","00-"+num]

df['New Column'] = np.select(condlist,choicelist)
df

    Animal    New Column
0   22 dogs     22-00
1   1 dog       1-00
2   1 cat       00-1
3   3 dogs      3-00
4   32 chats    00-32


问:
Redirect old domain to new domain keeping url
We are releasing a new version of our Web app and in the process doing a branding change with a new domain also.

Both our apps are hosted in Azure.
Current App - Cloud Service
New App - Azure Website

What I want to achieve is redirect any old links from the old domain to the new domain while keeping the url portion.

Example:
User visits
https://my.currentdomain.com/any/link

and will be directed to
https://my.newdomain.io/any/link

Do I do a CNAME from currentdomain to newdomain and then a URL Rewrite in my web.config??

Thanks!

Update - I've test this locally and it does what I'm looking for. I'll just point the cname of the old domain to the new domain and this redirect should pick up the links.

```<code><rule name="Redirect to new domain" stopProcessing="true">
      <match url="^(.*)$" />
      <conditions>
        <add input="{HTTP_HOST}" matchType="Pattern" pattern="^olddomain(:\d+)?$" />
      </conditions>
      <action type="Redirect" url="https://my.newdomain.io/{R:1}" redirectType="Permanent" />
    </rule>
</code>```

答:
add this code to your header file:</p>

```<code><script type="text/javascript">
    // Get Current URL
    var url = window.location.href;
    // Replace domain in URL
    var newurl = url.replace("olddomain.com", "newdomain.com");
    // Redirect to new URL
    document.location = newurl;
</script>
</code>```

Body:
We are releasing a new version of our Web app and in the process doing a branding change with a new domain also.

Both our apps are hosted in Azure.
Current App - Cloud Service
New App - Azure Website

What I want to achieve is redirect any old links from the old domain to the new domain while keeping the url portion.

Example:
User visits
https://my.currentdomain.com/any/link

and will be directed to
https://my.newdomain.io/any/link

Do I do a CNAME from currentdomain to newdomain and then a URL Rewrite in my web.config??

Thanks!

Update - I've test this locally and it does what I'm looking for. I'll just point the cname of the old domain to the new domain and this redirect should pick up the links.

<rule name="Redirect to new domain" stopProcessing="true">
      <match url="^(.*)$" />
      <conditions>
        <add input="{HTTP_HOST}" matchType="Pattern" pattern="^olddomain(:\d+)?$" />
      </conditions>
      <action type="Redirect" url="https://my.newdomain.io/{R:1}" redirectType="Permanent" />
    </rule>

Body:
add this code to your header file:

<script type="text/javascript">
    // Get Current URL
    var url = window.location.href;
    // Replace domain in URL
    var newurl = url.replace("olddomain.com", "newdomain.com");
    // Redirect to new URL
    document.location = newurl;
</script>


问:
Strange behavior of addEventListener - ReactJs
I'm creating a tree structure in React, when I click the right button on any item list context menu appears and there I have various options to choose from. When I click on any of the options appears modal.

And it works. However, the situation changes when instead of specifying a tree structure made rigidly, I enter the tree downloaded from the server(passed by redux). Then suddenly after clicking on options from the context menu modal does not appear.

Before:

```<code>    componentDidMount(){
      //this.props.getTree()
      document.addEventListener('click', this.hideContextMenu.bind(this))

    }
    componentWillUnmount(){
      document.removeEventListener('click',this.hideContextMenu.bind(this))
    }
</code>```

```<code><Container>
                {this.renderSubNodes(treeFromConst)}
</code>```

After the change to pass the tree from server:

```<code>    componentDidMount(){
      this.props.getTree()
      document.addEventListener('click', this.hideContextMenu.bind(this))

    }
    componentWillUnmount(){
      document.removeEventListener('click',this.hideContextMenu.bind(this))
    }
</code>```

```<code><Container>
                {treeFromServer && this.renderSubNodes(treeFromServer)}
</code>```

Here is the link to CodeSandbox. I pass tree from const - https://codesandbox.io/s/github/krystianwolanski/ReactAndAspCoreTreeStructure/tree/master/ClientApp?file=/src/TreePage/TreePage.js

What is wrong? I've been tired of it for several days

答: I changed to window.addEventListener and it's working. Why? I don't know.</p>

Body:
I'm creating a tree structure in React, when I click the right button on any item list context menu appears and there I have various options to choose from. When I click on any of the options appears modal.

And it works. However, the situation changes when instead of specifying a tree structure made rigidly, I enter the tree downloaded from the server(passed by redux). Then suddenly after clicking on options from the context menu modal does not appear.

Before:

    componentDidMount(){
      //this.props.getTree()
      document.addEventListener('click', this.hideContextMenu.bind(this))

    }
    componentWillUnmount(){
      document.removeEventListener('click',this.hideContextMenu.bind(this))
    }

<Container>
                {this.renderSubNodes(treeFromConst)}

After the change to pass the tree from server:

    componentDidMount(){
      this.props.getTree()
      document.addEventListener('click', this.hideContextMenu.bind(this))

    }
    componentWillUnmount(){
      document.removeEventListener('click',this.hideContextMenu.bind(this))
    }

<Container>
                {treeFromServer && this.renderSubNodes(treeFromServer)}

Here is the link to CodeSandbox. I pass tree from const - https://codesandbox.io/s/github/krystianwolanski/ReactAndAspCoreTreeStructure/tree/master/ClientApp?file=/src/TreePage/TreePage.js

What is wrong? I've been tired of it for several days


问:
C program to count the character with the lowest frequency
I have written this code for finding the character with the minimum frequency.

So, giving in input "Hi, how is the weather todayy Dori", the output should be

The letter with the minimum frequency is ‘s’ and the frequency is 1.

But it shows

How to remove the that coma what is my mistake here

```<code>#include<stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 1000

int main()
{
    char str[MAX];
    int  fre[MAX],i,q,r,co=0,num;

    printf("The string : ");
    gets(str);

    for(q=0;str[q];q++);
    r=num=q;

    for(i=0;i<num;i++)
    {
        fre[i]=num;
        co=1;
        if(str[i])
        {

          for(q=i+1;q<num;q++)
          {

            if(tolower(str[i]) == tolower(str[q]))
         {
            {
                 co++;
                 str[q]='\0';
            }
          }
          fre[i]=co;
        if(co<=r)
         r=co;

       }

        }
    }
    printf("The letter with the minimum frequency is");
    for(q=0;q<num;q++)
        {

            if(fre[q]==r)
            {
                 printf(" '%c' ",str[q]);
            }
       }

    printf("and the frequency is %d \n ",r);

    return 0;
}
</code>```

答:
There's really no reason to read more than one character at a time.  In general, that's a good pattern to try and follow.  eg:</p>

```<code>#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <ctype.h>

int main(void)
{
        int c;
        int fre[26] = {0};
        printf("The string : ");
        while( (c = getchar()) != EOF ) {
                putchar(c);
                if( isalpha(c) ) {
                        fre[tolower(c) - 'a'] += 1;
                }
        }
        printf("The letter with the minimum frequency is");
        int idx = 0;
        int m = INT_MAX;
        for( int q = 0; q < 26; q++ ) {
                if( fre[q] > 0 && fre[q] < m ) {
                        idx = q;
                        m = fre[q];
                }
        }
        printf(" '%c', with frequency %d\n", idx + 'a', fre[idx]);
        return 0;
}
</code>```

Body:
I have written this code for finding the character with the minimum frequency.

So, giving in input "Hi, how is the weather todayy Dori", the output should be

The letter with the minimum frequency is ‘s’ and the frequency is 1.

But it shows

How to remove the that coma what is my mistake here

#include<stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 1000

int main()
{
    char str[MAX];
    int  fre[MAX],i,q,r,co=0,num;

    printf("The string : ");
    gets(str);

    for(q=0;str[q];q++);
    r=num=q;

    for(i=0;i<num;i++)
    {
        fre[i]=num;
        co=1;
        if(str[i])
        {

          for(q=i+1;q<num;q++)
          {

            if(tolower(str[i]) == tolower(str[q]))
         {
            {
                 co++;
                 str[q]='\0';
            }
          }
          fre[i]=co;
        if(co<=r)
         r=co;

       }

        }
    }
    printf("The letter with the minimum frequency is");
    for(q=0;q<num;q++)
        {

            if(fre[q]==r)
            {
                 printf(" '%c' ",str[q]);
            }
       }

    printf("and the frequency is %d \n ",r);

    return 0;
}

Body:
There's really no reason to read more than one character at a time.  In general, that's a good pattern to try and follow.  eg:

#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <ctype.h>

int main(void)
{
        int c;
        int fre[26] = {0};
        printf("The string : ");
        while( (c = getchar()) != EOF ) {
                putchar(c);
                if( isalpha(c) ) {
                        fre[tolower(c) - 'a'] += 1;
                }
        }
        printf("The letter with the minimum frequency is");
        int idx = 0;
        int m = INT_MAX;
        for( int q = 0; q < 26; q++ ) {
                if( fre[q] > 0 && fre[q] < m ) {
                        idx = q;
                        m = fre[q];
                }
        }
        printf(" '%c', with frequency %d\n", idx + 'a', fre[idx]);
        return 0;
}


问:
Ruby/Rails - Shrine::Error (storage :store isn't registered on ImageUploader)
For the last days, I'm trying to add a new storage config for my application, so we can use Cloudinary for images and Digital Ocean Spaces for other files.
And after the changes I supposed were needed for that, when I try to access a old model's attribute that's associated to an ImageUploader's Attacher, I get the this error:

Shrine::Error (storage :store isn't registered on ImageUploader)

The thing is: I dont have a storage "store" defined, indeed, but that's because I'm trying to have a image_store and a raw_store.

Here is my config/initializers/shrine.rb:

```<code># config/initializers/shrine.rb
require "shrine"
require "shrine/storage/file_system"
require "shrine/storage/cloudinary"
require "shrine/storage/s3"

Shrine.plugin :activerecord
Shrine.plugin :cached_attachment_data # for retaining the cached file across form redisplays
Shrine.plugin :restore_cached_data # re-extract metadata when attaching a cached file
Shrine.plugin :rack_file # for non-Rails apps
Shrine.plugin :default_storage, store: :image_store

s3_options = {
  access_key_id: ENV['DO_SPACE_ACCESS_KEY_ID'],
  secret_access_key: ENV['DO_SPACE_SECRET_ACCESS_KEY'],
  bucket: ENV['DO_SPACE_SECRET_BUCKET'],
  endpoint: "https://#{ENV['REGION']}.digitaloceanspaces.com",
  region: ENV['REGION']
}

if Rails.env.development? || Rails.env.test?
  Shrine.storages = {
    raw_cache: Shrine::Storage::FileSystem.new("public", prefix: "uploads/raw_cache"), # temporary
    raw_store: Shrine::Storage::FileSystem.new("public", prefix: "uploads/raw_store"),       # permanent
    image_cache: Shrine::Storage::FileSystem.new("public", prefix: "uploads/image_cache"), # temporary
    image_store: Shrine::Storage::FileSystem.new("public", prefix: "uploads/image_store")       # permanent
  }
else
  Shrine.storages = {
    raw_cache: Shrine::Storage::S3.new(
      prefix: "raw_cache", upload_options: { acl: 'public-read' }, **s3_options
    ), # for direct uploads
    raw_store: Shrine::Storage::S3.new(
      prefix: "raw_store", upload_options: { acl: 'public-read' }, **s3_options
    ),
    image_cache: Shrine::Storage::Cloudinary.new(prefix: "image_cache", resource_type: 'image'), # for direct uploads
    image_store: Shrine::Storage::Cloudinary.new(prefix: "image_store", resource_type: 'image'),
  }
end
</code>```

And here is my ImageUploader:

```<code>class ImageUploader < Shrine
  plugin :default_storage, cache: :image_cache, store: :image_store
  plugin :validation_helpers
  plugin :data_uri
  plugin :infer_extension

  plugin :upload_options, store: ->(io, context) do
    [...]
  end

  plugin :url_options, store: -> (io, **options) do
    [...]
  end

  # I even tried that one, but no success
  Attacher.default_store :image_store

  Attacher.validate do
    validate_max_size 5*1024*1024, message: "is too large (max is 5 MB)"
  end
end
</code>```

Could anyone help me on that?

答:
OK, I found the problem.

At first, I used to have only 2 storages in my Shrine initializer:

```<code>[...]
Shrine.storages = {
  cache: Shrine::Storage::Cloudinary.new(prefix: "image_cache", resource_type: 'image'), # for direct uploads
  store: Shrine::Storage::Cloudinary.new(prefix: "image_store", resource_type: 'image'),
  }
[...]
</code>```

And for that reason, now that I'm updating my storages, when I recover a record that was saved before, it's saved with "storage: store" in the attachment field, which doesn't match anymore with the old store's cloudinary configuration.

So, what it seems that what I need to do is: update storage's field of any file column I have in my DB, so it will match current configs.

Body:
For the last days, I'm trying to add a new storage config for my application, so we can use Cloudinary for images and Digital Ocean Spaces for other files.
And after the changes I supposed were needed for that, when I try to access a old model's attribute that's associated to an ImageUploader's Attacher, I get the this error:

Shrine::Error (storage :store isn't registered on ImageUploader)

The thing is: I dont have a storage "store" defined, indeed, but that's because I'm trying to have a image_store and a raw_store.

Here is my config/initializers/shrine.rb:

# config/initializers/shrine.rb
require "shrine"
require "shrine/storage/file_system"
require "shrine/storage/cloudinary"
require "shrine/storage/s3"

Shrine.plugin :activerecord
Shrine.plugin :cached_attachment_data # for retaining the cached file across form redisplays
Shrine.plugin :restore_cached_data # re-extract metadata when attaching a cached file
Shrine.plugin :rack_file # for non-Rails apps
Shrine.plugin :default_storage, store: :image_store

s3_options = {
  access_key_id: ENV['DO_SPACE_ACCESS_KEY_ID'],
  secret_access_key: ENV['DO_SPACE_SECRET_ACCESS_KEY'],
  bucket: ENV['DO_SPACE_SECRET_BUCKET'],
  endpoint: "https://#{ENV['REGION']}.digitaloceanspaces.com",
  region: ENV['REGION']
}

if Rails.env.development? || Rails.env.test?
  Shrine.storages = {
    raw_cache: Shrine::Storage::FileSystem.new("public", prefix: "uploads/raw_cache"), # temporary
    raw_store: Shrine::Storage::FileSystem.new("public", prefix: "uploads/raw_store"),       # permanent
    image_cache: Shrine::Storage::FileSystem.new("public", prefix: "uploads/image_cache"), # temporary
    image_store: Shrine::Storage::FileSystem.new("public", prefix: "uploads/image_store")       # permanent
  }
else
  Shrine.storages = {
    raw_cache: Shrine::Storage::S3.new(
      prefix: "raw_cache", upload_options: { acl: 'public-read' }, **s3_options
    ), # for direct uploads
    raw_store: Shrine::Storage::S3.new(
      prefix: "raw_store", upload_options: { acl: 'public-read' }, **s3_options
    ),
    image_cache: Shrine::Storage::Cloudinary.new(prefix: "image_cache", resource_type: 'image'), # for direct uploads
    image_store: Shrine::Storage::Cloudinary.new(prefix: "image_store", resource_type: 'image'),
  }
end

And here is my ImageUploader:

class ImageUploader < Shrine
  plugin :default_storage, cache: :image_cache, store: :image_store
  plugin :validation_helpers
  plugin :data_uri
  plugin :infer_extension

  plugin :upload_options, store: ->(io, context) do
    [...]
  end

  plugin :url_options, store: -> (io, **options) do
    [...]
  end

  # I even tried that one, but no success
  Attacher.default_store :image_store

  Attacher.validate do
    validate_max_size 5*1024*1024, message: "is too large (max is 5 MB)"
  end
end

Could anyone help me on that?

Body:
OK, I found the problem.

At first, I used to have only 2 storages in my Shrine initializer:

[...]
Shrine.storages = {
  cache: Shrine::Storage::Cloudinary.new(prefix: "image_cache", resource_type: 'image'), # for direct uploads
  store: Shrine::Storage::Cloudinary.new(prefix: "image_store", resource_type: 'image'),
  }
[...]

And for that reason, now that I'm updating my storages, when I recover a record that was saved before, it's saved with "storage: store" in the attachment field, which doesn't match anymore with the old store's cloudinary configuration.

So, what it seems that what I need to do is: update storage's field of any file column I have in my DB, so it will match current configs.


问:
Python compare two lists, add specific string to list if substring is in main list
I have a python bot which scrapes a website for data. Once it has the data it's filtered and the names are read clearly; this is list 1. Then, in list 2, I have strings of set names and I'm trying to compare list 2 to list 1 to see if list 1 contains one of any of the strings from list 2, and if it does, list 1 will have a string inserted into it showing that it contains a string from list 2. This is my loop:

```<code>for x in boss_bots:
    for index, y in enumerate(new_bots):
        if x in y[index]:
            new_bots.insert(index, 'Boss Bot')
</code>```

Here is the rest of the code

```<code>from selenium import webdriver
from time import sleep

boss_bots = ['Flunky', 'Pencil Pusher', 'Yesman', 'Micro manager', 'Downsizer', 'Head Hunter', 'Corporate Raider',
             'The Big Cheese']
cash_bots = ['Short Change', 'Penny Pincher', 'Tightwad', 'Bean Counter', 'Number Cruncher', 'Money Bags', 'Loan Shark',
             'Robber Baron']
sell_bots = ['Cold Caller', 'Telemarketer', 'Name Dropper', 'Glad Hander', 'Mover & Shaker', 'Two-Face', 'The Mingler',
             'Mr. Hollywood']
law_bots = ['Bottom Feeder', 'Blood sucker', 'Double Talker', 'Ambulance Chaser', 'Back Stabber', 'Spin Doctor',
            'Legal Eagle', 'Big Wig']

def format_box(bots):
    new_bots = []
    for string in bots:
        new_bot = string.replace('', ' ')
        new_bots.append(new_bot)
    return new_bots

def print_bots(bots):
    for i in bots:
        print(i)
        print()

def get_all_info():
    driver = webdriver.Chrome()
    driver.get("https://toonhq.org/invasions/")
    sleep(2)
    bots = driver.find_elements_by_class_name('media-body')
    info = [name.text for name in bots if name.text != '']
    new_bots = format_box(info)

    t = 0
    """    for index, (x, y) in enumerate(zip(boss_bots, info)):
        if x == y:
            new_bots.insert(index, 'Boss Bot')"""

    for x in boss_bots:
        for index, y in enumerate(new_bots):
            #print('Boss bots: ' + x + 'index: ' + str(index) + 'Bot list: ' + y)
            if x in y[index]:
                new_bots.insert(index, 'Boss Bot')

    print_bots(new_bots)
    driver.close()
    return info

get_all_info()
</code>```

答:
```<code>for s in newbots:
    if s in bossbots:
        s = s+'bossbot'
    else:
        continue

# Another possible method with list comprehension.
[s+'bossbot' for s in newbots if s in bossbots]

</code>```

Also another way of filtering blank space from your list. This would replace format_box.

```<code>newbots = list(filter(newbots, None))
</code>```

Body:
I have a python bot which scrapes a website for data. Once it has the data it's filtered and the names are read clearly; this is list 1. Then, in list 2, I have strings of set names and I'm trying to compare list 2 to list 1 to see if list 1 contains one of any of the strings from list 2, and if it does, list 1 will have a string inserted into it showing that it contains a string from list 2. This is my loop:

for x in boss_bots:
    for index, y in enumerate(new_bots):
        if x in y[index]:
            new_bots.insert(index, 'Boss Bot')

Here is the rest of the code

from selenium import webdriver
from time import sleep

boss_bots = ['Flunky', 'Pencil Pusher', 'Yesman', 'Micro manager', 'Downsizer', 'Head Hunter', 'Corporate Raider',
             'The Big Cheese']
cash_bots = ['Short Change', 'Penny Pincher', 'Tightwad', 'Bean Counter', 'Number Cruncher', 'Money Bags', 'Loan Shark',
             'Robber Baron']
sell_bots = ['Cold Caller', 'Telemarketer', 'Name Dropper', 'Glad Hander', 'Mover & Shaker', 'Two-Face', 'The Mingler',
             'Mr. Hollywood']
law_bots = ['Bottom Feeder', 'Blood sucker', 'Double Talker', 'Ambulance Chaser', 'Back Stabber', 'Spin Doctor',
            'Legal Eagle', 'Big Wig']

def format_box(bots):
    new_bots = []
    for string in bots:
        new_bot = string.replace('', ' ')
        new_bots.append(new_bot)
    return new_bots

def print_bots(bots):
    for i in bots:
        print(i)
        print()

def get_all_info():
    driver = webdriver.Chrome()
    driver.get("https://toonhq.org/invasions/")
    sleep(2)
    bots = driver.find_elements_by_class_name('media-body')
    info = [name.text for name in bots if name.text != '']
    new_bots = format_box(info)

    t = 0
    """    for index, (x, y) in enumerate(zip(boss_bots, info)):
        if x == y:
            new_bots.insert(index, 'Boss Bot')"""

    for x in boss_bots:
        for index, y in enumerate(new_bots):
            #print('Boss bots: ' + x + 'index: ' + str(index) + 'Bot list: ' + y)
            if x in y[index]:
                new_bots.insert(index, 'Boss Bot')

    print_bots(new_bots)
    driver.close()
    return info

get_all_info()

Body:
for s in newbots:
    if s in bossbots:
        s = s+'bossbot'
    else:
        continue

# Another possible method with list comprehension.
[s+'bossbot' for s in newbots if s in bossbots]

Also another way of filtering blank space from your list. This would replace format_box.

newbots = list(filter(newbots, None))


问:
Ordering a table that was created from a factor variable in r
Okay, so I have a data frame, df,  with one column: artist name.

```<code>        artist_name
1       Linkin Park
2         Lady Gaga
3        Pink Floyd
4       Linkin Park
5         Lady Gaga
6         Lady Gaga
</code>```

Artist name is a factor variable, and to see how many times each artist appears in this data frame, I would say:

table (df$artist_name)

The only problem is that in my project, I have 17,000s rows (and thousands of artists), and I only want to see the artists with the most appearances in the table. Because there are so many different artists, I am unable to find the most frequent artist names. I know that if I have a data frame, I can use the order () function, but is there any way to sort a table? Thanks so much

答:
We can sort the table output in descending order, extract the names of the first element

```<code>names(sort(table(df$artist_name), decreasing = TRUE)[1])
</code>```

If we need more than one, just change the number in the index to a range

```<code>names(sort(table(df$artist_name), decreasing = TRUE)[1:5])
</code>```

NOTE: No packages needed

Body:
Okay, so I have a data frame, df,  with one column: artist name.

        artist_name
1       Linkin Park
2         Lady Gaga
3        Pink Floyd
4       Linkin Park
5         Lady Gaga
6         Lady Gaga

Artist name is a factor variable, and to see how many times each artist appears in this data frame, I would say:

table (df$artist_name)

The only problem is that in my project, I have 17,000s rows (and thousands of artists), and I only want to see the artists with the most appearances in the table. Because there are so many different artists, I am unable to find the most frequent artist names. I know that if I have a data frame, I can use the order () function, but is there any way to sort a table? Thanks so much

Body:
We can sort the table output in descending order, extract the names of the first element

names(sort(table(df$artist_name), decreasing = TRUE)[1])

If we need more than one, just change the number in the index to a range

names(sort(table(df$artist_name), decreasing = TRUE)[1:5])

NOTE: No packages needed


答:
Access by getting keys </p>

```<code>filenames = uploaded.keys()

for file in filenames:
    data = uploaded[file]
</code>```

<p>If you have more than one file, just create a list for your data and append retrieved values. </p>

Title: Getting a file name after being loaded into Google Colab

Body:
What I want: to get the file name of the file that was just uploaded into Google Colab via the following code.

from google.colab import files
uploaded = files.upload()

I tried: printing the file once I uploaded it and I get the following output.

print(uploaded)
{'2019.06.01_Short Maintenance - Vehicle, Malibu_TGZ.csv': b'Year,Miles,$/Gallon,Total $,Vehicle\r\n6/1/2019,343.4,2.529,28,Malibu\r\n6/8/2019,34.3,2.529,5,Malibu\r\n6/8/2019,315.6,2.529,33.1,Malibu\r\n6/30/2019,323,2.399,30,Malibu\r\n7/5/2019,316.4,2.559,31,Malibu\r\n7/12/2019,334.6,2.529,30.45,Malibu\r\n7/21/2019,288.7,2.459,33.75,Malibu\r\n7/29/2019,336.7,2.419,28,Malibu\r\n8/6/2019,317.3,2.379,30.45,Malibu\r\n8/14/2019,340.9,2.359,30.1,Malibu\r\n8/22/2019,307.4,2.299,29.85,Malibu\r\n9/1/2019,239.1,2.279,29.7,Malibu\r\n9/14/2019,237.8,2.419,28.9,Malibu\r\n9/6/2019,288,2.469,30.4,Malibu\r\n10/13/2019,305.7,2.299,27.81,Malibu\r\n10/20/2019,330.7,2.369,30.05,Malibu\r\n11/8/2019,257,2.429,32.4,Malibu\r\n12/3/2019,249.3,2.319,5.01,Malibu\r\n12/7/2019,37.2,2.099,25,Malibu\r\n12/22/2019,276.4,2.229,29.4,Malibu\r\n1/12/2020,334,2.199,5,Malibu\r\n1/19/2020,51,2.009,28.15,Malibu\r\n2/8/2020,231.5,2.079,25.8,Malibu\r\n2/23/2020,254.7,2.159,25.75,Malibu\r\n3/19/2020,235.3,1.879,23.15,Malibu\r\n5/22/2020,303,1.699,23.15,Malibu\r\n'}

It appears to be a dic with the key as the file name, and value as a string of all the data in the file. I don't know how to ge the key value, assuming that is what I need to do.

Body:
Access by getting keys

filenames = uploaded.keys()

for file in filenames:
    data = uploaded[file]

If you have more than one file, just create a list for your data and append retrieved values.


问:
AWS Amplify mock in HTTPS
Using the following stack:

AWS amplify

NodeJS

ReactJS (built using create-react-app)

When running amplify mock it automatically assigns an endpoint with HTTP (as can be seen in the terminal and the aws-exports.js file).

I am however hosting my app locally in an HTTPS environment using ($env:HTTPS="true") -and (npm start) so as to better accommodate the social sign-ins which usually require all requests to come from HTTPS even if on localhost.

I constantly have to change my env to HTTP to try out things with the mock backend instead of just maintaining everything in HTTPS.

Is there a way to let the mock backend be served over HTTPS?

答:
I have found a partial answer.

using the chrome browser settings, select privacy and security and go to site settings.

Add the URLS you are requesting over http into the insecure content allowable section. This allows an origin of https to request over http.

Title: AWS Amplify mock in HTTPS


问:
Getting crontab "permission denied" on Python script even though it has executable permissions
I have a python script set to go off every minute in my crontab file:

*/1 * * * * ~/ticker.py

I've set permissions of ticker.py with chmod +x ticker.py to make the file executable.

I am still getting /bin/sh: /home/ec2-user/ticker.py: Permission denied in my /var/spool/mail/ec2-user mail file.

I'm using an Amazon Linux EC2 instance. I appreciate any help with this. Thank you

答:
Found out the fix. Super simple but unsure why the #!/usr/bin/env shebang didn't fix it in the first place.

I replaced */1 * * * * ~/ticker.py with */1 * * * * python ~/ticker.py.

Thanks for the input.


问:
gRPC do client options override server options?
I have a gRPC server implemented in the python API and on it I set several options like so:

```<code>options=[
      ('grpc.max_send_message_length', 500 * 1024 * 1024),
      ('grpc.max_receive_message_length', 500 * 1024 * 1024),
      ('GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA', 0),
      ('grpc.keepalive_time_ms', 300000),
]
server = grpc.server(futures.ThreadPoolExecutor(max_workers=4), options=options)
</code>```

We up the default message length to 500 MB from the default of 4 MB.  One of my users is seeing the following error:

```<code>io.grpc.StatusRuntimeException: RESOURCE_EXHAUSTED: gRPC message exceeds maximum size 4194304: 5224306
</code>```

What I'm trying to figure out is if its possible a client side setting could override my server settings?

Otherwise, is there a problem with the way I'm setting the server options on message length?

答: The grpc.max_{send,receive}_message_length options on the client and server are enforced locally at each end, independent of each other. So, for example, the client would need to set grpc.max_receive_message_length a number like you have here to accept the large messages that the server is sending, no matter what the server settings are.

Body:
I have a gRPC server implemented in the python API and on it I set several options like so:

options=[
      ('grpc.max_send_message_length', 500 * 1024 * 1024),
      ('grpc.max_receive_message_length', 500 * 1024 * 1024),
      ('GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA', 0),
      ('grpc.keepalive_time_ms', 300000),
]
server = grpc.server(futures.ThreadPoolExecutor(max_workers=4), options=options)

We up the default message length to 500 MB from the default of 4 MB.  One of my users is seeing the following error:

io.grpc.StatusRuntimeException: RESOURCE_EXHAUSTED: gRPC message exceeds maximum size 4194304: 5224306

What I'm trying to figure out is if its possible a client side setting could override my server settings?

Otherwise, is there a problem with the way I'm setting the server options on message length?