问:
Debugging Cypress tests in Visual Studio Code
I want to use VS Code to edit and debug Cypress tests.  The cypress docs mention VS Code directly, but don't give any clues about how to configure VS Code's launch.json file for debugging either there or on the debugging page.

I have a launch.json configuration that starts cypress/electron, but VS Code gives this error:

Cannot connect to runtime process… connect ECONNREFUSED 127.0.0.1:5858

Then shuts it down.

Looking at the sample electron for VS Code project doesn't help, and adding protocol or program attributes didn't work.

Here is my configuration:

{
    "name": "Start integration_tests",
    "type": "node",
    "request": "launch",
    "stopOnEntry": false,
    "cwd": "${workspaceRoot}",
    "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/cypress",
    "runtimeArgs": [
        "open"
    ],
    "console" : "internalConsole",
    "port": 5858,
}
```

答:
@fhilton's answer used to work, but with newer versions of Cypress, it will cause Chrome to not be able to connect to the test runner and not run any tests. Use this instead:

If you or any of your co-workers develop in Windows, run npm i -D cross-env.

In package.json add a script to start the Cypress test runner (or if you already have a script that says something like cypress open then just modify that). You want the script to set the CYPRESS_REMOTE_DEBUGGING_PORT environment variable to something like 9222 before it runs cypress open. Since I use Windows, I use the cross-env npm package to set environment variables. Therefore, the script in my package.json looks like

"scripts": {
  "cypr": "cross-env CYPRESS_REMOTE_DEBUGGING_PORT=9222 cypress open",
},
```
<p>I got the idea of doing that from here and here. The rest of this answer is mostly what @fhilton wrote in his answer so most of the credit goes to them.</p>
</li>
<li><p>Add the following to the list of <code>configurations</code> in your launch.json (note the same port as above)</p>
<pre class="lang-json prettyprint-override"><code>{
    "type": "chrome",
    "request": "attach",
    "name": "Attach to Cypress Chrome",
    "port": 9222,
    "urlFilter": "http://localhost*",
    "webRoot": "${workspaceFolder}",
    "sourceMaps": true,
    "skipFiles": [
        "cypress_runner.js",
    ],
},
</code>```

Put the word debugger in your test. See Cypress Doc on debugging. Or, if you are confident in your source maps, put a breakpoint in your code with vscode.

Run npm run cypr (or whatever you called your npm script)

From the Cypress test runner, start your tests running in Chrome

Start the vscode debugger with your new "Attach to Cypress Chrome" configuration

Restart the test with breakpoint in it and debug away!

Body:
@fhilton's answer used to work, but with newer versions of Cypress, it will cause Chrome to not be able to connect to the test runner and not run any tests. Use this instead:

If you or any of your co-workers develop in Windows, run npm i -D cross-env.

In package.json add a script to start the Cypress test runner (or if you already have a script that says something like cypress open then just modify that). You want the script to set the CYPRESS_REMOTE_DEBUGGING_PORT environment variable to something like 9222 before it runs cypress open. Since I use Windows, I use the cross-env npm package to set environment variables. Therefore, the script in my package.json looks like

"scripts": {
  "cypr": "cross-env CYPRESS_REMOTE_DEBUGGING_PORT=9222 cypress open",
},

I got the idea of doing that from here and here. The rest of this answer is mostly what @fhilton wrote in his answer so most of the credit goes to them.

Add the following to the list of configurations in your launch.json (note the same port as above)

{
    "type": "chrome",
    "request": "attach",
    "name": "Attach to Cypress Chrome",
    "port": 9222,
    "urlFilter": "http://localhost*",
    "webRoot": "${workspaceFolder}",
    "sourceMaps": true,
    "skipFiles": [
        "cypress_runner.js",
    ],
},

Put the word debugger in your test. See Cypress Doc on debugging. Or, if you are confident in your source maps, put a breakpoint in your code with vscode.

Run npm run cypr (or whatever you called your npm script)

From the Cypress test runner, start your tests running in Chrome

Start the vscode debugger with your new "Attach to Cypress Chrome" configuration

Restart the test with breakpoint in it and debug away!


来源: stackexchange

问:
CS0119 in compiling C#, Error at Task parameters
I've been working on a Discord Bot, and I get a really bad error.

I'm a beginner. I'm sorry if it's a dumb error, I probably didn't even knew C# basics more than a month ago.

private async Task Filter(SocketMessage arg)
{

}

public async Task StartInterpretation()
{
    await Filter(SocketMessage arg);
}
```

This is a small example that makes the error i'm getting. the await Filter(SocketMessage arg) causes this error:

error CS0119: 'SocketMessage' is a type, which is not valid in the given context

(the error is something with parameters as i can see.)

答:
You'll need to initialize arg, then pass into the Filter function. Something like:</p>

```<code>public async Task StartInterpretation()
{
    var arg= new SocketMessage();
    await Filter(arg);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've been working on a Discord Bot, and I get a really bad error.

I'm a beginner. I'm sorry if it's a dumb error, I probably didn't even knew C# basics more than a month ago.

private async Task Filter(SocketMessage arg)
{

}

public async Task StartInterpretation()
{
    await Filter(SocketMessage arg);
}

This is a small example that makes the error i'm getting. the await Filter(SocketMessage arg) causes this error:

error CS0119: 'SocketMessage' is a type, which is not valid in the given context

(the error is something with parameters as i can see.)

Body:
You'll need to initialize arg, then pass into the Filter function. Something like:

public async Task StartInterpretation()
{
    var arg= new SocketMessage();
    await Filter(arg);
}


问:
How to return JSX from a method in React?
I'm pretty new to React, I'm trying to return a JSX from a method, code as follows:

import React, { useReducer } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';

const formatName = (user) => {
    return user.firstName + ' ' + user.lastName;
}

const getGreeting = (user) => {
    if (user) {
        return {greeting}
    }
    else {
        return {forbidden}
    }
}

const user = {
    firstName: 'John',
    lastName: 'Smith'
};

const greeting = (

Hello {formatName(user)}

);

const forbidden = (

Hello stranger!

);

const element = (

{getGreeting(user)}

);

ReactDOM.render(
    element, document.getElementById('root')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div></code>```

As you can see, element contains a div which I wish to render getGreeting, since user == true, it should return greeting, which calls the method formatName. However it returns an error:

```<code>Error: Objects are not valid as a React child (found: object with keys {greeting}). If you meant to render a collection of children, use an array instead.
</code>```

What am I doing wrong here?

答: Change return {greeting} to return greeting without the bracket.

Body:
I'm pretty new to React, I'm trying to return a JSX from a method, code as follows:

import React, { useReducer } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';

const formatName = (user) => {
    return user.firstName + ' ' + user.lastName;
}

const getGreeting = (user) => {
    if (user) {
        return {greeting}
    }
    else {
        return {forbidden}
    }
}

const user = {
    firstName: 'John',
    lastName: 'Smith'
};

const greeting = (

Hello {formatName(user)}

);

const forbidden = (

Hello stranger!

);

const element = (

{getGreeting(user)}

);

ReactDOM.render(
    element, document.getElementById('root')
);

As you can see, element contains a div which I wish to render getGreeting, since user == true, it should return greeting, which calls the method formatName. However it returns an error:

Error: Objects are not valid as a React child (found: object with keys {greeting}). If you meant to render a collection of children, use an array instead.

What am I doing wrong here?


问:
Uploading Image in Django: 'utf-8' codec can't decode byte 0x89 in position 246: invalid start byte
I'm trying to upload images in my api using pure json, but when i tried to upload image in request.Files and the token in request.body, I face this error:

```<code>UnicodeDecodeError at /api/auth/set-profile-image/
'utf-8' codec can't decode byte 0x89 in position 246: invalid start byte
</code>```

and it says:

```<code>Unicode error hint
The string that could not be encoded/decoded was: " �PNG
</code>```

but i'm sending JPG! :D

View.py

@csrf_exempt
def set_profile_image(request):
    if request.method == 'POST':
        request_info = json.loads(request.body)
        token = request_info.get('token')
        img = request.FILES['image']
        if token is not None and img is not None:
            user = User.objects.filter(token=token)
            if user.exists():
                user = user.get()
                form = UploadImage(request.POST, request.FILES['image'])
                if form.is_valid():
                    user.profile_image = form.cleaned_data['image']
                    user.save()
                    response = {
                        'status_code': 200,
                        'image_set': True,
                        'image_url': user.profile_image.url
                    }
```

<p>Form.py</p>

<pre class="lang-py prettyprint-override"><code>from django import forms

class UploadImage(forms.Form):
    image = forms.ImageField()
</code>```

and my test code is:

import requests

data = {
    'token': 'helloworld1--_aFsV-ZVG9lVpi0KSydrx3pG3TSMPqqHVKWD2Yc8bE'
}

url = 'http://localhost:8000/api/auth/set-profile-image/'

with open('test.jpg', 'rb') as img:

    response = requests.post(
        url=url,
        data=data,
        files={
            'image': img
        }
    )

    # print(response.text)
    f = open('test.html', 'wb')
    f.write(response.content)
    f.close()
```

I'm using ImageField as my db field in models.py

Warmest Regards,
Poor Maintenance guy who's stuck in others code!

答:
Images are going to contain data which is not safe to represent in UTF-8. If you need to transport image data this way, you should encode it into something else first which is safe in UTF-8, such as base64.

To do this in your Python sender, you can use something like base64.b64encode(img)

And to decode it again on the other side, you will need to use base64.b64decode(img)

Body:
I'm trying to upload images in my api using pure json, but when i tried to upload image in request.Files and the token in request.body, I face this error:

UnicodeDecodeError at /api/auth/set-profile-image/
'utf-8' codec can't decode byte 0x89 in position 246: invalid start byte

and it says:

Unicode error hint
The string that could not be encoded/decoded was: " �PNG

but i'm sending JPG! :D

View.py

@csrf_exempt
def set_profile_image(request):
    if request.method == 'POST':
        request_info = json.loads(request.body)
        token = request_info.get('token')
        img = request.FILES['image']
        if token is not None and img is not None:
            user = User.objects.filter(token=token)
            if user.exists():
                user = user.get()
                form = UploadImage(request.POST, request.FILES['image'])
                if form.is_valid():
                    user.profile_image = form.cleaned_data['image']
                    user.save()
                    response = {
                        'status_code': 200,
                        'image_set': True,
                        'image_url': user.profile_image.url
                    }

Form.py

from django import forms

class UploadImage(forms.Form):
    image = forms.ImageField()

and my test code is:

import requests

data = {
    'token': 'helloworld1--_aFsV-ZVG9lVpi0KSydrx3pG3TSMPqqHVKWD2Yc8bE'
}

url = 'http://localhost:8000/api/auth/set-profile-image/'

with open('test.jpg', 'rb') as img:

    response = requests.post(
        url=url,
        data=data,
        files={
            'image': img
        }
    )

    # print(response.text)
    f = open('test.html', 'wb')
    f.write(response.content)
    f.close()

I'm using ImageField as my db field in models.py

Warmest Regards,
Poor Maintenance guy who's stuck in others code!


问:
Can a JS script block a whole server? If so, how can I possibly get rid of this attack?
We are using MySQL db and Apache as our server. All of our project folders are affected by a particular script called "y.js/a.js" which is blocking our whole .js files and sits before  that triggers 404 error. The URL it all refers to is https://tom.verybeatifulantony.com/a.js (or) https://tom.verybeatifulantony.com/y.js. It calls this same js files in each and every project.

The following are the screenshots below:

答:
Our files are affected, too. Where or how do I have to execute the following you wrote?

sudo grep --include=*.{js,html,htm,php} -rnw '.' -e "tom.verybeatifulantony.com"

Would you be so kind and give me a manual....


问:
Tuple Unpacking and Generating variable name automatically using a loop
I have a function which returns 4 lists.

```<code>def foo ( Input1, input 2)
    return list1, list2, list3, list 4
</code>```

I am using following code right now:

```<code>x0, y0, z0, w0 = foo(ip0, ip4)
x1, y1, z1, w1 = foo(ip3, ip1)
x2, y2, z2, w2 = foo(ip3, ip4)
x3, y3, z3, w3 = foo(ip1, ip2)
</code>```

I want to reduce the number of lines and may be use a for loop.

I tried while loop:

```<code>i=0
while i<3:
    'x'+str(i), 'y'+str(i),'z'+str(i),'w'+str(i)= foo(input[i], input[i])
    i +=1
</code>```

Python is throwing an error, it thinks I am assigning a value to a string. How do I unpack the tuple and generate variable name using a loop or automatically?

答:
You can do something like this:</p>

```<code>def MyFunction(arg1, arg2):

    list1 = [arg1, arg2]
    list2 = [arg2, arg1]

    return list1, list2

# create empty dictionary:
my_dictionary = {}

# iterate in given range:
for index in range(4):

    # get output of function:
    list1, list2 = MyFunction(1, 2)

    # assign output to dictionary:
    single_dictionary_entry = {
        'x' + str(index) : list1,
        'y' + str(index) : list2,
    }

    # update original dictionary with new entry:
    my_dictionary.update(single_dictionary_entry)

# print result:
print(my_dictionary)
</code>```

Body:
I have a function which returns 4 lists.

def foo ( Input1, input 2)
    return list1, list2, list3, list 4

I am using following code right now:

x0, y0, z0, w0 = foo(ip0, ip4)
x1, y1, z1, w1 = foo(ip3, ip1)
x2, y2, z2, w2 = foo(ip3, ip4)
x3, y3, z3, w3 = foo(ip1, ip2)

I want to reduce the number of lines and may be use a for loop.

I tried while loop:

i=0
while i<3:
    'x'+str(i), 'y'+str(i),'z'+str(i),'w'+str(i)= foo(input[i], input[i])
    i +=1

Python is throwing an error, it thinks I am assigning a value to a string. How do I unpack the tuple and generate variable name using a loop or automatically?

Body:
You can do something like this:

def MyFunction(arg1, arg2):

    list1 = [arg1, arg2]
    list2 = [arg2, arg1]

    return list1, list2

# create empty dictionary:
my_dictionary = {}

# iterate in given range:
for index in range(4):

    # get output of function:
    list1, list2 = MyFunction(1, 2)

    # assign output to dictionary:
    single_dictionary_entry = {
        'x' + str(index) : list1,
        'y' + str(index) : list2,
    }

    # update original dictionary with new entry:
    my_dictionary.update(single_dictionary_entry)

# print result:
print(my_dictionary)


答:
getGreeting should return a JSX and not an object

try this:

```<code>const greeting = (
    <h1>Hello {formatName(user)}</h1>
);

const forbidden = (
    <h1>Hello stranger!</h1>
);

const getGreeting = (user) => {
    if (user) {
        return greeting
    }
    else {
        return forbidden
    }
}
</code>```

Title: How to return JSX from a method in React?

Body:
getGreeting should return a JSX and not an object

try this:

const greeting = (
    <h1>Hello {formatName(user)}</h1>
);

const forbidden = (
    <h1>Hello stranger!</h1>
);

const getGreeting = (user) => {
    if (user) {
        return greeting
    }
    else {
        return forbidden
    }
}


问:
Resetting Select2 value in dropdown with reset button
What would be the best way to reset the selected item to default? I'm using Select2 library and when using a normal button type="reset", the value in the dropdown doesn't reset.

So when I press my button I want "All" to be shown again.

jQuery

```<code>$("#d").select2();
</code>```

html

```<code><select id="d" name="d">
  <option selected disabled>All</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
</code>```

答:
Just to that :)</p>

```<code>$('#form-edit').trigger("reset");
$('#form-edit').find('select').each(function(){
  $(this).change();
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What would be the best way to reset the selected item to default? I'm using Select2 library and when using a normal button type="reset", the value in the dropdown doesn't reset.

So when I press my button I want "All" to be shown again.

jQuery

$("#d").select2();

html

<select id="d" name="d">
  <option selected disabled>All</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

Body:
Just to that :)

$('#form-edit').trigger("reset");
$('#form-edit').find('select').each(function(){
  $(this).change();
});


问:
jsf dynamic change of managedbean
How can I dynamically change managed bean of "value" attribute? For example, I have h:inputText and, depending on typed-in text, managed bean must be #{studentBean.login} or #{lecturerBean.login}. In a simplified form:

```<code><h:inputText id="loginField" value="#{'nameofbean'.login}" />
</code>```

I tried to embed another el-expression instead of 'nameofbean':

```<code>value="#{{userBean.specifyLogin()}.login}"
</code>```

but it doesn't worked out.

答:
Another way: </p>

```<code><h:inputText id="loginField1" value="#{bean1.login}" rendered="someCondition1"/>
<h:inputText id="loginField2" value="#{bean2.login}" rendered="someCondition2"/>
</code>```

Title: jsf dynamic change of managedbean

Body:
How can I dynamically change managed bean of "value" attribute? For example, I have h:inputText and, depending on typed-in text, managed bean must be #{studentBean.login} or #{lecturerBean.login}. In a simplified form:

<h:inputText id="loginField" value="#{'nameofbean'.login}" />

I tried to embed another el-expression instead of 'nameofbean':

value="#{{userBean.specifyLogin()}.login}"

but it doesn't worked out.

Body:
Another way:

<h:inputText id="loginField1" value="#{bean1.login}" rendered="someCondition1"/>
<h:inputText id="loginField2" value="#{bean2.login}" rendered="someCondition2"/>


问:
Dapper provide default name for dynamic result sets with QueryMultiple
TLDR; Is there a way (using a type map or some other solution) to give dynamic result sets a default name, such as "(No Column Name)" in Dapper when no column name is supplied?

I am writing a query editor that allows users to write and run user-supplied queries against MS SQL Server databases. I've been using Dapper for all our querying and it has been working beautifully for 99% of what we need. I've hit a snag though and I'm hoping someone has a solution.

The query editor is similar to SSMS. I don't know ahead of time what the script will look like, what the shape or type the result set(s) will be, or even how many result sets will be returned. For this reason, I've been batching the scripts and using Dapper's QueryMultiple to read dynamic results from the GridReader. The results are then sent to a third party UI data grid (WPF). The data grid knows how to consume dynamic data and the only thing it requires to display a given row is at least one key value pair with a non-null, but not necessarily unique key and a nullable value. So far, so good.

The simplified version of the Dapper call looks something like this:

```<code>        public async Task<IEnumerable<IEnumerable<T>>> QueryMultipleAsync<T>(string sql,
                                                                             object parameters,
                                                                             string connectionString,
                                                                             CommandType commandType = CommandType.Text,
                                                                             CancellationTokenSource cancellationTokenSource = null)
        {
            using (IDbConnection con = _dbConnectionFactory.GetConnection(connectionString))
            {

                con.Open();
                var transaction = con.BeginTransaction();

                var sqlBatches = sql
                    .ToUpperInvariant()
                    .Split(new[] { " GO ", "\r\nGO ", "\n\nGO ", "\nGO\n", "\tGO ", "\rGO "}, StringSplitOptions.RemoveEmptyEntries);

                var batches = new List<CommandDefinition>();

                foreach(var batch in sqlBatches)
                {
                    batches.Add(new CommandDefinition(batch, parameters, transaction, null, commandType, CommandFlags.Buffered, cancellationTokenSource.Token));
                }

                var resultSet = new List<List<T>>();

                foreach (var commandDefinition in batches)
                {
                    using (GridReader reader = await con.QueryMultipleAsync(commandDefinition))
                    {
                        while (!reader.IsConsumed)
                        {
                            try
                            {
                                var result = (await reader.ReadAsync<T>()).AsList();
                                if (result.FirstOrDefault() is IDynamicMetaObjectProvider)
                                {
                                    (result as List<dynamic>).ConvertNullKeysToNoColumnName();
                                }
                                resultSet.Add(result);
                            }
                            catch(Exception e)
                            {
                                if(e.Message.Equals("No columns were selected"))
                                {
                                    break;
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                    }
                }
                try
                {
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(ex.ToString());
                    if (transaction != null)
                    {
                        transaction.Rollback();
                    }
                }

                return resultSet;
            }
        }

public static IEnumerable<dynamic> ConvertNullKeysToNoColumnName<dynamic>(this IEnumerable<dynamic> rows)
        {
            foreach (var row in rows)
            {
                if (row is IDictionary<string, object> rowDictionary)
                {
                    if (rowDictionary == null) continue;

                    rowDictionary.Where(x => string.IsNullOrEmpty(x.Key)).ToList().ForEach(x =>
                    {
                        var val = rowDictionary[x.Key];

                        if (x.Value == val)
                        {
                            rowDictionary.Remove(x);
                            rowDictionary.Add("(No Column Name)", val);
                        }
                        else
                        {
                            Trace.WriteLine("Something went wrong");
                        }
                    });
                }
            }
            return rows;
        }

</code>```

This works with most queries (and for queries with only one unnamed result column), but the problem manifests when the user writes a query with more than one unnamed column like this:

select COUNT(*), MAX(create_date) from sys.databases.

In this case, Dapper returns a DapperRow that looks something like this:

{DapperRow,  = '9',  = '2/14/2020 9:51:54 AM'}

So the result set is exactly what the user asks for (i.e., values with no names or aliases) but I need to supply (non-unique) keys for all data in the grid...

My first thought was to simply change the null keys in the DapperRow object to a default value (like '(No Column Name)'), as it appears to be optimized for storage so table keys are only stored once in the object (which is nice and would provide a nice performance bonus for queries with huge result sets). The DapperRow type is private though. After searching around, I found that I could cast the DapperRow to an IDictionary<string, object> to access keys and values for the object, and even set and remove values. That's where the ConvertNullKeysToNoColumnName extension method comes from. And it works... But only once.

Why? Well, it appears that when you have multiple null or empty keys in a DapperRow that gets cast to an IDictionary<string,object> and you call the Remove(x) function (where x is the entire item OR just the key for any single item with a null or empty key), all subsequent attempts to resolve other values with a null or empty key via the indexer item[key] fail to retrieve a value--even if the additional key value pairs still exist in the object.

In other words, I can't remove or replace subsequent empty keys after the first one is removed.

Am I missing something obvious? Do I just need to alter the DapperRow via reflection and hope it doesn't have any weird side affects or that the underlying data structure doesn't change later? Or do I take the performance/memory hit and just copy/map the entire potentially large result set into a new sequence to give empty keys a default value at runtime?

答:
I suspect this is because the dynamic DapperRow object is actually not a 'normal' dictionary. It can have several entries with the same key. You can see this if you inspect the object in the debugger.

When you reference rowDictionary[x.Key], I suspect you will always get the first unnamed column.

If you call rowDictionary.Remove(""); rowDictionary.Remove("");, you actually only remove the first entry - the second is still present, even though rowDictionary.ContainsKey("") returns false.

You can Clear() and rebuild the entire dictionary.
At that point, you're really not gaining much by using a dynamic object.

```<code>if (row is IDictionary<string, object>)
{
    var rowDictionary = row as IDictionary<string, object>;
    if (rowDictionary.ContainsKey(""))
    {
        var kvs = rowDictionary.ToList();
        rowDictionary.Clear();

        for (var i = 0; i < kvs.Count; ++i)
        {
            var kv = kvs[i];

            var key = kv.Key == ""? $"(No Column <{i + 1}>)" : kv.Key;
            rowDictionary.Add(key, kv.Value);
        }
    }
}
</code>```

Since you're working with unknown result structure, and just want to pass it to a grid view, I would consider using a DataTable instead.

You can still keep Dapper for parameter handling:

```<code>foreach (var commandDefinition in batches)
{
    using(var reader = await con.ExecuteReaderAsync(commandDefinition)) {
        while(!reader.IsClosed) {
            var table = new DataTable();
            table.Load(reader);
            resultSet.Add(table);
        }
    }
}
</code>```

Body:
TLDR; Is there a way (using a type map or some other solution) to give dynamic result sets a default name, such as "(No Column Name)" in Dapper when no column name is supplied?

I am writing a query editor that allows users to write and run user-supplied queries against MS SQL Server databases. I've been using Dapper for all our querying and it has been working beautifully for 99% of what we need. I've hit a snag though and I'm hoping someone has a solution.

The query editor is similar to SSMS. I don't know ahead of time what the script will look like, what the shape or type the result set(s) will be, or even how many result sets will be returned. For this reason, I've been batching the scripts and using Dapper's QueryMultiple to read dynamic results from the GridReader. The results are then sent to a third party UI data grid (WPF). The data grid knows how to consume dynamic data and the only thing it requires to display a given row is at least one key value pair with a non-null, but not necessarily unique key and a nullable value. So far, so good.

The simplified version of the Dapper call looks something like this:

        public async Task<IEnumerable<IEnumerable<T>>> QueryMultipleAsync<T>(string sql,
                                                                             object parameters,
                                                                             string connectionString,
                                                                             CommandType commandType = CommandType.Text,
                                                                             CancellationTokenSource cancellationTokenSource = null)
        {
            using (IDbConnection con = _dbConnectionFactory.GetConnection(connectionString))
            {

                con.Open();
                var transaction = con.BeginTransaction();

                var sqlBatches = sql
                    .ToUpperInvariant()
                    .Split(new[] { " GO ", "\r\nGO ", "\n\nGO ", "\nGO\n", "\tGO ", "\rGO "}, StringSplitOptions.RemoveEmptyEntries);

                var batches = new List<CommandDefinition>();

                foreach(var batch in sqlBatches)
                {
                    batches.Add(new CommandDefinition(batch, parameters, transaction, null, commandType, CommandFlags.Buffered, cancellationTokenSource.Token));
                }

                var resultSet = new List<List<T>>();

                foreach (var commandDefinition in batches)
                {
                    using (GridReader reader = await con.QueryMultipleAsync(commandDefinition))
                    {
                        while (!reader.IsConsumed)
                        {
                            try
                            {
                                var result = (await reader.ReadAsync<T>()).AsList();
                                if (result.FirstOrDefault() is IDynamicMetaObjectProvider)
                                {
                                    (result as List<dynamic>).ConvertNullKeysToNoColumnName();
                                }
                                resultSet.Add(result);
                            }
                            catch(Exception e)
                            {
                                if(e.Message.Equals("No columns were selected"))
                                {
                                    break;
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                    }
                }
                try
                {
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(ex.ToString());
                    if (transaction != null)
                    {
                        transaction.Rollback();
                    }
                }

                return resultSet;
            }
        }

public static IEnumerable<dynamic> ConvertNullKeysToNoColumnName<dynamic>(this IEnumerable<dynamic> rows)
        {
            foreach (var row in rows)
            {
                if (row is IDictionary<string, object> rowDictionary)
                {
                    if (rowDictionary == null) continue;

                    rowDictionary.Where(x => string.IsNullOrEmpty(x.Key)).ToList().ForEach(x =>
                    {
                        var val = rowDictionary[x.Key];

                        if (x.Value == val)
                        {
                            rowDictionary.Remove(x);
                            rowDictionary.Add("(No Column Name)", val);
                        }
                        else
                        {
                            Trace.WriteLine("Something went wrong");
                        }
                    });
                }
            }
            return rows;
        }

This works with most queries (and for queries with only one unnamed result column), but the problem manifests when the user writes a query with more than one unnamed column like this:

select COUNT(*), MAX(create_date) from sys.databases.

In this case, Dapper returns a DapperRow that looks something like this:

{DapperRow,  = '9',  = '2/14/2020 9:51:54 AM'}

So the result set is exactly what the user asks for (i.e., values with no names or aliases) but I need to supply (non-unique) keys for all data in the grid...

My first thought was to simply change the null keys in the DapperRow object to a default value (like '(No Column Name)'), as it appears to be optimized for storage so table keys are only stored once in the object (which is nice and would provide a nice performance bonus for queries with huge result sets). The DapperRow type is private though. After searching around, I found that I could cast the DapperRow to an IDictionary<string, object> to access keys and values for the object, and even set and remove values. That's where the ConvertNullKeysToNoColumnName extension method comes from. And it works... But only once.

Why? Well, it appears that when you have multiple null or empty keys in a DapperRow that gets cast to an IDictionary<string,object> and you call the Remove(x) function (where x is the entire item OR just the key for any single item with a null or empty key), all subsequent attempts to resolve other values with a null or empty key via the indexer item[key] fail to retrieve a value--even if the additional key value pairs still exist in the object.

In other words, I can't remove or replace subsequent empty keys after the first one is removed.

Am I missing something obvious? Do I just need to alter the DapperRow via reflection and hope it doesn't have any weird side affects or that the underlying data structure doesn't change later? Or do I take the performance/memory hit and just copy/map the entire potentially large result set into a new sequence to give empty keys a default value at runtime?

Body:
I suspect this is because the dynamic DapperRow object is actually not a 'normal' dictionary. It can have several entries with the same key. You can see this if you inspect the object in the debugger.

When you reference rowDictionary[x.Key], I suspect you will always get the first unnamed column.

If you call rowDictionary.Remove(""); rowDictionary.Remove("");, you actually only remove the first entry - the second is still present, even though rowDictionary.ContainsKey("") returns false.

You can Clear() and rebuild the entire dictionary.
At that point, you're really not gaining much by using a dynamic object.

if (row is IDictionary<string, object>)
{
    var rowDictionary = row as IDictionary<string, object>;
    if (rowDictionary.ContainsKey(""))
    {
        var kvs = rowDictionary.ToList();
        rowDictionary.Clear();

        for (var i = 0; i < kvs.Count; ++i)
        {
            var kv = kvs[i];

            var key = kv.Key == ""? $"(No Column <{i + 1}>)" : kv.Key;
            rowDictionary.Add(key, kv.Value);
        }
    }
}

Since you're working with unknown result structure, and just want to pass it to a grid view, I would consider using a DataTable instead.

You can still keep Dapper for parameter handling:

foreach (var commandDefinition in batches)
{
    using(var reader = await con.ExecuteReaderAsync(commandDefinition)) {
        while(!reader.IsClosed) {
            var table = new DataTable();
            table.Load(reader);
            resultSet.Add(table);
        }
    }
}


问:
SQL - Dividing aggregated fields, very new to SQL
I have list of line items from invoices with a field that indicates if a line was delivered or picked up. I need to find a percentage of delivered items from the total number of lines.

SALES_NBR | Total | Deliveryrate

1 = Delivered 0 = picked up from FULFILLMENT.

```<code>SELECT SALES_NBR,
COUNT (ITEMS) as Total,
SUM (case when FULFILLMENT = '1' then 1 else 0 end) as delivered,
(SELECT delivered/total) as Deliveryrate
FROM Invoice_table
WHERE STORE IN '0123'
And SALE_DATE >='2020-02-01'
And SALE_DATE <='2020-02-07'
Group By SALES_NBR, Deliveryrate;
</code>```

My query executes but never finishes for some reason. Is there any easier way to do this? Fulfillment field does not contain any NULL values.

Any help would be appreciated.

答:
If you want to get a "nice" query, you can use subqueries like this:

```<code>select
  qry.*,
  qry.delivered/qry.total as Deliveryrate
from (
  select
    SALES_NBR,
    count(ITEMS) as Total,
    sum(case when FULFILLMENT = '1' then 1 else 0 end) as delivered
  from Invoice_table
  where STORE IN '0123'
    and SALE_DATE >='2020-02-01'
    and SALE_DATE <='2020-02-07'
  group by SALES_NBR
  ) qry;
</code>```

But I think this one, even being ugglier, could perform faster:

```<code>  select
    SALES_NBR,
    count(ITEMS) as Total,
    sum(case when FULFILLMENT = '1' then 1 else 0 end) as delivered,
    sum(case when FULFILLMENT = '1' then 1 else 0 end)/count(ITEMS) as Deliveryrate
  from Invoice_table
  where STORE IN '0123'
    and SALE_DATE >='2020-02-01'
    and SALE_DATE <='2020-02-07'
  group by SALES_NBR
</code>```

Body:
I have list of line items from invoices with a field that indicates if a line was delivered or picked up. I need to find a percentage of delivered items from the total number of lines.

SALES_NBR | Total | Deliveryrate

1 = Delivered 0 = picked up from FULFILLMENT.

SELECT SALES_NBR,
COUNT (ITEMS) as Total,
SUM (case when FULFILLMENT = '1' then 1 else 0 end) as delivered,
(SELECT delivered/total) as Deliveryrate
FROM Invoice_table
WHERE STORE IN '0123'
And SALE_DATE >='2020-02-01'
And SALE_DATE <='2020-02-07'
Group By SALES_NBR, Deliveryrate;

My query executes but never finishes for some reason. Is there any easier way to do this? Fulfillment field does not contain any NULL values.

Any help would be appreciated.

Body:
If you want to get a "nice" query, you can use subqueries like this:

select
  qry.*,
  qry.delivered/qry.total as Deliveryrate
from (
  select
    SALES_NBR,
    count(ITEMS) as Total,
    sum(case when FULFILLMENT = '1' then 1 else 0 end) as delivered
  from Invoice_table
  where STORE IN '0123'
    and SALE_DATE >='2020-02-01'
    and SALE_DATE <='2020-02-07'
  group by SALES_NBR
  ) qry;

But I think this one, even being ugglier, could perform faster:

  select
    SALES_NBR,
    count(ITEMS) as Total,
    sum(case when FULFILLMENT = '1' then 1 else 0 end) as delivered,
    sum(case when FULFILLMENT = '1' then 1 else 0 end)/count(ITEMS) as Deliveryrate
  from Invoice_table
  where STORE IN '0123'
    and SALE_DATE >='2020-02-01'
    and SALE_DATE <='2020-02-07'
  group by SALES_NBR


问:
Generate AlphaNumeric Sequence in Oracle PL/SQL
Hi guys I want to create a sequence for an unique primary key, it should starts in 0000 and increment 1 by 1, e.g 0001, 0002. When numeric chars finish at 9, next value should be 000A and next one 000B to 000Z, then next one should be 0010 (0011, 0012 and so on). I'm really new to oracle and I don't really understand how to do this, can anyone give me a light? thank you!</p>

答:
Got this:</p>

```<code>    CREATE OR REPLACE FUNCTION GENERA_ALFANUM (N INTEGER) RETURN VARCHAR2
     IS
      Q INTEGER;
      R VARCHAR2(4);
    BEGIN
      Q := N;
      WHILE Q >= 36 LOOP
         R := CHR(MOD(Q,36)+CASE WHEN MOD(Q,36) < 10 THEN 48 ELSE 55 END) || R;
         Q := FLOOR(Q/36);
      END LOOP;
      R := CHR(MOD(Q,36)+CASE WHEN MOD(Q,36) < 10 THEN 48 ELSE 55 END) || R;
      RETURN LPAD(R,4,'0');
    END;
</code>```

Body:
Got this:

    CREATE OR REPLACE FUNCTION GENERA_ALFANUM (N INTEGER) RETURN VARCHAR2
     IS
      Q INTEGER;
      R VARCHAR2(4);
    BEGIN
      Q := N;
      WHILE Q >= 36 LOOP
         R := CHR(MOD(Q,36)+CASE WHEN MOD(Q,36) < 10 THEN 48 ELSE 55 END) || R;
         Q := FLOOR(Q/36);
      END LOOP;
      R := CHR(MOD(Q,36)+CASE WHEN MOD(Q,36) < 10 THEN 48 ELSE 55 END) || R;
      RETURN LPAD(R,4,'0');
    END;


问:
argument expression's type is not compatible with formal parameter type，You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
I'm using below code to check for something, and I get two errors at ".map(f => f.getBlacklistedAccounts.contains(accountID))" line, have no idea what does that means, can anyone help me with that? Thanks.

The first one is

```<code>argument expression's type is not compatible with formal parameter type;
no type parameters for method map: (x$1: java.util.function.Function[_ >: my.util.BlacklistRule, _ <: U])java.util.Optional[U] exist so that it can be applied to arguments (java.util.function.Function[my.util.BlacklistRule,Boolean])
found   : java.util.function.Function[my.util.BlacklistRule,Boolean]
[scalac-2.12]  required: java.util.function.Function[_ >: my.util.BlacklistRule, _ <: ?U]
[scalac-2.12] Note: my.util.BlacklistRule <: Any, but Java-defined trait Function is invariant in type T.
[scalac-2.12] You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
[scalac-2.12]       .map(f => f.getBlacklistedAccounts.contains(accountID))
[scalac-2.12]        ^
</code>```

Second one

```<code> error: type mismatch;
[scalac-2.12]  found   : java.util.function.Function[my.util.BlacklistRule,Boolean]
[scalac-2.12]  required: java.util.function.Function[_ >: my.util.BlacklistRule, _ <: U]
[scalac-2.12]       .map(f => f.getBlacklistedAccounts.contains(accountID))
</code>```

my code

```<code>def isAccountBlacklistForAction(ruleBlacklist: RuleBlacklist, accountID: String, rule: String): Boolean ={
    ruleBlacklist.getRules
      .stream
      .filter(a => a.getRuleName.equals(rule))
      .findFirst()
      .map(f => f.getBlacklistedAccounts.contains(accountID))
      .orElse(true)
  }
</code>```

答:
It seems to have trouble inferring the type arg to map when the result is Boolean.

```<code>object Test extends App {
  val vs = java.util.List.of(1, 2, 3)

  println {
    vs.stream()
      .filter(_ > 2)
      .findFirst()
      //.map(i => i + 1)         // OK
      //.orElse(42)
      //.map(i => i > 0)         // OK scala 2.13
      .map[Boolean](i => i > 0)  // required for scala 2.12
      .orElse(true)
  }
}
</code>```

It was fixed in 2.13.1. The issue hints that the bug is hit if the A => B output is different type from input.

Body:
I'm using below code to check for something, and I get two errors at ".map(f => f.getBlacklistedAccounts.contains(accountID))" line, have no idea what does that means, can anyone help me with that? Thanks.

The first one is

argument expression's type is not compatible with formal parameter type;
no type parameters for method map: (x$1: java.util.function.Function[_ >: my.util.BlacklistRule, _ <: U])java.util.Optional[U] exist so that it can be applied to arguments (java.util.function.Function[my.util.BlacklistRule,Boolean])
found   : java.util.function.Function[my.util.BlacklistRule,Boolean]
[scalac-2.12]  required: java.util.function.Function[_ >: my.util.BlacklistRule, _ <: ?U]
[scalac-2.12] Note: my.util.BlacklistRule <: Any, but Java-defined trait Function is invariant in type T.
[scalac-2.12] You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
[scalac-2.12]       .map(f => f.getBlacklistedAccounts.contains(accountID))
[scalac-2.12]        ^

Second one

 error: type mismatch;
[scalac-2.12]  found   : java.util.function.Function[my.util.BlacklistRule,Boolean]
[scalac-2.12]  required: java.util.function.Function[_ >: my.util.BlacklistRule, _ <: U]
[scalac-2.12]       .map(f => f.getBlacklistedAccounts.contains(accountID))

my code

def isAccountBlacklistForAction(ruleBlacklist: RuleBlacklist, accountID: String, rule: String): Boolean ={
    ruleBlacklist.getRules
      .stream
      .filter(a => a.getRuleName.equals(rule))
      .findFirst()
      .map(f => f.getBlacklistedAccounts.contains(accountID))
      .orElse(true)
  }

Body:
It seems to have trouble inferring the type arg to map when the result is Boolean.

object Test extends App {
  val vs = java.util.List.of(1, 2, 3)

  println {
    vs.stream()
      .filter(_ > 2)
      .findFirst()
      //.map(i => i + 1)         // OK
      //.orElse(42)
      //.map(i => i > 0)         // OK scala 2.13
      .map[Boolean](i => i > 0)  // required for scala 2.12
      .orElse(true)
  }
}

It was fixed in 2.13.1. The issue hints that the bug is hit if the A => B output is different type from input.


问:
Convert one line json into multiple lines to write to a file (Ruby)
I've run into a situation where I'm retrieving a json string in ruby, but I'm attempting to write it to a file structured like your usual json file (for example:

```<code>{
    "top":{
        "mid1":"bot1",
        "mid2":"bot2"
    }
}
</code>```

However, the way the json string is structured is like so:

```<code>{"top":{"mid1":"bot1","mid2":"bot2"}}
</code>```

I've seen other posts mention doing JSON.parse in order to get what I want, however that just causes it to look like this:

```<code>{"top"=>{"mid1"=>"bot1", "mid2"=>"bot2"}}
</code>```

Is there a way that I can just convert the json string into what it looks like in the first code block above?

答:
The first representation is JSON. The decoded version is Ruby's internal representation. If you want to go back to JSON, JSON.dump(...) will reconvert it.

Keep in mind this is just presentation. The data is the same.

You may be interested in the pp method as that produces nice, structured debugging output.

Body:
I've run into a situation where I'm retrieving a json string in ruby, but I'm attempting to write it to a file structured like your usual json file (for example:

{
    "top":{
        "mid1":"bot1",
        "mid2":"bot2"
    }
}

However, the way the json string is structured is like so:

{"top":{"mid1":"bot1","mid2":"bot2"}}

I've seen other posts mention doing JSON.parse in order to get what I want, however that just causes it to look like this:

{"top"=>{"mid1"=>"bot1", "mid2"=>"bot2"}}

Is there a way that I can just convert the json string into what it looks like in the first code block above?


问:
Unable to dequeue single cell in collection view
I have come across a very disturbing issue in which I am not able to dequeue only a single cell in collectionView. When there are more than one item in collectionView, it works fine but soon as I have an array with a single item, it doesn't show any cell. I am not able to figure it out what’s wrong with my code.

```<code>extension collectionview: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! UICollectionViewCell
        return cell
    }
}
</code>```

答:
First:

the returned of numberOfItemsInSectionwill be array.count for Example

```<code>var array = [model]()
</code>```

Then in cellForItemAt you should configure your cell with data so
Add this block in your cell class

```<code>func configureCell(_ data: model) {
   // code for cell view
}

</code>```

Finally cellForItemAt will be

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! UICollectionViewCell
    cell.configureCell(array[indexPath.item])
    return cell
}

</code>```

I hope this be helpful for you.

Body:
I have come across a very disturbing issue in which I am not able to dequeue only a single cell in collectionView. When there are more than one item in collectionView, it works fine but soon as I have an array with a single item, it doesn't show any cell. I am not able to figure it out what’s wrong with my code.

extension collectionview: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! UICollectionViewCell
        return cell
    }
}

Body:
First:

the returned of numberOfItemsInSectionwill be array.count for Example

var array = [model]()

Then in cellForItemAt you should configure your cell with data so
Add this block in your cell class

func configureCell(_ data: model) {
   // code for cell view
}

Finally cellForItemAt will be

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! UICollectionViewCell
    cell.configureCell(array[indexPath.item])
    return cell
}

I hope this be helpful for you.


问:
Getters and setters in parent class
I have a quick question on best practice and if getters and setters are the best option in a specific case.  The case is when I have class 'A' instantiating classes 'B' and 'C'.  Class A contains public getters and setters for classes B and C to access so data is centralised.

Is this best practice or would it be best to pass the data to classes B and C through parameters?

Thanks

Chris

答:
Personally I would recommend structuring your application so that all the data required by classes B and C is passed through.  This will remove their dependency on Class A and thereby reduce coupling and complexity; for example:

```<code>public class A {
    private var b : B;

    public function A() {
        b = new B();
        b.someData = "some data that b requires";
    }
}
</code>```

You could then improve this further by removing the instantiation of Class B from Class A by a process referred to as Inversion of Control.  This way you make Class B a dependency of Class A.

```<code>public class A {
    private var b : B;

    public function A(b : B) {
        this.b = b;
    }
}
</code>```

This then allows an external Client to configure the B instance ahead of time making your project's structure more flexible to later changes:

```<code>public class Client {
    public function Client() {
        var b : B = new B();
        b.someData = "The Client is now Configuring B";

        var a : A = new A(b);
    }
}
</code>```

Title: Getters and setters in parent class

Body:
Personally I would recommend structuring your application so that all the data required by classes B and C is passed through.  This will remove their dependency on Class A and thereby reduce coupling and complexity; for example:

public class A {
    private var b : B;

    public function A() {
        b = new B();
        b.someData = "some data that b requires";
    }
}

You could then improve this further by removing the instantiation of Class B from Class A by a process referred to as Inversion of Control.  This way you make Class B a dependency of Class A.

public class A {
    private var b : B;

    public function A(b : B) {
        this.b = b;
    }
}

This then allows an external Client to configure the B instance ahead of time making your project's structure more flexible to later changes:

public class Client {
    public function Client() {
        var b : B = new B();
        b.someData = "The Client is now Configuring B";

        var a : A = new A(b);
    }
}


问:
Google Sheets Query for Maximum Date
I have a table which I would like to return in its entirety but filtered by column H with the maximum date as rows have duplicate account numbers with different dates.

https://docs.google.com/spreadsheets/d/1x3hYy1igiL3_lqhFE3IwrQNFbOjdpXRtHLAbOXB2BE4/edit?usp=sharing

I'm using this query right now, but clearly I'm overlooking something, can anyone help, please?

```<code>=QUERY(B3:I12, "Select *, Max(H) WHERE B is not null Group by C")
</code>```

答:
correct syntax would be:

```<code>=QUERY(B3:I12,
 "select B,C,D,E,F,G,H,I,max(H)
  where B is not null
  group by B,C,D,E,F,G,H,I")
</code>```

but you probably need this:

```<code>={B3:I3; SORTN(SORT(B4:I, 7, 0), 99^99, 2, 2, 1)}
</code>```

Title: Google Sheets Query for Maximum Date

Body:
I have a table which I would like to return in its entirety but filtered by column H with the maximum date as rows have duplicate account numbers with different dates.

https://docs.google.com/spreadsheets/d/1x3hYy1igiL3_lqhFE3IwrQNFbOjdpXRtHLAbOXB2BE4/edit?usp=sharing

I'm using this query right now, but clearly I'm overlooking something, can anyone help, please?

=QUERY(B3:I12, "Select *, Max(H) WHERE B is not null Group by C")

Body:
correct syntax would be:

=QUERY(B3:I12,
 "select B,C,D,E,F,G,H,I,max(H)
  where B is not null
  group by B,C,D,E,F,G,H,I")

but you probably need this:

={B3:I3; SORTN(SORT(B4:I, 7, 0), 99^99, 2, 2, 1)}


问:
Parsing a non-Unicode string with Flask-RESTful
I have a webhook developed with Flask-RESTful which gets several parameters with POST.
One of the parameters is a non-Unicode string, encoded in cp1251.

Can't find a way to correctly parse this argument using reqparse.

Here is the fragment of my code:

```<code>parser = reqparse.RequestParser()
parser.add_argument('text')
msg = parser.parse_args()
</code>```

Then, I write msg to a text file, and it looks like this:

```<code>{"text": "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd !\n\n\ufffd\ufffd\ufffd\ufffd\ufffd\n\n-- \n\ufffd \ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd."}
</code>```

As you can see, Flask somehow replaces all Cyrillic characters with \ufffd. At the same time, non-Cyrillic characters, like ! or \n are processed correctly.

Anything I can do to advise RequestParser with the string encoding?

Here is my code for writing the text to disk:

```<code> f = open('log_msg.txt', 'w+')
 f.write(json.dumps(msg))
 f.close()
</code>```

I tried f = open('log_msg.txt', 'w+', encoding='cp1251') with the same result.

Then, I tried

```<code> f = open('log_msg_ascii.txt', 'w+')
 f.write(ascii(json.dumps(msg)))
</code>```

Also, no difference.

So, I'm pretty sure it's RequestParser() tries to be too smart and can't understand the non-Unicode input.

Thanks!

答:
Okay, I finally found a workaround. Thanks to @lenz for helping me with this issue. It seems that reqparse wrongly assumes that every string parameter comes as UTF-8. So when it sees a non-Unicode input field (among other Unicode fields!), it tries to load it as Unicode and fails. As a result, all characters are U+FFFD (replacement character).

So, to access that non-Unicode field, I did the following trick.

First, I load raw data using get_data(), decode it using cp1251 and parse with a simple regexp.

```<code> raw_data = request.get_data()
 contents = raw_data.decode('windows-1251')
 match = re.search(r'(?P<delim>--\w+\r?\n)Content-Disposition: form-data; name=\"text\"\r?\n(.*?)(?P=delim)', contents, re.MULTILINE | re.DOTALL)
 text = match.group(2)
</code>```

Not the most beautiful solution, but it works.

Body:
I have a webhook developed with Flask-RESTful which gets several parameters with POST.
One of the parameters is a non-Unicode string, encoded in cp1251.

Can't find a way to correctly parse this argument using reqparse.

Here is the fragment of my code:

parser = reqparse.RequestParser()
parser.add_argument('text')
msg = parser.parse_args()

Then, I write msg to a text file, and it looks like this:

{"text": "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd !\n\n\ufffd\ufffd\ufffd\ufffd\ufffd\n\n-- \n\ufffd \ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd."}

As you can see, Flask somehow replaces all Cyrillic characters with \ufffd. At the same time, non-Cyrillic characters, like ! or \n are processed correctly.

Anything I can do to advise RequestParser with the string encoding?

Here is my code for writing the text to disk:

 f = open('log_msg.txt', 'w+')
 f.write(json.dumps(msg))
 f.close()

I tried f = open('log_msg.txt', 'w+', encoding='cp1251') with the same result.

Then, I tried

 f = open('log_msg_ascii.txt', 'w+')
 f.write(ascii(json.dumps(msg)))

Also, no difference.

So, I'm pretty sure it's RequestParser() tries to be too smart and can't understand the non-Unicode input.

Thanks!

Body:
Okay, I finally found a workaround. Thanks to @lenz for helping me with this issue. It seems that reqparse wrongly assumes that every string parameter comes as UTF-8. So when it sees a non-Unicode input field (among other Unicode fields!), it tries to load it as Unicode and fails. As a result, all characters are U+FFFD (replacement character).

So, to access that non-Unicode field, I did the following trick.

First, I load raw data using get_data(), decode it using cp1251 and parse with a simple regexp.

 raw_data = request.get_data()
 contents = raw_data.decode('windows-1251')
 match = re.search(r'(?P<delim>--\w+\r?\n)Content-Disposition: form-data; name=\"text\"\r?\n(.*?)(?P=delim)', contents, re.MULTILINE | re.DOTALL)
 text = match.group(2)

Not the most beautiful solution, but it works.


问:
Javascript: indexOf() & substr() not returning expected result on date string
In the image you will see the value being passed in and all the string functions I tried, but nothing seems to be working. I even tried putting it into a variable via new Date(d), but got "Invalid Date". I also tried using trim(). If I hard-coded a date string as the value for "d" then everything functioned as expected.
Can someone let me know what I am doing wrong?
Image: JS console.log of values

```<code>function convertDate2ISO(dateToConvert){
    var strDate = dateToConvert.trim();
    if (dateToConvert.indexOf("-") > 0) { strDate = dateToConvert.replace(/-/g, ' ');}

    if (dateToConvert.indexOf("/") > 0) {
        var substrValue = dateToConvert.substr(0,3);
        var indexOfValue = dateToConvert.indexOf('/');
        var toStringIndexOfValue = dateToConvert.toString().indexOf('/');
        var sliceValue = dateToConvert.slice(0,2);
        console.log("Incoming value (dateToConvert): " + dateToConvert + "\r\n" + "Using dateToConvert.substr(0,3): " +substrValue+ "\r\nUsing dateToConvert.indexOf('/'): " +indexOfValue+ "\r\nUsing dateToConvert.toString().indexOf('/'): " +toStringIndexOfValue+ "\r\nUsing dateToConvert.slice(0,2): " +sliceValue+ "\r\nUsing dateToConvert.length: " +dateToConvert.length );
        //was trying to use dateToConvert.indexOf('/') to test on, but result was unexpected
        //add 0 to begining if month is a singel digit
        strDate = "0" + strDate;
    }

    var myDate = new Date(strDate);
    myDate.toISOString(); //"2011-23-12T15:28:46.493Z
    return myDate
}
</code>```

The default for the incoming parameter is...

```<code>var myDateObj = new Date();
var strDTGReceived = myDateObj.toLocaleDateString();
</code>```

The call to the function is...

```<code>var dtISOReceivedDate = convertDate2ISO(strDTGReceived);
</code>```

Values I am getting are...

```<code>Incoming Parameter (dateToConvert): 2/18/2020
Using dateToConvert.substr(0,3): 2
dateToConvert.indexOf('/'): 3
Using dateToConvert.toString().indexOf('/'): 3
Using dateToConvert.slice(0,2): 2
Using dateToConvert.length: 14
</code>```

答:
You have an error on your function when you try to use and return the date variable when you defined it as myDate.

Changing that, your code should work as shown here:

function convertDate(d){
        var strDate = d;
        if (d.indexOf("-") > 0) {
          strDate = d.replace(/-/g, ' ');
        }

        if (d.indexOf("/") > 0) {
            var substrValue = d.substr(0,3);
            var indexOfValue = d.indexOf('/');
            var toStringIndexOfValue = d.toString().indexOf('/');
            var sliceValue = d.slice(0,2);
            console.log("Incoming value (d): " + d + "\r\n" + "Using d.substr(0,3): " +substrValue+ "\r\nUsing d.indexOf('/'): " +indexOfValue+ "\r\nUsing d.toString().indexOf('/'): " +toStringIndexOfValue+ "\r\nUsing d.slice(0,2): " +sliceValue );
            strDate = "0" + strDate;
        }

        var myDate = new Date(strDate);
        myDate.toISOString();
        return myDate
    }

 console.log('Result: ' +convertDate('2/18/2020'));```

Body:
In the image you will see the value being passed in and all the string functions I tried, but nothing seems to be working. I even tried putting it into a variable via new Date(d), but got "Invalid Date". I also tried using trim(). If I hard-coded a date string as the value for "d" then everything functioned as expected.
Can someone let me know what I am doing wrong?
Image: JS console.log of values

function convertDate2ISO(dateToConvert){
    var strDate = dateToConvert.trim();
    if (dateToConvert.indexOf("-") > 0) { strDate = dateToConvert.replace(/-/g, ' ');}

    if (dateToConvert.indexOf("/") > 0) {
        var substrValue = dateToConvert.substr(0,3);
        var indexOfValue = dateToConvert.indexOf('/');
        var toStringIndexOfValue = dateToConvert.toString().indexOf('/');
        var sliceValue = dateToConvert.slice(0,2);
        console.log("Incoming value (dateToConvert): " + dateToConvert + "\r\n" + "Using dateToConvert.substr(0,3): " +substrValue+ "\r\nUsing dateToConvert.indexOf('/'): " +indexOfValue+ "\r\nUsing dateToConvert.toString().indexOf('/'): " +toStringIndexOfValue+ "\r\nUsing dateToConvert.slice(0,2): " +sliceValue+ "\r\nUsing dateToConvert.length: " +dateToConvert.length );
        //was trying to use dateToConvert.indexOf('/') to test on, but result was unexpected
        //add 0 to begining if month is a singel digit
        strDate = "0" + strDate;
    }

    var myDate = new Date(strDate);
    myDate.toISOString(); //"2011-23-12T15:28:46.493Z
    return myDate
}

The default for the incoming parameter is...

var myDateObj = new Date();
var strDTGReceived = myDateObj.toLocaleDateString();

The call to the function is...

var dtISOReceivedDate = convertDate2ISO(strDTGReceived);

Values I am getting are...

Incoming Parameter (dateToConvert): 2/18/2020
Using dateToConvert.substr(0,3): 2
dateToConvert.indexOf('/'): 3
Using dateToConvert.toString().indexOf('/'): 3
Using dateToConvert.slice(0,2): 2
Using dateToConvert.length: 14


问:
Unable to connect to MongoDB Atlas from GKE pod
I have a pod running on Google Cloud Kubernetes and I have a MongoDB cluster running on Atlas.
The issue is quite simple:

If I allow IP from ANYWHERE on Atlas MongoDB, I can connect.
If I add the IP of the pod (so not from ANYWHERE anymore), it doesn't work.

I also tried locally and from a docker running locally as well, it works.

I got the IP (YY.YYY.YYY.YY) of my pod using:

```<code>MacBook-Pro-de-Emixam23:plop-service emixam23$ kubectl get services
NAME           TYPE           CLUSTER-IP    EXTERNAL-IP     PORT(S)                           AGE
polop-service  LoadBalancer   XX.XX.X.XXX   YY.YYY.YYY.YY   ZZZZZ:32633/TCP,ZZZZZ:32712/TCP   172m
kubernetes     ClusterIP      XX.X.X.X      <none>          443/TCP                           3h24m
</code>```

But by the behavior I get.. I feel like this EXTERNAL-IP isn't the IP from where my requests are sent from.

Can anyone explain to me what can be the issue?

答:
The IP exposed to Mongo Atlas should be Internet accessible IP (or called it, public IP).

Normally it should be the net gateway IPs (or proxy server's IPs, if you go with proxy).

One quick way to check the IP by running below command in pods

```<code>curl ifconfig.me
</code>```

If your pod doesn't support this command, you can kubectl exec -ti <pod_name> -- sh in it and install this command.

Remember: normally the IPs are not only one, there should be 3 or more public facing IPs via net gateway, you need find them all and add to Mongo Atlas whitelists

Body:
I have a pod running on Google Cloud Kubernetes and I have a MongoDB cluster running on Atlas.
The issue is quite simple:

If I allow IP from ANYWHERE on Atlas MongoDB, I can connect.
If I add the IP of the pod (so not from ANYWHERE anymore), it doesn't work.

I also tried locally and from a docker running locally as well, it works.

I got the IP (YY.YYY.YYY.YY) of my pod using:

MacBook-Pro-de-Emixam23:plop-service emixam23$ kubectl get services
NAME           TYPE           CLUSTER-IP    EXTERNAL-IP     PORT(S)                           AGE
polop-service  LoadBalancer   XX.XX.X.XXX   YY.YYY.YYY.YY   ZZZZZ:32633/TCP,ZZZZZ:32712/TCP   172m
kubernetes     ClusterIP      XX.X.X.X      <none>          443/TCP                           3h24m

But by the behavior I get.. I feel like this EXTERNAL-IP isn't the IP from where my requests are sent from.

Can anyone explain to me what can be the issue?

Body:
The IP exposed to Mongo Atlas should be Internet accessible IP (or called it, public IP).

Normally it should be the net gateway IPs (or proxy server's IPs, if you go with proxy).

One quick way to check the IP by running below command in pods

curl ifconfig.me

If your pod doesn't support this command, you can kubectl exec -ti <pod_name> -- sh in it and install this command.

Remember: normally the IPs are not only one, there should be 3 or more public facing IPs via net gateway, you need find them all and add to Mongo Atlas whitelists


问:
babel-plugin-macros - MacroError: The macro you imported from "undefined" is being executed
I got a Gatsby website project. Since Gatsby's default babel config contains babel-plugin-macros I don't need much to set it up.

E.g. I've installed preval.macro and it works fine.

Now I want to create my own macro to do some stuff. So I created a new NPM package containing only the package.json, index.js and macro.js. The macro by itself does nothing by now.

But if I install the package and try to use it, I get

MacroError: The macro you imported from "undefined" is being executed
  outside the context of compilation with babel-plugin-macros. This
  indicates that you don't have the babel plugin "babel-plugin-macros"
  configured correctly.

package.json

```<code>{
  "name": "my-package",
  "version": "0.0.21-alpha",
  "description": "my package description",
  "main": "dist/index.js",
  "scripts": {
    ...
  },
  "keywords": [],
  "author": "John Doe <john@doe.com>",
  "license": "ISC",
  "dependencies": {
    ...
  }
</code>```

}

index.js

```<code>import macro from "./macro";
export default macro;
</code>```

macro.js

```<code>import { createMacro } from "babel-plugin-macros";
export default createMacro(macro);
function macro({ references, babel, path }) {
    const { default: items = [] } = references;
    items.forEach((reference) => {
        if (!reference.parentPath.node.quasi) {
            return;
        }
    });
}
</code>```

Update

I would like to use the macro like this

```<code>import macro from "my-macro";

console.log(macro`something`)
</code>```

Update 2

I created codesandbox for a tiny gatsby starter project which shows the problem.

Codesandbox

答:
The problem is the import statement for the macro does not match the required convention for babel-plugin-macros to transform the code and call your custom macro.

You'll need to change the filename to end in .macro or import the macro file like: my/macro.

Learn more from the docs here: https://github.com/kentcdodds/babel-plugin-macros/blob/master/other/docs/author.md#filename

Good luck!

Body:
I got a Gatsby website project. Since Gatsby's default babel config contains babel-plugin-macros I don't need much to set it up.

E.g. I've installed preval.macro and it works fine.

Now I want to create my own macro to do some stuff. So I created a new NPM package containing only the package.json, index.js and macro.js. The macro by itself does nothing by now.

But if I install the package and try to use it, I get

MacroError: The macro you imported from "undefined" is being executed
  outside the context of compilation with babel-plugin-macros. This
  indicates that you don't have the babel plugin "babel-plugin-macros"
  configured correctly.

package.json

{
  "name": "my-package",
  "version": "0.0.21-alpha",
  "description": "my package description",
  "main": "dist/index.js",
  "scripts": {
    ...
  },
  "keywords": [],
  "author": "John Doe <john@doe.com>",
  "license": "ISC",
  "dependencies": {
    ...
  }

}

index.js

import macro from "./macro";
export default macro;

macro.js

import { createMacro } from "babel-plugin-macros";
export default createMacro(macro);
function macro({ references, babel, path }) {
    const { default: items = [] } = references;
    items.forEach((reference) => {
        if (!reference.parentPath.node.quasi) {
            return;
        }
    });
}

Update

I would like to use the macro like this

import macro from "my-macro";

console.log(macro`something`)

Update 2

I created codesandbox for a tiny gatsby starter project which shows the problem.

Codesandbox


问:
Login into facebook using oauth in python?
I got the following link for a app
https://www.facebook.com/dialog/oauth?client_id=SOME_NUMER_I_HAVE&redirect_uri=https://someSITE.com/fblogin&state=SOME_VALID_STATE
I want to send the name and password, and get the cookie.

Does anyone know what the request would look like?
(Or a library that takes care of this)

My setup, I'm trying to crawl a website, i need to login to this website to do so.

答:
a bit more info about your setup would be helpful.

If you are using Django I would recommend using django-allauth for social authentication.


问:
Is it possible to reuse a double quoted string with variables?
The application I'm writing generates some HTML server side though it could be applied to just any string.

```<code>$badges = [
    "<span class='badge badge--brand badge--inline'>$target</span>",
    "<span class='badge badge--dark badge--inline'>$target</span>",
    "<span class='badge badge--primary badge--inline'>$target</span>",
    "<span class='badge badge--success badge--inline'>$target</span>",
    "<span class='badge badge--info badge--inline'>$target</span>",
    "<span class='badge badge--warning badge--inline'>$target</span>",
    "<span class='badge badge--danger badge--inline'>$target</span>",
];

$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= $badges[$index % count($badges)];
}
echo $Badges;
</code>```

The desired output would be:

```<code><span class='badge badge--brand badge--inline'>one</span><span class='badge badge--dark badge--inline'>two</span><span class='badge badge--primary badge--inline'>three</span>
</code>```

I realize the $target variables are being evaluated inside the array, before it reaches the loop. With error reporting, this fails and without it, there is nothing in place of $target.

I can certainly just leverage str_replace and achieve desired results but this seemed like an interesting solution if I could get it to work.

Is it possible to achieve this? I haven't tried using eval and I would prefer not to as the $TargetStr is user supplied.

答:
I would prefer this:

```<code>$badges = [
    "<span class='badge badge--brand badge--inline'>{{target}}</span>",
    "<span class='badge badge--dark badge--inline'>{{target}}</span>",
    "<span class='badge badge--primary badge--inline'>{{target}}</span>",
    "<span class='badge badge--success badge--inline'>{{target}}</span>",
    "<span class='badge badge--info badge--inline'>{{target}}</span>",
    "<span class='badge badge--warning badge--inline'>{{target}}</span>",
    "<span class='badge badge--danger badge--inline'>{{target}}</span>",
];

$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= str_replace('{{target}}', $target, $badges[$index % count($badges)]);
}
echo $Badges;
</code>```

eval solution (tested / Working):

```<code><?php
        //Enter your code here, enjoy!
$badges = [
    '<span class="badge badge--brand badge--inline">$target</span>',
    '<span class="badge badge--dark badge--inline">$target</span>',
    '<span class="badge badge--primary badge--inline">$target</span>',
    '<span class="badge badge--success badge--inline">$target</span>',
    '<span class="badge badge--info badge--inline">$target</span>',
    '<span class="badge badge--warning badge--inline">$target</span>',
    '<span class="badge badge--danger badge--inline">$target</span>',
];

$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= eval(" ?>".preg_replace('/>([^<]+)</', '><?php echo $1; ?><', $badges[$index % count($badges)]). "<?php ");
}
echo $Badges;
</code>```

Body:
The application I'm writing generates some HTML server side though it could be applied to just any string.

$badges = [
    "$target",
    "$target",
    "$target",
    "$target",
    "$target",
    "$target",
    "$target",
];

$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= $badges[$index % count($badges)];
}
echo $Badges;

The desired output would be:

onetwothree

I realize the $target variables are being evaluated inside the array, before it reaches the loop. With error reporting, this fails and without it, there is nothing in place of $target.

I can certainly just leverage str_replace and achieve desired results but this seemed like an interesting solution if I could get it to work.

Is it possible to achieve this? I haven't tried using eval and I would prefer not to as the $TargetStr is user supplied.

Body:
I would prefer this:

$badges = [
    "<span class='badge badge--brand badge--inline'>{{target}}</span>",
    "<span class='badge badge--dark badge--inline'>{{target}}</span>",
    "<span class='badge badge--primary badge--inline'>{{target}}</span>",
    "<span class='badge badge--success badge--inline'>{{target}}</span>",
    "<span class='badge badge--info badge--inline'>{{target}}</span>",
    "<span class='badge badge--warning badge--inline'>{{target}}</span>",
    "<span class='badge badge--danger badge--inline'>{{target}}</span>",
];

$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= str_replace('{{target}}', $target, $badges[$index % count($badges)]);
}
echo $Badges;

eval solution (tested / Working):

<?php
        //Enter your code here, enjoy!
$badges = [
    '<span class="badge badge--brand badge--inline">$target</span>',
    '<span class="badge badge--dark badge--inline">$target</span>',
    '<span class="badge badge--primary badge--inline">$target</span>',
    '<span class="badge badge--success badge--inline">$target</span>',
    '<span class="badge badge--info badge--inline">$target</span>',
    '<span class="badge badge--warning badge--inline">$target</span>',
    '<span class="badge badge--danger badge--inline">$target</span>',
];

$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= eval(" ?>".preg_replace('/>([^<]+)</', '><?php echo $1; ?><', $badges[$index % count($badges)]). "<?php ");
}
echo $Badges;


问:
Thread-safe uniform random number generator
I have some parallel Fortran90 code in which each thread needs to generate the same sequence of random numbers.

I have a random number generator that seems to be thread-unsafe, since, for a given seed, I'm completely unable to repeat the same results each time I run the program.

I surfed unsuccessfully (almost) the entire web looking for some code of a thread-safe RNG. Could anyone provide me with (the link to) the code of one?

Thanks in advance!

答:
When you say "needs to generate the same sequence of random numbers" do you mean that

Each thread needs to generate a stream of numbers identical to the other thread? This implies choosing the seed before peeling off threads, then instantiating the a thread-local PRNG in each thread with the same seed.

or

You want to be able to repeat the same sequence of numbers between different runs of the programs, but each thread generates it's own independent sequence? In this case, you still can't share a single PRNG because the thread operation sequence is non-deterministic. So seed a single PRNG with a known seed before launching threads, and use it to generate the initial seeds for the threads. Then you instantiate thread-local generators in each thread...

In each of these cases you should note what Neil Butterworth say about the statistics: most of the usual guarantees that the PRNG  like to claim are not reliable when mix streams generated in this way.

In both cases you need a thread-local PRNG. I don't know what is available in f90...but you can also write you own (lookup Mersenne Twister, and write a routne that takes the saved state as a parameter...).

In fortran 77, this would look something like

```<code>      function PRNGthread (state)

      double state(statesize)

c stuff happens here which uses and manipulates the state vector...

      PRNGthread = result
      return
</code>```

and each of your threads should maintain a separate state vector, though all will use the same initial value.

OwnerDisplayName: Bellman

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eric P

Body:
When you say "needs to generate the same sequence of random numbers" do you mean that

Each thread needs to generate a stream of numbers identical to the other thread? This implies choosing the seed before peeling off threads, then instantiating the a thread-local PRNG in each thread with the same seed.

or

You want to be able to repeat the same sequence of numbers between different runs of the programs, but each thread generates it's own independent sequence? In this case, you still can't share a single PRNG because the thread operation sequence is non-deterministic. So seed a single PRNG with a known seed before launching threads, and use it to generate the initial seeds for the threads. Then you instantiate thread-local generators in each thread...

In each of these cases you should note what Neil Butterworth say about the statistics: most of the usual guarantees that the PRNG  like to claim are not reliable when mix streams generated in this way.

In both cases you need a thread-local PRNG. I don't know what is available in f90...but you can also write you own (lookup Mersenne Twister, and write a routne that takes the saved state as a parameter...).

In fortran 77, this would look something like

      function PRNGthread (state)

      double state(statesize)

c stuff happens here which uses and manipulates the state vector...

      PRNGthread = result
      return

and each of your threads should maintain a separate state vector, though all will use the same initial value.

OwnerDisplayName: dmckee

LastEditorDisplayName: dmckee


问:
VBA. Deleting multiple cells in a row if one cell is blank
I have multiple columns in an excel sheet...say A1:D10.
I want to find any blank cells in column C, delete that cell as well as the A,B, and D cells of that same row, then shift up.  But only in the range of A1:D10.  I have other information in this excel sheet outside this range that I want to perserve in its original position.  Therefore I can not use somthing like this:

```<code>.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
</code>```

Nor can I get something like the following to work, because it only shifts the single column up, not all four columns.

```<code>Set rng = Range("A1:D10").SpecialCells(xlCellTypeBlanks)
rng.Rows.Delete Shift:=xlShiftUp
</code>```

答:
The below will take care of your requirement by looking for an empty cell in column 3, and deleting the row and shifting up only in that row.</p>

```<code>Sub deleteEmptyRow()
Dim i As Integer

    For i = 1 To 10
        If Cells(i, 3) = "" Then
            Range(Cells(i, 1), Cells(i, 4)).delete Shift:=xlUp
        End If
    Next i

End Sub
</code>```

Body:
I have multiple columns in an excel sheet...say A1:D10.
I want to find any blank cells in column C, delete that cell as well as the A,B, and D cells of that same row, then shift up.  But only in the range of A1:D10.  I have other information in this excel sheet outside this range that I want to perserve in its original position.  Therefore I can not use somthing like this:

.SpecialCells(xlCellTypeBlanks).EntireRow.Delete

Nor can I get something like the following to work, because it only shifts the single column up, not all four columns.

Set rng = Range("A1:D10").SpecialCells(xlCellTypeBlanks)
rng.Rows.Delete Shift:=xlShiftUp

Body:
The below will take care of your requirement by looking for an empty cell in column 3, and deleting the row and shifting up only in that row.

Sub deleteEmptyRow()
Dim i As Integer

    For i = 1 To 10
        If Cells(i, 3) = "" Then
            Range(Cells(i, 1), Cells(i, 4)).delete Shift:=xlUp
        End If
    Next i

End Sub


问:
How can I use cypress to make a JSON call?
Day one with Cypress.

Trying to make a JSON call and examine result but all attempts giving me undefined.

```<code>describe('Test Number 000001 !!!', function() {
  it('starts off OK', function() {
    expect(true).to.equal(true)
  })
  it('can call the example api', function() {
    cy.request('https://jsonplaceholder.typicode.com/todos/1')
  })
  it('can call the example api and store the result', function() {
    result = cy.request('http://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json()) // I tried with and without then
    expect(result).to.equal(1) // will fail but once i get real response I will adjust
  })
})
</code>```

Update: the below passes... but doesn't actually check anything (any values used will pass)

```<code>    cy.request('http://jsonplaceholder.typicode.com/todos/1').
    then((response) => {
      response = JSON.stringify(response)
      var jsonData = JSON.parse(response)
      for (var i = 0; i < jsonData.length; i++) {
        expect(jsonData[i]['xuserId']).to.equal(1)
      }
    })
</code>```

答:
I have used the same test API earlier and have got the results like below; Please have a look. I have used response.body. to get json values

```<code>it('Sample Api testing', function () {
        cy.request({
            method: 'get',
            url: 'https://jsonplaceholder.typicode.com/todos/1',
            headers: {
                'accept': 'application/json'
            }
        }).then((response) => {
            expect(response.status).to.eq(200);
            expect(response.body.userId).to.eq(1);
            expect(response.body.id).to.eq(1);
            expect(response.body.title).to.eq('delectus aut autem');
        })
    })
</code>```

Body:
Day one with Cypress.

Trying to make a JSON call and examine result but all attempts giving me undefined.

describe('Test Number 000001 !!!', function() {
  it('starts off OK', function() {
    expect(true).to.equal(true)
  })
  it('can call the example api', function() {
    cy.request('https://jsonplaceholder.typicode.com/todos/1')
  })
  it('can call the example api and store the result', function() {
    result = cy.request('http://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json()) // I tried with and without then
    expect(result).to.equal(1) // will fail but once i get real response I will adjust
  })
})

Update: the below passes... but doesn't actually check anything (any values used will pass)

    cy.request('http://jsonplaceholder.typicode.com/todos/1').
    then((response) => {
      response = JSON.stringify(response)
      var jsonData = JSON.parse(response)
      for (var i = 0; i < jsonData.length; i++) {
        expect(jsonData[i]['xuserId']).to.equal(1)
      }
    })

Body:
I have used the same test API earlier and have got the results like below; Please have a look. I have used response.body. to get json values

it('Sample Api testing', function () {
        cy.request({
            method: 'get',
            url: 'https://jsonplaceholder.typicode.com/todos/1',
            headers: {
                'accept': 'application/json'
            }
        }).then((response) => {
            expect(response.status).to.eq(200);
            expect(response.body.userId).to.eq(1);
            expect(response.body.id).to.eq(1);
            expect(response.body.title).to.eq('delectus aut autem');
        })
    })


问:
How to return JSX from a method in React?
I'm pretty new to React, I'm trying to return a JSX from a method, code as follows:

import React, { useReducer } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';

const formatName = (user) => {
    return user.firstName + ' ' + user.lastName;
}

const getGreeting = (user) => {
    if (user) {
        return {greeting}
    }
    else {
        return {forbidden}
    }
}

const user = {
    firstName: 'John',
    lastName: 'Smith'
};

const greeting = (

Hello {formatName(user)}

);

const forbidden = (

Hello stranger!

);

const element = (

{getGreeting(user)}

);

ReactDOM.render(
    element, document.getElementById('root')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div></code>```

As you can see, element contains a div which I wish to render getGreeting, since user == true, it should return greeting, which calls the method formatName. However it returns an error:

```<code>Error: Objects are not valid as a React child (found: object with keys {greeting}). If you meant to render a collection of children, use an array instead.
</code>```

What am I doing wrong here?

答:
In JavaScript, when you write:

return {greeting}

...what you are saying is "return an object, with a property named 'greeting', which is set to value of the variable greeting"

The last part of that, where the value is set, is an ES6 shortcut, essentially replacing { "greeting": greeting } with {greeting} for brevity's sake.

In other words, you are currently returning an object with a single property, "greeting", which is basically what your error message says.
What you are returning is:

```<code>{
    "greeting": <h1>Hello ... </h1>
}
</code>```

What you want to return is:

```<code><h1>Hello ... </h1>
</code>```

Since your greeting const is valid JSX, you can just return it directly! i.e. return greeting;

Body:
I'm pretty new to React, I'm trying to return a JSX from a method, code as follows:

import React, { useReducer } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';

const formatName = (user) => {
    return user.firstName + ' ' + user.lastName;
}

const getGreeting = (user) => {
    if (user) {
        return {greeting}
    }
    else {
        return {forbidden}
    }
}

const user = {
    firstName: 'John',
    lastName: 'Smith'
};

const greeting = (

Hello {formatName(user)}

);

const forbidden = (

Hello stranger!

);

const element = (

{getGreeting(user)}

);

ReactDOM.render(
    element, document.getElementById('root')
);

As you can see, element contains a div which I wish to render getGreeting, since user == true, it should return greeting, which calls the method formatName. However it returns an error:

Error: Objects are not valid as a React child (found: object with keys {greeting}). If you meant to render a collection of children, use an array instead.

What am I doing wrong here?

Body:
In JavaScript, when you write:

return {greeting}

...what you are saying is "return an object, with a property named 'greeting', which is set to value of the variable greeting"

The last part of that, where the value is set, is an ES6 shortcut, essentially replacing { "greeting": greeting } with {greeting} for brevity's sake.

In other words, you are currently returning an object with a single property, "greeting", which is basically what your error message says.
What you are returning is:

{
    "greeting": <h1>Hello ... </h1>
}

What you want to return is:

<h1>Hello ... </h1>

Since your greeting const is valid JSX, you can just return it directly! i.e. return greeting;


问:
HTML5 Video Autoplay not working correctly
I'm using this code:

```<code><video width="440px" loop="true" autoplay="true" controls>
<source src="http://www.example.com/CorporateVideo.mp4" type="video/mp4" />
<source src="http://www.example.com/CorporateVideo.ogv" type="video/ogv" />
<source src="http://www.example.com/CorporateVideo.webm" type="video/webm" />
</video>
</code>```

I want the video to autoplay but when the page loads the video doesn't play. It looks like it's a buffering issue, as when I hover on the video (to show controls) the video is always 2 seconds in but then stops and doesn't continue.

Note: I just visited the site again and autoplay seemed to work, but when I try again the same issue is happening, is this a buffering issue? Anything I can do to stop this?

答:
html {
  padding: 20px 0;
  background-color: #efefef;
}

body {
  width: 400px;
  padding: 40px;
  margin: 0 auto;
  background: #fff;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.5);
}

video {
  width: 400px;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video onloadeddata="this.play();this.muted=false;" poster="https://durian.blender.org/wp-content/themes/durian/images/void.png" playsinline loop muted controls>
    <source src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4" />
    Your browser does not support the video tag or the file format of this video.
</video></code>```

Body:
I'm using this code:

<video width="440px" loop="true" autoplay="true" controls>
<source src="http://www.example.com/CorporateVideo.mp4" type="video/mp4" />
<source src="http://www.example.com/CorporateVideo.ogv" type="video/ogv" />
<source src="http://www.example.com/CorporateVideo.webm" type="video/webm" />
</video>

I want the video to autoplay but when the page loads the video doesn't play. It looks like it's a buffering issue, as when I hover on the video (to show controls) the video is always 2 seconds in but then stops and doesn't continue.

Note: I just visited the site again and autoplay seemed to work, but when I try again the same issue is happening, is this a buffering issue? Anything I can do to stop this?

Body:
html {
  padding: 20px 0;
  background-color: #efefef;
}

body {
  width: 400px;
  padding: 40px;
  margin: 0 auto;
  background: #fff;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.5);
}

video {
  width: 400px;
  display: block;
}

<video onloadeddata="this.play();this.muted=false;" poster="https://durian.blender.org/wp-content/themes/durian/images/void.png" playsinline loop muted controls>
    <source src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4" />
    Your browser does not support the video tag or the file format of this video.
</video>


问:
How do you map routes according to the following schema?
How do you map this url

/Topic/topicName/action?topicId=someInt

Where Topic is the controller name (this is const - it always reads "Topic"),

topicName is being ignored

action is action name,

and someInt is the topicId argument for "action".

Here are couple of examples:

/Topic/c-sharp/AddQuestion?topicId=1

To invoke:

Controller: Topic

Action: AddQuestion

topicId =1

Where this is the action's singnature in TopicConroller

```<code>public ActionResult AddQuestion(int topicId)
</code>```

Another example:

/Topic/MySql-queries/AddSubTopic?topicId=1

To invoke:

Controller: Topic

Action: AddSubTopic

topicId =1

Where this is the action's singnature in TopicConroller

```<code>public ActionResult AddSubTopic(int topicId)
</code>```

etc. (all actions in Topic controller receive only one argument - that is the topic's id).

答:
```<code>routes.MapRoute(
    "Topics",
    "Topic/{topicName}/{action}",
    new { controller = "Topic", action = "Index" }
);
</code>```

where you would have:

```<code>public class TopicController: Controller
{
    public ActionResult AddQuestion(int topicId)
    {
        ...
    }
}
</code>```

and if you cared about the topic name you could have your controller action take it as action parameter:

```<code>public ActionResult AddQuestion(int topicId, string topicName)
{
    ...
}
</code>```

Body:
How do you map this url

/Topic/topicName/action?topicId=someInt

Where Topic is the controller name (this is const - it always reads "Topic"),

topicName is being ignored

action is action name,

and someInt is the topicId argument for "action".

Here are couple of examples:

/Topic/c-sharp/AddQuestion?topicId=1

To invoke:

Controller: Topic

Action: AddQuestion

topicId =1

Where this is the action's singnature in TopicConroller

public ActionResult AddQuestion(int topicId)

Another example:

/Topic/MySql-queries/AddSubTopic?topicId=1

To invoke:

Controller: Topic

Action: AddSubTopic

topicId =1

Where this is the action's singnature in TopicConroller

public ActionResult AddSubTopic(int topicId)

etc. (all actions in Topic controller receive only one argument - that is the topic's id).

Body:
routes.MapRoute(
    "Topics",
    "Topic/{topicName}/{action}",
    new { controller = "Topic", action = "Index" }
);

where you would have:

public class TopicController: Controller
{
    public ActionResult AddQuestion(int topicId)
    {
        ...
    }
}

and if you cared about the topic name you could have your controller action take it as action parameter:

public ActionResult AddQuestion(int topicId, string topicName)
{
    ...
}