问:
The input to a flatten layer must be a tensor
I had the following keras model, which was running ok:

```<code>model = Sequential()
model.add(Flatten(input_shape=(1,1,68)))
model.add(Dense(35,activation='linear'))
model.add(LeakyReLU(alpha=.001))
model.add(Dense(nb_actions))
model.add(Activation('linear'))
</code>```

Then, I tried to make something more elaborated, as below:

```<code>model = Sequential()
input1 = keras.layers.Flatten(input_shape=(1,1,68))
x1 = keras.layers.Dense(68, activation='linear')(input1)
x2 = keras.layers.Dense(68, activation='relu')(input1)
x3 = keras.layers.Dense(68, activation='sigmoid')(input1)
add1 = keras.layers.Add()([x1, x2, x3])
activ1 = keras.layers.advanced_activations.LeakyReLU(add1)

x4 = keras.layers.Dense(34, activation='linear')(activ1)
x5 = keras.layers.Dense(34, activation='relu')(activ1)
x6 = keras.layers.Dense(34, activation='sigmoid')(activ1)
add2 = keras.layers.Add()([x4, x5, x6])
activ2 = keras.layers.advanced_activations.LeakyReLU(add2)

x7 = keras.layers.Dense(17, activation='linear')(activ2)
x8 = keras.layers.Dense(17, activation='relu')(activ2)
x9 = keras.layers.Dense(17, activation='sigmoid')(activ2)
add2 = keras.layers.Add()([x4, x5, x6])
activ3 = keras.layers.advanced_activations.LeakyReLU(add3)

final_layer=keras.layers.Dense(nb_actions, activation='linear')(activ3)
model = keras.models.Model(inputs=input1, outputs=final_layer)
</code>```

As you can see in the above code, I am keeping the same input from a Flatten layer and just summing up layers with the same number of neurons, but activated differently. My problem is when I try to run this code. I am getting always the following error:

```<code>Using TensorFlow backend. Traceback (most recent call last):   File "/home/anselmo/virtualenvironment/virtualenvironment_anselmo2/lib/python3.5/site-packages/keras/engine/base_layer.py", line 279, in assert_input_compatibility
    K.is_keras_tensor(x)   File "/home/anselmo/virtualenvironment/virtualenvironment_anselmo2/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py", line 474, in is_keras_tensor
    str(type(x)) + '`. ' ValueError: Unexpectedly found an instance of type class keras.layers.core.Flatten. Expected a symbolic tensor instance.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "main.py", line 64, in <module>
    x1 = keras.layers.Dense(68, activation='linear')(input1)   File "/home/anselmo/virtualenvironment/virtualenvironment_anselmo2/lib/python3.5/site-packages/keras/engine/base_layer.py", line 414, in __call__
    self.assert_input_compatibility(inputs)   File "/home/anselmo/virtualenvironment/virtualenvironment_anselmo2/lib/python3.5/site-packages/keras/engine/base_layer.py", line 285, in assert_input_compatibility
    str(inputs) + '. All inputs to the layer ' ValueError: Layer dense_1 was called with an input that isn't a symbolic tensor. Received type: class keras.layers.core.Flatten. Full input: [keras.layers.core.Flatten object at 0x7f0a145d6438]. All inputs to the layer should be tensors.
</code>```

When I ran the previous code, the error did not happen. So why changing the network design there is this error? how can I solve it? where is my mistake here?

答:
What you are trying in the 2nd code is a Keras Functional model, and not a Sequential one. You should change the first line from model = Sequential() to input1 = Input(shape=(1, 1, 68)).

More details at the official documentation.

Body:
I had the following keras model, which was running ok:

model = Sequential()
model.add(Flatten(input_shape=(1,1,68)))
model.add(Dense(35,activation='linear'))
model.add(LeakyReLU(alpha=.001))
model.add(Dense(nb_actions))
model.add(Activation('linear'))

Then, I tried to make something more elaborated, as below:

model = Sequential()
input1 = keras.layers.Flatten(input_shape=(1,1,68))
x1 = keras.layers.Dense(68, activation='linear')(input1)
x2 = keras.layers.Dense(68, activation='relu')(input1)
x3 = keras.layers.Dense(68, activation='sigmoid')(input1)
add1 = keras.layers.Add()([x1, x2, x3])
activ1 = keras.layers.advanced_activations.LeakyReLU(add1)

x4 = keras.layers.Dense(34, activation='linear')(activ1)
x5 = keras.layers.Dense(34, activation='relu')(activ1)
x6 = keras.layers.Dense(34, activation='sigmoid')(activ1)
add2 = keras.layers.Add()([x4, x5, x6])
activ2 = keras.layers.advanced_activations.LeakyReLU(add2)

x7 = keras.layers.Dense(17, activation='linear')(activ2)
x8 = keras.layers.Dense(17, activation='relu')(activ2)
x9 = keras.layers.Dense(17, activation='sigmoid')(activ2)
add2 = keras.layers.Add()([x4, x5, x6])
activ3 = keras.layers.advanced_activations.LeakyReLU(add3)

final_layer=keras.layers.Dense(nb_actions, activation='linear')(activ3)
model = keras.models.Model(inputs=input1, outputs=final_layer)

As you can see in the above code, I am keeping the same input from a Flatten layer and just summing up layers with the same number of neurons, but activated differently. My problem is when I try to run this code. I am getting always the following error:

Using TensorFlow backend. Traceback (most recent call last):   File "/home/anselmo/virtualenvironment/virtualenvironment_anselmo2/lib/python3.5/site-packages/keras/engine/base_layer.py", line 279, in assert_input_compatibility
    K.is_keras_tensor(x)   File "/home/anselmo/virtualenvironment/virtualenvironment_anselmo2/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py", line 474, in is_keras_tensor
    str(type(x)) + '`. ' ValueError: Unexpectedly found an instance of type class keras.layers.core.Flatten. Expected a symbolic tensor instance.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "main.py", line 64, in <module>
    x1 = keras.layers.Dense(68, activation='linear')(input1)   File "/home/anselmo/virtualenvironment/virtualenvironment_anselmo2/lib/python3.5/site-packages/keras/engine/base_layer.py", line 414, in __call__
    self.assert_input_compatibility(inputs)   File "/home/anselmo/virtualenvironment/virtualenvironment_anselmo2/lib/python3.5/site-packages/keras/engine/base_layer.py", line 285, in assert_input_compatibility
    str(inputs) + '. All inputs to the layer ' ValueError: Layer dense_1 was called with an input that isn't a symbolic tensor. Received type: class keras.layers.core.Flatten. Full input: [keras.layers.core.Flatten object at 0x7f0a145d6438]. All inputs to the layer should be tensors.

When I ran the previous code, the error did not happen. So why changing the network design there is this error? how can I solve it? where is my mistake here?


来源: stackexchange

问:
Creating a list from an excel file that's a slice of a column. How can I print it without a 'text:' prefix in any value?
Trying to fetch a list of values from an excel file consisting of a column but has to end at a certain row. Can fetch it using a slice of the col and rows, however a prefix of 'text:' appears. This makes the list incompatible for what I need to use it for.

```<code>import xlrd
import csv

loc = ("/Users/uni/Desktop/TESTEXCEL.xls")

wb =xlrd.open_workbook(loc)

sheet = wb.sheet_by_index(0)

sheet.cell_value(0,0)

CANDIDATE = sheet.col_slice(colx=5,
                            start_rowx=1,
                            end_rowx=29)

print (CANDIDATE)
</code>```

RESULT:

```<code>[text:u'lt102', text:u'lt103', text:u'lt104', text:u'lt105', text:u'lt108', text:u'lt124', text:u'lt149', text:u'lt151', text:u'lt152', text:u'lt153', text:u'lt195', text:u'lt223', text:u'lt229', text:u'lt254', text:u'lt255', text:u'lt268', text:u'lt269', text:u'lt270', text:u'lt277', text:u'lt278', text:u'lt280', text:u'lt284', text:u'lt285', text:u'lt287', text:u'lt299', text:u'lt95', text:u'lt96', text:u'lt97']
</code>```

答:
You can use pandas library, it has convenient read_excel method. Here is example:

```<code>import pandas as pd

column_number = 5
df = pd.read_excel('/Users/uni/Desktop/TESTEXCEL.xls', usecols=[column_number], nrows=29, header=None)
values = df[column_number].to_list()  # a list of values in your 5th column
</code>```

You can read more about read_excel here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html

ContentLicense: CC BY-SA 4.0

Body:
Trying to fetch a list of values from an excel file consisting of a column but has to end at a certain row. Can fetch it using a slice of the col and rows, however a prefix of 'text:' appears. This makes the list incompatible for what I need to use it for.

import xlrd
import csv

loc = ("/Users/uni/Desktop/TESTEXCEL.xls")

wb =xlrd.open_workbook(loc)

sheet = wb.sheet_by_index(0)

sheet.cell_value(0,0)

CANDIDATE = sheet.col_slice(colx=5,
                            start_rowx=1,
                            end_rowx=29)

print (CANDIDATE)

RESULT:

[text:u'lt102', text:u'lt103', text:u'lt104', text:u'lt105', text:u'lt108', text:u'lt124', text:u'lt149', text:u'lt151', text:u'lt152', text:u'lt153', text:u'lt195', text:u'lt223', text:u'lt229', text:u'lt254', text:u'lt255', text:u'lt268', text:u'lt269', text:u'lt270', text:u'lt277', text:u'lt278', text:u'lt280', text:u'lt284', text:u'lt285', text:u'lt287', text:u'lt299', text:u'lt95', text:u'lt96', text:u'lt97']

Body:
You can use pandas library, it has convenient read_excel method. Here is example:

import pandas as pd

column_number = 5
df = pd.read_excel('/Users/uni/Desktop/TESTEXCEL.xls', usecols=[column_number], nrows=29, header=None)
values = df[column_number].to_list()  # a list of values in your 5th column

You can read more about read_excel here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html


问:
Search element in array based on another array and change property
I have two array of objects like this:

```<code>const officers: any[] = [
  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'Admiral Ozzel' },
  { id: 88, name: 'Commander Jerjerrod' }
];

const searchAndChangeFor: any[] = [
  { id: 56, name: 'New Name', additionalData: 1 },
];
</code>```

I want to find elements from searchAndChangeFor in officers and modify content. Usually If I have one element I do this:

```<code>officers.map((item) => {
    // I want to modify id: 56 and update officers here.
    item.id === 56 ? { ...item, name: 'Change name for 56' } : item
});
</code>```

But I need to search by array not single element so I've tried this but not succeeded:

```<code>officers.map((item) => {
   searchAndChangeFor.find((item2) => {
       item.id === item2.id? { ...item, name: 'Change name for 56' } : item
   });
});
</code>```

Expected Output:

```<code>  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'New Name', additionalData: 1 },
  { id: 88, name: 'Commander Jerjerrod' }
</code>```

It goes crazy with array. How can I find elements in officers based on searchAndChangeFor and change its name? I also want to keep all other existing items in officers.

答:
Assuming you want to preserve all properties of the objects of officers and searchAndChangeFor:

const officers = [
    { id: 20, name: 'Captain Piett' },
    { id: 24, name: 'General Veers' },
    { id: 56, name: 'Admiral Ozzel', admiralSince: 2008 },
    { id: 88, name: 'Commander Jerjerrod' }
];

const searchAndChangeFor = [
    { id: 56, name: 'New Name', additionalData: 1 },
];

const newOfficers = officers.map(officer => {
    const changedOfficer = searchAndChangeFor.find(changedOfficer => changedOfficer.id === officer.id)
    return changedOfficer ? { ...officer, ...changedOfficer } : officer;
});

console.log(newOfficers);```

Body:
I have two array of objects like this:

const officers: any[] = [
  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'Admiral Ozzel' },
  { id: 88, name: 'Commander Jerjerrod' }
];

const searchAndChangeFor: any[] = [
  { id: 56, name: 'New Name', additionalData: 1 },
];

I want to find elements from searchAndChangeFor in officers and modify content. Usually If I have one element I do this:

officers.map((item) => {
    // I want to modify id: 56 and update officers here.
    item.id === 56 ? { ...item, name: 'Change name for 56' } : item
});

But I need to search by array not single element so I've tried this but not succeeded:

officers.map((item) => {
   searchAndChangeFor.find((item2) => {
       item.id === item2.id? { ...item, name: 'Change name for 56' } : item
   });
});

Expected Output:

  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'New Name', additionalData: 1 },
  { id: 88, name: 'Commander Jerjerrod' }

It goes crazy with array. How can I find elements in officers based on searchAndChangeFor and change its name? I also want to keep all other existing items in officers.


问:
How to remove cache in WKWebView?
Any one worked with WKWebView and tried to clear cache? If yes, how to do it? Any example?

P.S. : Normal NSURLCache is not working.

答:
Remove Cache and Cookies

```<code># WKWebView+Clean.swift

import WebKit

extension WKWebView {
    class func clean() {
        guard #available(iOS 9.0, *) else {return}

        HTTPCookieStorage.shared.removeCookies(since: Date.distantPast)

        WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
            records.forEach { record in
                WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: {})
                #if DEBUG
                    print("WKWebsiteDataStore record deleted:", record)
                #endif
            }
        }
    }
}
</code>```

Example:

```<code>import WebKit
...
WKWebview.clean()
</code>```

Title: How to remove cache in WKWebView?

Body:
Remove Cache and Cookies

# WKWebView+Clean.swift

import WebKit

extension WKWebView {
    class func clean() {
        guard #available(iOS 9.0, *) else {return}

        HTTPCookieStorage.shared.removeCookies(since: Date.distantPast)

        WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
            records.forEach { record in
                WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: {})
                #if DEBUG
                    print("WKWebsiteDataStore record deleted:", record)
                #endif
            }
        }
    }
}

Example:

import WebKit
...
WKWebview.clean()


问:
An interpolation string $ is considered as an invalid character and returns an error BC30037 (vb.net)
I'm setting up a Redis cache server in vb.net, so I started implementing the Redis class in my source code so I could use the class methods later.

I currently have this error: "BC30037: invalid caracter" and I can't resolve it. The error comes from the character "$" in front of my string allowing to normally make string interpolation. Here it doesn't work and on the contrary, this character is considered to be invalid (the compilator doesn't understand that it's an interpolation string and therefore returns an error because).

I found someone who solved the same problem in another topic but he used Team Foundation Server and was working on a Visual Studio project : tfs build server - string interpolation $ Character is not valid

I'm working with Visual Studio 2019 and ASP.NET 4.7.2 but I have no project (my code is as it is in visual studio but it's not in a project).

I would like to know how to solve this problem with my current configuration?

Public Function GetCommand() As String Implements IRedisCommand.GetCommand
    Return $"APPEND {Key} {Value}" //$ is the problem here
End Function
```

答:
I finally found an alternative to the problem: I used the String.Format () method to convert the value of objects into strings according to the specified formats and insert them into another string.

It looks like this now :

```<code>Public Function GetCommand() As String Implements IRedisCommand.GetCommand
    Return String.Format("APPEND {0} {1}", Key, Value)
End Function
</code>```

By the way, thank you for your clarifications concerning the vb comments.

Have a good day !!

Body:
I finally found an alternative to the problem: I used the String.Format () method to convert the value of objects into strings according to the specified formats and insert them into another string.

It looks like this now :

Public Function GetCommand() As String Implements IRedisCommand.GetCommand
    Return String.Format("APPEND {0} {1}", Key, Value)
End Function

By the way, thank you for your clarifications concerning the vb comments.

Have a good day !!


问:
Change font and font size during creating userform programatically
I am going to create a userform programmatically, I am able to create other controls like commandbuttons, textboxes, optionbuttons...etc., as my wish.

But I can not figure out the way to set the font and font size at the beginning of creating the userform programmatically.

As there are near hundred controls, it would be better for me to set the font at the beginning, otherwise, I may set the font manually afterwards.

I tried the following for setting:

```<code>    Dim NewForm As Object

    Application.VBE.MainWindow.Visible = True

    Set NewForm = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_MSForm)
    With NewForm
        .Properties("Caption") = ""
        .Properties("Width") = 400
        .Properties("Height") = 400
------> 'Properties("Font.Name") = "Arial"
        'Properties("Font.size") = 9
               'Or
------> '.Font = "Arial"
        '.font.size = 9
        .Name = "frmWebScraping"
    End With

    'code for creating other controls with no problem is neglected

End Sub
</code>```

答:
The correct properties are:

```<code>.Properties("Font").Value.Item("Name") = "Arial"
.Properties("Font").Value.Item("Size") = 9
</code>```

Body:
I am going to create a userform programmatically, I am able to create other controls like commandbuttons, textboxes, optionbuttons...etc., as my wish.

But I can not figure out the way to set the font and font size at the beginning of creating the userform programmatically.

As there are near hundred controls, it would be better for me to set the font at the beginning, otherwise, I may set the font manually afterwards.

I tried the following for setting:

    Dim NewForm As Object

    Application.VBE.MainWindow.Visible = True

    Set NewForm = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_MSForm)
    With NewForm
        .Properties("Caption") = ""
        .Properties("Width") = 400
        .Properties("Height") = 400
------> 'Properties("Font.Name") = "Arial"
        'Properties("Font.size") = 9
               'Or
------> '.Font = "Arial"
        '.font.size = 9
        .Name = "frmWebScraping"
    End With

    'code for creating other controls with no problem is neglected

End Sub

Body:
The correct properties are:

.Properties("Font").Value.Item("Name") = "Arial"
.Properties("Font").Value.Item("Size") = 9


问:
How to create and push multiple files to git repository using node js code
I have a code where I am downloading lot of files from S3/Azure. I want to push them to new repository in github using NodeJS code. Tried simpleGit module but it didnt workout. Here is the thing which I want to do
- Create a new repository in github if not exists already
- create files on fly with data I have and add them git repository.
- commit those changes
- push them to remote

Tried SimpleGit, NodeGit...but none of them have proper examples to do this task.

答:
From what you are saying, you are trying to create a new repo on github before pushing to it.
I think your issue is that you can't use git to create a github repo directly. They are two different things. For creating a new github repo you should use the github API
https://developer.github.com/v3/repos/#create

When your repository is done, you should then be able to push to it with git and the libs you mentionned should do the trick.

When the repository is created follow the step here but with the equivalent commands from simpleGit (or any other lib, but this is the first you cited)

https://help.github.com/en/articles/adding-an-existing-project-to-github-using-the-command-line

Step 4 to the end (but don't do it directly, that's just to show what is needed to do)

And from simpleGit documentation

https://www.npmjs.com/package/simple-git#starting-a-new-repo

This example should do exactly what you need. You can try to find which command correspond to which of the step describe in the github doc.


问:
Imageview won't show image with piccsso if the image is in HTTP format
I am using Picasso to inflate image from URL to Imageview:

```<code>
@Override
    public void onBindViewHolder(@NonNull HeroesViewHolder holder, int position) {

        Hero currentHero = heroList.get(position);
        String str = String.join(",", currentHero.abilities);

        holder.heroTitle.setText(currentHero.title);
        holder.heroAbilities.setText(str);
        Picasso.get().load(currentHero.image).resize(500, 500).into(holder.heroesImage);

    }

</code>```

The thing is that everything that is HTTP protocol won't show up at emulator & physical device, only the ones that are HTTPS. Instead of showing it, it just leaves a black space.

The images that are HTTP protocol are also .png extension, if that has anything to do with that.

how can I workaround this issue?

答:
Please try below code :</p>

```<code>Picasso.with(this)  // Activity context
       .load(currentHero.image) // Set URL
       .resize(100,100) // Resize the image
       .placeholder(getResources().getDrawable(R.drawable.ic_defuser)) // Default Image
       .error(getResources().getDrawable(R.drawable.ic_defuser))
       .into(holder.heroesImage); // Imageview
</code>```

Body:
I am using Picasso to inflate image from URL to Imageview:

@Override
    public void onBindViewHolder(@NonNull HeroesViewHolder holder, int position) {

        Hero currentHero = heroList.get(position);
        String str = String.join(",", currentHero.abilities);

        holder.heroTitle.setText(currentHero.title);
        holder.heroAbilities.setText(str);
        Picasso.get().load(currentHero.image).resize(500, 500).into(holder.heroesImage);

    }

The thing is that everything that is HTTP protocol won't show up at emulator & physical device, only the ones that are HTTPS. Instead of showing it, it just leaves a black space.

The images that are HTTP protocol are also .png extension, if that has anything to do with that.

how can I workaround this issue?

Body:
Please try below code :

Picasso.with(this)  // Activity context
       .load(currentHero.image) // Set URL
       .resize(100,100) // Resize the image
       .placeholder(getResources().getDrawable(R.drawable.ic_defuser)) // Default Image
       .error(getResources().getDrawable(R.drawable.ic_defuser))
       .into(holder.heroesImage); // Imageview


问:
Training a model to tell if it's an actual credit card/ driver's license vs image on a screen/ photocopy, etc
I'm looking for any advice on how I might train a model to tell the difference between a photo of the actual object vs a photo of an image of an object. Specifically when it comes to credit cards and drivers license.

For instance, on Google pay, and similar pay apps you can add a credit card by the camera. But it turns out it can't tell if I'm taking a photo of my actual card or a photo of an image of my card on the screen. For my app, I need to do something similar but be able to tell if it's real or not.

The reason is that users sometimes try to pass off someone else's identity as their own (i.e they have a photo of someone's card) and using the app takes a photo of that photo (you can't upload a photo on the app, only take a live photo).

I'm also looking for successful implementations that already exist to study them. I couldn't really find anything, possibly because most of it is proprietary and isn't an advertised feature.

The first step I plan to take is, of course, generating the dataset, which is pretty labor intensive. This means printing out fake cards on to plastic, then taking a photo of them. The model I'm aiming for should be able to classify (1) Actual card (2) Image of the card on the screen (3) Image of the card on paper (printed/photocopy). It seems possible because most humans can tell the difference (from the glare on the screen, the texture of paper, etc). Note, the card is issued from the same entity (same logo, color, etc), so a lot of things should be constant.

Any other non-ML suggestions are welcome.

Ceci n'est pas une pipe

答:
It all comes down to the training of your algorithm and to additional security layers. Solutions I saw and have in mind:

Have two layers of algorithms: First classifies if it is a photo or a photo of a photo, second which recognizes what is on the picture. In this case you need a large set of training sample with two classification in order to get the results.

Have an additional layer of security: This could also be tricked, but at least you will know who cheated. The DriveNow app requires one to upload a selfie holding the actual card next to your head.

Anyway, there are no bulletproof way to process these images, if someone really wants they could trick these security gates. I think what is also really important is to monitor the transactions, actions made by the users to catch any unusual movements.


问:
How to execute a function in child component when (change) on a select in the parent component happens
I have child component with a function that I want to call once the (change) event gets triggered on a select in the parent component. Is this possible?</p>

答:
I wouldn't advise the @AdritaSharma solution since it's not reusable. It requires some boilerplate for every implementation.

I use to adopt this solution:

In parent component:

```<code>// HTML:
<select (change)="onChange($event.target.value)">
  <option>...</option>
</select>
<child-component [value]="value"></child-component>

// TS:
value: string;

onChange(value: string) {
  this.value = value;
}
</code>```

In child component:

```<code>_value: string;
@Input()
set value(v) {
  this._value = v;
  // execute your update code
}
get value() {
  return this._value;
}
</code>```

Body:
I wouldn't advise the @AdritaSharma solution since it's not reusable. It requires some boilerplate for every implementation.

I use to adopt this solution:

In parent component:

// HTML:
<select (change)="onChange($event.target.value)">
  <option>...</option>
</select>
<child-component [value]="value"></child-component>

// TS:
value: string;

onChange(value: string) {
  this.value = value;
}

In child component:

_value: string;
@Input()
set value(v) {
  this._value = v;
  // execute your update code
}
get value() {
  return this._value;
}


问:
Making cells bold in a table using python-docx
The code snippet below basically creates a table with the required number of rows and columns in a new word document i.e 2 columns and 14 rows. It then adds the content to the rows and columns accordingly.

```<code>from docx import Document
newDoc=Document()
newDoc.add_heading ('GIS Request Form')
newDoc.add_paragraph()

#inserting a table and the header and value objects to the table
 table=newDoc.add_table(rows=14,cols=2)
 table.style='Table Grid'
 table.autofit=False
 table.columns[0].width=2500000
 table.columns[1].width=3500000

 #inserting contents into table cells
 for i in range(0,14):
   row=table.rows[i]
   row.cells[0].text=reqdheaderList[i]
   row.cells[1].text=reqdvalueList[i]
</code>```

I have been trying to make the contents of everything in column 1 bold, but it is not working.

```<code>  #inserting contents into table cells
   for i in range(0,14):
     row=table.rows[i]
     row.cells[0].text=reqdheaderList[i]
     row.cells[0].paragraphs[0].add_run(line[0]).bold=True
     row.cells[1].text=reqdvalueList[i]
</code>```

Help?

答:
Expanding @Nikos Tavoularis answer; you can also add a helper function. E.g.:

from docx import Document

def make_rows_bold(*rows):
    for row in rows:
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.bold = True

doc = Document()

table = doc.add_table(rows=4, cols=2)
table.cell(0, 0).text = "Some text"
table.cell(1, 0).text = "Some bold text"
table.cell(1, 1).text = "Some more bold text"
table.cell(2, 0).text = "Some text"
table.cell(3, 1).text = "And more bold text"

make_rows_bold(table.rows[1], table.rows[3])

doc.save('test.docx')
```

Writing more functions like make_rows_bold can make working with docx way more pleasant.

ContentLicense: CC BY-SA 3.0

Body:
The code snippet below basically creates a table with the required number of rows and columns in a new word document i.e 2 columns and 14 rows. It then adds the content to the rows and columns accordingly.

from docx import Document
newDoc=Document()
newDoc.add_heading ('GIS Request Form')
newDoc.add_paragraph()

#inserting a table and the header and value objects to the table
 table=newDoc.add_table(rows=14,cols=2)
 table.style='Table Grid'
 table.autofit=False
 table.columns[0].width=2500000
 table.columns[1].width=3500000

 #inserting contents into table cells
 for i in range(0,14):
   row=table.rows[i]
   row.cells[0].text=reqdheaderList[i]
   row.cells[1].text=reqdvalueList[i]

I have been trying to make the contents of everything in column 1 bold, but it is not working.

  #inserting contents into table cells
   for i in range(0,14):
     row=table.rows[i]
     row.cells[0].text=reqdheaderList[i]
     row.cells[0].paragraphs[0].add_run(line[0]).bold=True
     row.cells[1].text=reqdvalueList[i]

Help?

Body:
Expanding @Nikos Tavoularis answer; you can also add a helper function. E.g.:

from docx import Document

def make_rows_bold(*rows):
    for row in rows:
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.bold = True

doc = Document()

table = doc.add_table(rows=4, cols=2)
table.cell(0, 0).text = "Some text"
table.cell(1, 0).text = "Some bold text"
table.cell(1, 1).text = "Some more bold text"
table.cell(2, 0).text = "Some text"
table.cell(3, 1).text = "And more bold text"

make_rows_bold(table.rows[1], table.rows[3])

doc.save('test.docx')

Writing more functions like make_rows_bold can make working with docx way more pleasant.


问:
How to prevent currency rounding errors with decimal variable type?
I am working on a payment plan calculator. I switched from 'double' to 'decimal' variable types to prevent rounding errors but I am still getting one somewhere. I came up with this data-set to use to test my code because there is a clear remainder:

Balance: $1,575.75

Down Payment: $500.00

Remaining Balance: $1,075.75

Number of Payments after the Down Payment: 9

Installment Amount: $119.53 (x8)

Remainder: $119.51

I switched my datatypes from double to decimal (obviously)
I tried re-writing the code multiple times calculating the same things in different ways (which is why some of the math at this point is less than 'minimalist')
I tried making my code more modular to find the rounding error

```<code>// Method within my WinForms project
public void CalculateInstallmentPayments()
{
    decimal currentBalance = Convert.ToDecimal(txtBalanceInput.Text); // Current Balance
    decimal downPayment = Convert.ToDecimal(txtDownPayment.Text); // Down Payment
    decimal installmentCount = sliderRemainingPmtCount.Value; // Installment Count
    decimal balanceAfterDP = currentBalance - downPayment; // Balance After Down Payment
    decimal installmentAmount = (balanceAfterDP / installmentCount); // Installment Amount
    decimal remainderPayment = (balanceAfterDP - (installmentAmount * (installmentCount - 1))); // Final Payment (Remainder)

    // Using Rich Text box as a 'Console' for debugging
    rtxtNotate.Text = ($"Current Balance: {currentBalance.ToString()}\nDown Payment: {downPayment.ToString("C")}\n" +
        $"Installment Count: {installmentCount.ToString()}\nInstallment Amount: {installmentAmount.ToString("C")}\n" +
        $"Remainder: {remainderPayment.ToString("C")}\n");
}
</code>```

This is currently the output:

Current Balance: 1575.75

Down Payment: $500.00

Installment Count: 9

Installment Amount: $119.53

Remainder: $119.53 -- This is the rounding error. It should read $119.51

I've been refactoring this code for hours and I feel like I'm missing something incredibly simple.

答:
You can use:

```<code>decimal currentBalance = 1575.75M; // Current Balance
        decimal downPayment = 500.00M; // Down Payment
        decimal installmentCount = 9; // Installment Count
        decimal balanceAfterDP = currentBalance - downPayment; // Balance After Down Payment
        decimal installmentAmount = Math.Round((balanceAfterDP / installmentCount),2, MidpointRounding.AwayFromZero); // Installment Amount
        decimal remainderPayment = (balanceAfterDP - (installmentAmount * (installmentCount - 1))); // Final Payment (Remainder)
</code>```

and you will get the right value : 119.51

Body:
I am working on a payment plan calculator. I switched from 'double' to 'decimal' variable types to prevent rounding errors but I am still getting one somewhere. I came up with this data-set to use to test my code because there is a clear remainder:

Balance: $1,575.75

Down Payment: $500.00

Remaining Balance: $1,075.75

Number of Payments after the Down Payment: 9

Installment Amount: $119.53 (x8)

Remainder: $119.51

I switched my datatypes from double to decimal (obviously)
I tried re-writing the code multiple times calculating the same things in different ways (which is why some of the math at this point is less than 'minimalist')
I tried making my code more modular to find the rounding error

// Method within my WinForms project
public void CalculateInstallmentPayments()
{
    decimal currentBalance = Convert.ToDecimal(txtBalanceInput.Text); // Current Balance
    decimal downPayment = Convert.ToDecimal(txtDownPayment.Text); // Down Payment
    decimal installmentCount = sliderRemainingPmtCount.Value; // Installment Count
    decimal balanceAfterDP = currentBalance - downPayment; // Balance After Down Payment
    decimal installmentAmount = (balanceAfterDP / installmentCount); // Installment Amount
    decimal remainderPayment = (balanceAfterDP - (installmentAmount * (installmentCount - 1))); // Final Payment (Remainder)

    // Using Rich Text box as a 'Console' for debugging
    rtxtNotate.Text = ($"Current Balance: {currentBalance.ToString()}\nDown Payment: {downPayment.ToString("C")}\n" +
        $"Installment Count: {installmentCount.ToString()}\nInstallment Amount: {installmentAmount.ToString("C")}\n" +
        $"Remainder: {remainderPayment.ToString("C")}\n");
}

This is currently the output:

Current Balance: 1575.75

Down Payment: $500.00

Installment Count: 9

Installment Amount: $119.53

Remainder: $119.53 -- This is the rounding error. It should read $119.51

I've been refactoring this code for hours and I feel like I'm missing something incredibly simple.

Body:
You can use:

decimal currentBalance = 1575.75M; // Current Balance
        decimal downPayment = 500.00M; // Down Payment
        decimal installmentCount = 9; // Installment Count
        decimal balanceAfterDP = currentBalance - downPayment; // Balance After Down Payment
        decimal installmentAmount = Math.Round((balanceAfterDP / installmentCount),2, MidpointRounding.AwayFromZero); // Installment Amount
        decimal remainderPayment = (balanceAfterDP - (installmentAmount * (installmentCount - 1))); // Final Payment (Remainder)

and you will get the right value : 119.51


问:
How to Validate FormArray length in angular2
I have a data driven form in angular2 like below

```<code>this.formBuilder.group({
  'name': ['',Validators.required],
  'description': ['', Validators.required],
  'places': this.formBuilder.array([], Validators.minlength(1))
})
</code>```

I want to add validations to the place formArray, so i am adding minlength validation, but minlength validation is not working on formArray.

What are the other validations for formArray, so that form must be valid only when places array contain atleast one place.

答:
Having a template

```<code><div formArrayName="items">
    <div *ngFor="[...] let i = index" [formGroupName]="i">

    [...]

    </div>
</div>
</code>```

You could simply use this in your button :

```<code>[disabled]="!myForm.get('items.1')"
</code>```

Body:
I have a data driven form in angular2 like below

this.formBuilder.group({
  'name': ['',Validators.required],
  'description': ['', Validators.required],
  'places': this.formBuilder.array([], Validators.minlength(1))
})

I want to add validations to the place formArray, so i am adding minlength validation, but minlength validation is not working on formArray.

What are the other validations for formArray, so that form must be valid only when places array contain atleast one place.

Body:
Having a template

<div formArrayName="items">
    <div *ngFor="[...] let i = index" [formGroupName]="i">

    [...]

    </div>
</div>

You could simply use this in your button :

[disabled]="!myForm.get('items.1')"


问:
Why width style value not show in input?
I'm trying to take the width from the "demo" div and put it in the "input number" value. I can not figure out where I made a mistake...

function myFunction() {
    var element = document.getElementById("poster"),
    style = window.getComputedStyle(element),
    width = style.getPropertyValue('width');

  document.getElementById("demo").value = width;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
<div id="poster" style="width:35px;height:45px;background-color:blue;"></div>

<input id="demo" type="number" placeholder="0" min="" max="" step="0.1">

<button onclick="myFunction()" type="button">Click Me!</button>
 </code>```

答:
This issue because width value is 35px so you should remove px before assign it to document.getElementById("demo").value to be number as soon as your input type is number as following code

```<code><div id="poster" style="width:35px;height:45px;background-color:blue;"></div>
<input id="demo" type="number" placeholder="0" min="" max="" step="0.1">
<button onclick="myFunction()" type="button">Click Me!</button>
<script>
    function myFunction() {
        var element = document.getElementById("poster"),
        style = window.getComputedStyle(element),
        width = style.getPropertyValue('width').match(/\d+/);

      document.getElementById("demo").value = width;
    }
</script>
</code>```

if you want to get width number as it is without unit eg. 35px or 35% will get 35 you can use the following code:

```<code>  <div id="poster" style="width:35px;height:45px;background-color:blue;"></div>
<input id="demo" type="number" placeholder="0" min="" max="" step="0.1">
<select id="unit" >
  <option >none</option>
  <option value="%">%</option>
  <option value="px">px</option>
</select>
<button onclick="myFunction()" type="button">Click Me!</button>
<script>
    function myFunction() {
        var element = document.getElementById("poster"),
        width = element.style["width"].match(/\d+/),
        unit = element.style["width"].match(/[^\d]+/);
        document.getElementById("unit").value = unit
        document.getElementById("demo").value = width;
    }
</script>
</code>```

Body:
I'm trying to take the width from the "demo" div and put it in the "input number" value. I can not figure out where I made a mistake...

function myFunction() {
    var element = document.getElementById("poster"),
    style = window.getComputedStyle(element),
    width = style.getPropertyValue('width');

  document.getElementById("demo").value = width;
}

<input id="demo" type="number" placeholder="0" min="" max="" step="0.1">

<button onclick="myFunction()" type="button">Click Me!</button>

Body:
This issue because width value is 35px so you should remove px before assign it to document.getElementById("demo").value to be number as soon as your input type is number as following code

<div id="poster" style="width:35px;height:45px;background-color:blue;"></div>
<input id="demo" type="number" placeholder="0" min="" max="" step="0.1">
<button onclick="myFunction()" type="button">Click Me!</button>
<script>
    function myFunction() {
        var element = document.getElementById("poster"),
        style = window.getComputedStyle(element),
        width = style.getPropertyValue('width').match(/\d+/);

      document.getElementById("demo").value = width;
    }
</script>

if you want to get width number as it is without unit eg. 35px or 35% will get 35 you can use the following code:

  <div id="poster" style="width:35px;height:45px;background-color:blue;"></div>
<input id="demo" type="number" placeholder="0" min="" max="" step="0.1">
<select id="unit" >
  <option >none</option>
  <option value="%">%</option>
  <option value="px">px</option>
</select>
<button onclick="myFunction()" type="button">Click Me!</button>
<script>
    function myFunction() {
        var element = document.getElementById("poster"),
        width = element.style["width"].match(/\d+/),
        unit = element.style["width"].match(/[^\d]+/);
        document.getElementById("unit").value = unit
        document.getElementById("demo").value = width;
    }
</script>


问:
Error: mat-form-field, mat-selection-list must contain a MatFormFieldControl
I am trying to add a checkbox and attach to a formfield. I am using angular 7.
I am using tags mat-form-field, and for this I am getting error

mat-form-field must contain a MatFormFieldControl.

I have checked my Component code and made sure FormControl exist. Though it is not very clear but add formControl "mat-selection-list"

```<code>//DECLARE CONTROL
    preexistingControl = new FormControl('',[Validators.required]);
// CHECKBOX DATA
    preExistingCondList: PreExistingCond[] = [
            {id:'0' ,value:'None'},
            {id:'1' ,value:'Arthritis'},
            {id:'2' ,value:'Asthma'},];
//ADD TO FormGroup
    preexistingControl:this.preexistingControl,
</code>```

HTML code

```<code><mat-form-field>
    <mat-selection-list #preConditions placeholder="PreExisting Conditions" [formControl]="preexistingControl">
        <mat-list-option *ngFor="let preExistingCond of preExistingCondList">
                        {{preExistingCond.value}}
        </mat-list-option>
    </mat-selection-list>
</mat-form-field>
</code>```

It is throwing following error:

```<code>ERROR Error: mat-form-field must contain a MatFormFieldControl.
    at getMatFormFieldMissingControlError (form-field.es5.js:119)
    at MatFormField.push../node_modules/@angular/material/esm5/form-field.es5.js.MatFormField._validateControlChild (form-field.es5.js:764)
    at MatFormField.push../node_modules/@angular/material/esm5/form-field.es5.js.MatFormField.ngAfterContentInit (form-field.es5.js:453)
    at callProviderLifecycles (core.js:22311)
    at callElementProvidersLifecycles (core.js:22292)
    at callLifecycleHooksChildrenFirst (core.js:22282)
    at checkAndUpdateView (core.js:23213)
    at callViewAction (core.js:23450)
    at execComponentViewsAction (core.js:23392)
    at checkAndUpdateView (core.js:23215)
</code>```

I have check the formControl exist and the ref id is correct.

答:
It is possible to do this with a small work around, this applies to any material components that are not supported. You can nest them within a mat-form-field like so.

```<code>    <mat-form-field [formGroup]="formGroup" class="mat-form-field--no-underline">
        <!-- Important part, input with matInput -->
        <input matInput style="display: none!important">
        <mat-selection-list #preConditions [formControl]="preexistingControl" [(ngModel)]="controlAnswer.value">
            <mat-list-option *ngFor="let preExistingCond of preExistingCondList">
                {{preExistingCond.value}}
            </mat-list-option>
        </mat-selection-list>
     </mat-form-field>
</code>```

And then you need the following CSS

```<code>  .mat-form-field--no-underline .mat-form-field-underline {
     background-color: transparent !important;
  }
</code>```

If the style does not apply you can use ngdeep to have it apply

Body:
I am trying to add a checkbox and attach to a formfield. I am using angular 7.
I am using tags mat-form-field, and for this I am getting error

mat-form-field must contain a MatFormFieldControl.

I have checked my Component code and made sure FormControl exist. Though it is not very clear but add formControl "mat-selection-list"

//DECLARE CONTROL
    preexistingControl = new FormControl('',[Validators.required]);
// CHECKBOX DATA
    preExistingCondList: PreExistingCond[] = [
            {id:'0' ,value:'None'},
            {id:'1' ,value:'Arthritis'},
            {id:'2' ,value:'Asthma'},];
//ADD TO FormGroup
    preexistingControl:this.preexistingControl,

HTML code

<mat-form-field>
    <mat-selection-list #preConditions placeholder="PreExisting Conditions" [formControl]="preexistingControl">
        <mat-list-option *ngFor="let preExistingCond of preExistingCondList">
                        {{preExistingCond.value}}
        </mat-list-option>
    </mat-selection-list>
</mat-form-field>

It is throwing following error:

ERROR Error: mat-form-field must contain a MatFormFieldControl.
    at getMatFormFieldMissingControlError (form-field.es5.js:119)
    at MatFormField.push../node_modules/@angular/material/esm5/form-field.es5.js.MatFormField._validateControlChild (form-field.es5.js:764)
    at MatFormField.push../node_modules/@angular/material/esm5/form-field.es5.js.MatFormField.ngAfterContentInit (form-field.es5.js:453)
    at callProviderLifecycles (core.js:22311)
    at callElementProvidersLifecycles (core.js:22292)
    at callLifecycleHooksChildrenFirst (core.js:22282)
    at checkAndUpdateView (core.js:23213)
    at callViewAction (core.js:23450)
    at execComponentViewsAction (core.js:23392)
    at checkAndUpdateView (core.js:23215)

I have check the formControl exist and the ref id is correct.

Body:
It is possible to do this with a small work around, this applies to any material components that are not supported. You can nest them within a mat-form-field like so.

    <mat-form-field [formGroup]="formGroup" class="mat-form-field--no-underline">
        <!-- Important part, input with matInput -->
        <input matInput style="display: none!important">
        <mat-selection-list #preConditions [formControl]="preexistingControl" [(ngModel)]="controlAnswer.value">
            <mat-list-option *ngFor="let preExistingCond of preExistingCondList">
                {{preExistingCond.value}}
            </mat-list-option>
        </mat-selection-list>
     </mat-form-field>

And then you need the following CSS

  .mat-form-field--no-underline .mat-form-field-underline {
     background-color: transparent !important;
  }

If the style does not apply you can use ngdeep to have it apply


问:
C# - How to delete selected rows from a DataGridView?
I am trying to delete the row which the user selects in a DataGridView in a C# WinForms app (connected to a local DB that has records already).

I have implemented the code below, and there are no errors, but the delete is never picked up (even though messagebox shows that a record has been 'deleted', which is not true, as the record remains in the DataGrid)

Please also note that the delete function is within a Search function - please see below code.

```<code>public void DisplayData()
    {
        string ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename= C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\Library System Project.mdf ;Integrated Security=True;Connect Timeout=30";

        string Query = "select * from Customers";

        SqlConnection DBCon = new SqlConnection(ConnectionString);
        SqlCommand DBCommand = new SqlCommand(Query, DBCon);
        SqlDataReader DBReader;

        try
        {
            DBCon.Open();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(DBCommand);
            da.Fill(dt);
            dgv_CustomerDetails.DataSource = dt;
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        finally
        {
            // *** If you're going to be opening a connection be sure to close it ***
            // *** Finally blocks work well for this ***
            DBCon.Close();
        }
    }

    private void SearchCustomerRecordForm_Load(object sender, EventArgs e)
    {
        DisplayData();
    }

    private void btnDeleteCustomerRecord_Click(object sender, EventArgs e)
    {
        string ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename= C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\Library System Project.mdf ;Integrated Security=True;Connect Timeout=30";

        int rowIndex = dgv_CustomerDetails.CurrentCell.RowIndex;

        string Query = "delete from Customers where CustomerName = '"+ dgv_CustomerDetails.CurrentCell(rowIndex) +"'";

        SqlConnection DBCon = new SqlConnection(ConnectionString);
        SqlCommand DBCommand = new SqlCommand(Query, DBCon);
        SqlDataReader DBReader;

        try
        {
            DBCon.Open();
            DBReader = DBCommand.ExecuteReader();
            MessageBox.Show("Customer record removed from the system.", "Library System", MessageBoxButtons.OK);
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        finally
        {
            // *** If you're going to be opening a connection be sure to close it ***
            // *** Finally blocks work well for this ***
            DBCon.Close();
            DisplayData();
        }
    }
</code>```

答:
Are you sure that Query is created well? It seems that there is missing Cell Value property in that row:

```<code>string Query = "delete from Customers where CustomerName = '"+ dgv_CustomerDetails.CurrentCell(rowIndex).value +"'";
</code>```

try to look at the value of Query variable since it is builded up.

Body:
I am trying to delete the row which the user selects in a DataGridView in a C# WinForms app (connected to a local DB that has records already).

I have implemented the code below, and there are no errors, but the delete is never picked up (even though messagebox shows that a record has been 'deleted', which is not true, as the record remains in the DataGrid)

Please also note that the delete function is within a Search function - please see below code.

public void DisplayData()
    {
        string ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename= C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\Library System Project.mdf ;Integrated Security=True;Connect Timeout=30";

        string Query = "select * from Customers";

        SqlConnection DBCon = new SqlConnection(ConnectionString);
        SqlCommand DBCommand = new SqlCommand(Query, DBCon);
        SqlDataReader DBReader;

        try
        {
            DBCon.Open();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(DBCommand);
            da.Fill(dt);
            dgv_CustomerDetails.DataSource = dt;
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        finally
        {
            // *** If you're going to be opening a connection be sure to close it ***
            // *** Finally blocks work well for this ***
            DBCon.Close();
        }
    }

    private void SearchCustomerRecordForm_Load(object sender, EventArgs e)
    {
        DisplayData();
    }

    private void btnDeleteCustomerRecord_Click(object sender, EventArgs e)
    {
        string ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename= C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\Library System Project.mdf ;Integrated Security=True;Connect Timeout=30";

        int rowIndex = dgv_CustomerDetails.CurrentCell.RowIndex;

        string Query = "delete from Customers where CustomerName = '"+ dgv_CustomerDetails.CurrentCell(rowIndex) +"'";

        SqlConnection DBCon = new SqlConnection(ConnectionString);
        SqlCommand DBCommand = new SqlCommand(Query, DBCon);
        SqlDataReader DBReader;

        try
        {
            DBCon.Open();
            DBReader = DBCommand.ExecuteReader();
            MessageBox.Show("Customer record removed from the system.", "Library System", MessageBoxButtons.OK);
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        finally
        {
            // *** If you're going to be opening a connection be sure to close it ***
            // *** Finally blocks work well for this ***
            DBCon.Close();
            DisplayData();
        }
    }

Body:
Are you sure that Query is created well? It seems that there is missing Cell Value property in that row:

string Query = "delete from Customers where CustomerName = '"+ dgv_CustomerDetails.CurrentCell(rowIndex).value +"'";

try to look at the value of Query variable since it is builded up.


问:
Selecting elements from "div" dropdown - Selenium
I have a "div" dropdown, not "select". So my function works fine everywhere except dropdows which open not from the dropdown button place, but from above (because dropdown is placed at the bottom of the page) to prevent... page scrolling i guess? Maybe the problem is that it opens too fast or too slow or what, so function usually clicks not the needed element but one of the closest to it. Mostly it works this way if element is not at the beginning of dropdown so it is scrolled to the element. Any suggestions what can be made?

The best way i found is to use actions, splitting moving to element and clicking into 2 rows (works much worse if writing in 1 row). By the way, "waitVisibilityOfElement(By)" is a function with webdriver wait for expected conditions

```<code>public void selectFromDropdown(By by) {
        Log.debug("selecting from dropdown by" + by);
        waitVisibilityOfElement(by);
        Actions actions = new Actions(wrappedWebDriver);
       actions.moveToElement(wrappedWebDriver.findElement(by)).perform();
        Log.debug("clicking dropdown item");
        wrappedWebDriver.findElement(by).click();
}
</code>```

I expect needed element to be clicked, But usually it clicks another one

Ok with some help i came to a final decision which is the best way to select dropdown filters without using any .sleep() functions if other simple ways do not work for you.

```<code>public void selectFromDropdown(By by) {
        Log.debug("selecting from dropdown by" + by);
        WebElement eleV = wrappedWebDriver.findElement(by);

        waitVisibilityOfElement(by);

        JavascriptExecutor js = (JavascriptExecutor) wrappedWebDriver;
        js.executeScript("arguments[0].scrollIntoView();", eleV);

        Actions actions = new Actions(wrappedWebDriver);
        actions.moveToElement(wrappedWebDriver.findElement(by)).perform();
        Log.debug("clicking dropdown item");
        wrappedWebDriver.findElement(by).click();
    }
</code>```

答:
If the you are trying to click a static value, you can directly click the value from the dropdown

you can try this

```<code>driver.findElement(By.xpath("THE VALUE FROM DROPDOWN")).click();
</code>```

Body:
I have a "div" dropdown, not "select". So my function works fine everywhere except dropdows which open not from the dropdown button place, but from above (because dropdown is placed at the bottom of the page) to prevent... page scrolling i guess? Maybe the problem is that it opens too fast or too slow or what, so function usually clicks not the needed element but one of the closest to it. Mostly it works this way if element is not at the beginning of dropdown so it is scrolled to the element. Any suggestions what can be made?

The best way i found is to use actions, splitting moving to element and clicking into 2 rows (works much worse if writing in 1 row). By the way, "waitVisibilityOfElement(By)" is a function with webdriver wait for expected conditions

public void selectFromDropdown(By by) {
        Log.debug("selecting from dropdown by" + by);
        waitVisibilityOfElement(by);
        Actions actions = new Actions(wrappedWebDriver);
       actions.moveToElement(wrappedWebDriver.findElement(by)).perform();
        Log.debug("clicking dropdown item");
        wrappedWebDriver.findElement(by).click();
}

I expect needed element to be clicked, But usually it clicks another one

Ok with some help i came to a final decision which is the best way to select dropdown filters without using any .sleep() functions if other simple ways do not work for you.

public void selectFromDropdown(By by) {
        Log.debug("selecting from dropdown by" + by);
        WebElement eleV = wrappedWebDriver.findElement(by);

        waitVisibilityOfElement(by);

        JavascriptExecutor js = (JavascriptExecutor) wrappedWebDriver;
        js.executeScript("arguments[0].scrollIntoView();", eleV);

        Actions actions = new Actions(wrappedWebDriver);
        actions.moveToElement(wrappedWebDriver.findElement(by)).perform();
        Log.debug("clicking dropdown item");
        wrappedWebDriver.findElement(by).click();
    }

Body:
If the you are trying to click a static value, you can directly click the value from the dropdown

you can try this

driver.findElement(By.xpath("THE VALUE FROM DROPDOWN")).click();


问:
Use two UIPickerView in the same UIView the second UIPickerView can not align center the content
I use two UIPickerView in the same view, but the second one can not align center the content, can anyone help me out?

答:
I have solved this problem.

When using two dynamic arrays of two UIPicker, this will happen.

So, Just be careful.


问:
ec2 centos userdata not ran
I am trying to deploy an ruby on rails app through centos ec2 instance by using userdata at instance startup, the specify image is an centos 7 image. below is my userdata section. However, the userdata is not working and even the log file was not created when I piped each command output to an log. Does anyone have any insight on this or how to troubleshoot ec2 userdata? I have looked at the cloud-init.log file in /var/logs too but unable to make out which command actually ran and which one did not, I have included the last few lines from the log below as well. any help is appreciated thanks!

```<code>#!/bin/bash
sudo yum update -y | tee -a log.txt
sudo gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 | tee -a /home/ec2-user/log.txt
curl -sSL https://get.rvm.io | sudo bash -s stable | tee -a /home/ec2-user/log.txt
sudo usermod -a -G rvm `whoami` | tee -a /home/ec2-user/log.txt
if sudo grep -q secure_path /etc/sudoers; then sudo sh -c "echo export rvmsudo_secure_path=1 >> /etc/profile.d/rvm_secure_path.sh" && echo Environment variable installed; fi | & tee -a log.txt
sudo su ec2-user
rvm install ruby | tee -a /home/ec2-user/log.txt
rvm --default use ruby | tee -a /home/ec2-user/log.txt
curl -sL https://rpm.nodesource.com/setup_11.x | sudo -E bash - | tee -a /home/ec2-user/log.txt
sudo yum install -y nodejs | tee -a /home/ec2-user/log.txt
sudo yum -y install ImageMagick-devel | tee -a /home/ec2-user/log.txt
sudo yum -y upgrade | tee -a /home/ec2-user/log.txt
sudo yum -y install git | tee -a /home/ec2-user/log.txt
sudo yum -y install java-1.8.0-openjdk | tee -a log.txt
export JAVA_HOME="/usr/lib/jvm/jre-1.8.0-openjdk" | tee -a /home/ec2-user/log.txt
export PATH=$JAVA_HOME/bin:$PATH | tee -a /home/ec2-user/log.txt
sudo yum install postgresql postgresql-server postgresql-devel postgresql-contrib postgresql-docs | tee -a /home/ec2-user/log.txt
rails new app-name -m https://raw.githubusercontent.com/projectblacklight/spotlight/master/template.rb | tee -a /home/ec2-user/log.txt
cd app-name
rake db:migrate | tee -a /home/ec2-user/log.txt
solr_wrapper | tee -a /home/ec2-user/log.txt
rails server | tee -a /home/ec2-user/log.txt
</code>```

the cloud-init.log

```<code>2018-12-10 16:24:43,554 - util.py[DEBUG]: Cloud-init v. 0.7.9 finished at Mon, 10 Dec 2018 21:24:43 +0000. Datasource DataSourceEc2.  Up 735.81 seconds
2018-12-10 16:24:43,554 - util.py[DEBUG]: Writing to /var/lib/cloud/instance/boot-finished - wb: [420] 52 bytes
2018-12-10 16:24:43,555 - util.py[DEBUG]: Restoring selinux mode for /var/lib/cloud/instances/i-0b323a8331354129b/boot-finished (recursive=False)
2018-12-10 16:24:43,555 - util.py[DEBUG]: Restoring selinux mode for /var/lib/cloud/instances/i-0b323a8331354129b/boot-finished (recursive=False)
2018-12-10 16:24:43,556 - handlers.py[DEBUG]: finish: modules-final/config-final-message: SUCCESS: config-final-message ran successfully
2018-12-10 16:24:43,556 - main.py[DEBUG]: Ran 9 modules with 1 failures
2018-12-10 16:24:43,565 - util.py[DEBUG]: Creating symbolic link from '/run/cloud-init/result.json' => '../../var/lib/cloud/data/result.json'
2018-12-10 16:24:43,566 - util.py[DEBUG]: Reading from /proc/uptime (quiet=False)
2018-12-10 16:24:43,566 - util.py[DEBUG]: Read 14 bytes from /proc/uptime
2018-12-10 16:24:43,566 - util.py[DEBUG]: cloud-init mode 'modules' took 687.571 seconds (687.57)
2018-12-10 16:24:43,566 - handlers.py[DEBUG]: finish: modules-final: FAIL: running modules for final
</code>```

答:
CloudFormation? Did you remember to Base64 encode the userdata?</p>

```<code>  EventCollectionLc:
    Type: 'AWS::AutoScaling::LaunchConfiguration'
    Properties:
      UserData: !Base64
        'Fn::Sub': |
          #!/bin/bash
</code>```

Title: ec2 centos userdata not ran

Body:
I am trying to deploy an ruby on rails app through centos ec2 instance by using userdata at instance startup, the specify image is an centos 7 image. below is my userdata section. However, the userdata is not working and even the log file was not created when I piped each command output to an log. Does anyone have any insight on this or how to troubleshoot ec2 userdata? I have looked at the cloud-init.log file in /var/logs too but unable to make out which command actually ran and which one did not, I have included the last few lines from the log below as well. any help is appreciated thanks!

#!/bin/bash
sudo yum update -y | tee -a log.txt
sudo gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 | tee -a /home/ec2-user/log.txt
curl -sSL https://get.rvm.io | sudo bash -s stable | tee -a /home/ec2-user/log.txt
sudo usermod -a -G rvm `whoami` | tee -a /home/ec2-user/log.txt
if sudo grep -q secure_path /etc/sudoers; then sudo sh -c "echo export rvmsudo_secure_path=1 >> /etc/profile.d/rvm_secure_path.sh" && echo Environment variable installed; fi | & tee -a log.txt
sudo su ec2-user
rvm install ruby | tee -a /home/ec2-user/log.txt
rvm --default use ruby | tee -a /home/ec2-user/log.txt
curl -sL https://rpm.nodesource.com/setup_11.x | sudo -E bash - | tee -a /home/ec2-user/log.txt
sudo yum install -y nodejs | tee -a /home/ec2-user/log.txt
sudo yum -y install ImageMagick-devel | tee -a /home/ec2-user/log.txt
sudo yum -y upgrade | tee -a /home/ec2-user/log.txt
sudo yum -y install git | tee -a /home/ec2-user/log.txt
sudo yum -y install java-1.8.0-openjdk | tee -a log.txt
export JAVA_HOME="/usr/lib/jvm/jre-1.8.0-openjdk" | tee -a /home/ec2-user/log.txt
export PATH=$JAVA_HOME/bin:$PATH | tee -a /home/ec2-user/log.txt
sudo yum install postgresql postgresql-server postgresql-devel postgresql-contrib postgresql-docs | tee -a /home/ec2-user/log.txt
rails new app-name -m https://raw.githubusercontent.com/projectblacklight/spotlight/master/template.rb | tee -a /home/ec2-user/log.txt
cd app-name
rake db:migrate | tee -a /home/ec2-user/log.txt
solr_wrapper | tee -a /home/ec2-user/log.txt
rails server | tee -a /home/ec2-user/log.txt

the cloud-init.log

2018-12-10 16:24:43,554 - util.py[DEBUG]: Cloud-init v. 0.7.9 finished at Mon, 10 Dec 2018 21:24:43 +0000. Datasource DataSourceEc2.  Up 735.81 seconds
2018-12-10 16:24:43,554 - util.py[DEBUG]: Writing to /var/lib/cloud/instance/boot-finished - wb: [420] 52 bytes
2018-12-10 16:24:43,555 - util.py[DEBUG]: Restoring selinux mode for /var/lib/cloud/instances/i-0b323a8331354129b/boot-finished (recursive=False)
2018-12-10 16:24:43,555 - util.py[DEBUG]: Restoring selinux mode for /var/lib/cloud/instances/i-0b323a8331354129b/boot-finished (recursive=False)
2018-12-10 16:24:43,556 - handlers.py[DEBUG]: finish: modules-final/config-final-message: SUCCESS: config-final-message ran successfully
2018-12-10 16:24:43,556 - main.py[DEBUG]: Ran 9 modules with 1 failures
2018-12-10 16:24:43,565 - util.py[DEBUG]: Creating symbolic link from '/run/cloud-init/result.json' => '../../var/lib/cloud/data/result.json'
2018-12-10 16:24:43,566 - util.py[DEBUG]: Reading from /proc/uptime (quiet=False)
2018-12-10 16:24:43,566 - util.py[DEBUG]: Read 14 bytes from /proc/uptime
2018-12-10 16:24:43,566 - util.py[DEBUG]: cloud-init mode 'modules' took 687.571 seconds (687.57)
2018-12-10 16:24:43,566 - handlers.py[DEBUG]: finish: modules-final: FAIL: running modules for final

Body:
CloudFormation? Did you remember to Base64 encode the userdata?

  EventCollectionLc:
    Type: 'AWS::AutoScaling::LaunchConfiguration'
    Properties:
      UserData: !Base64
        'Fn::Sub': |
          #!/bin/bash


问:
Coding in Objective-C 2.0 screencasts?
Has anyone used the Pragmatic Programmers screencast series Coding in Objective-C 2.0?

They look good, but I don't know if I could get just as much value out of a text book or other web links.

答:
At $5.00 a video your not going to find "as much value out of a  text book" books would cover a lot more information though.

edit:

I haven't watched the screen casts, but If you have programming expereinece, getting a book (maybe even their book?) would be what I'd recomend instead. By just looking at the topics covered and the time given I can't see the screen casts (the two that are available I mean) going into that much detail

OwnerDisplayName: Steven Behnke

ContentLicense: CC BY-SA 2.5

Title: Coding in Objective-C 2.0 screencasts?

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: hhafez

LastEditorDisplayName: hhafez


问:
How to check if the default JS object been modified?
How can I check from my JS script (running on my HTML page, that is loaded in user's browser), that some base JS API been spoofed by user (browser extension or whatever)? Like HTMLElement.prototype.appendChild() method or screen.width property?

答:
A basic (but by no means foolproof) method would be to check if the function is still composed of native code. If not, then it's definitely been monkeypatched; if so, then if it's been monkeypatched, it's also had its toString method purposefully changed, to avoid this sort of detection (which is possible, but probably pretty unusual to see):

const checkValid = () => {
  const { appendChild } = Node.prototype;
  if (appendChild.toString() === `function appendChild() { [native code] }`) {
    document.write('Might not have been modified
');
  } else {
    document.write('Definitely modified
');
  }
};

checkValid();
Node.prototype.appendChild = () => {
  console.log('My monkeypatched function');
};
checkValid();
// Check is foolable via:
const fooler = function appendChild() {
  console.log('My monkeypatched function');
};
fooler.toString = () => `function appendChild() { [native code] }`;
Node.prototype.appendChild = fooler;
checkValid();```
</div>
</div>
</p>

<blockquote>
  <p>Like HTMLElement.prototype.appendChild() method</p>
</blockquote>

<p>The object that <code>appendChild</code> is directly on is <code>Node.protoype.</code> If the monkeypatcher has put it on <code>HTMLElement.prototype</code> (or the element itself), that's easily detectable:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const div = document.querySelector('div');
if (HTMLElement.prototype.hasOwnProperty('appendChild')) {
  console.log('Definitely modified');
}

if (div.appendChild !== Node.prototype.appendChild) {
  console.log('Definitely modified');
}</code>```

```

Body:
A basic (but by no means foolproof) method would be to check if the function is still composed of native code. If not, then it's definitely been monkeypatched; if so, then if it's been monkeypatched, it's also had its toString method purposefully changed, to avoid this sort of detection (which is possible, but probably pretty unusual to see):

const checkValid = () => {
  const { appendChild } = Node.prototype;
  if (appendChild.toString() === `function appendChild() { [native code] }`) {
    document.write('Might not have been modified<br>');
  } else {
    document.write('Definitely modified<br>');
  }
};

checkValid();
Node.prototype.appendChild = () => {
  console.log('My monkeypatched function');
};
checkValid();
// Check is foolable via:
const fooler = function appendChild() {
  console.log('My monkeypatched function');
};
fooler.toString = () => `function appendChild() { [native code] }`;
Node.prototype.appendChild = fooler;
checkValid();

Like HTMLElement.prototype.appendChild() method

The object that appendChild is directly on is Node.protoype. If the monkeypatcher has put it on HTMLElement.prototype (or the element itself), that's easily detectable:

const div = document.querySelector('div');
if (HTMLElement.prototype.hasOwnProperty('appendChild')) {
  console.log('Definitely modified');
}

if (div.appendChild !== Node.prototype.appendChild) {
  console.log('Definitely modified');
}

<div></div>


问:
How to return only the Date from a SQL Server DateTime datatype
```<code>SELECT GETDATE()
</code>```

Returns: 2008-09-22 15:24:13.790

I want that date part without the time part: 2008-09-22 00:00:00.000

How can I get that?

答:
The easiest way would be to use:
SELECT DATE(GETDATE())

OwnerDisplayName: eddiegroves

Body:
SELECT GETDATE()

Returns: 2008-09-22 15:24:13.790

I want that date part without the time part: 2008-09-22 00:00:00.000

How can I get that?

LastEditorDisplayName: Glenn Slaven


问:
Problem accessing wiki page with MediaWiki 1.32, PHP is out of date
I'm currently running a wiki website that's supported by MediaWiki. The site was made a while ago and I've never used the MediaWiki software to manage it before. The new update to MediaWiki 1.32 apparently causes an internal error on my wiki site apparently and returns the following when I try accessing it:

MediaWiki 1.32 internal error

MediaWiki 1.32 requires at least PHP version 7.0.13 or HHVM version 3.18.5, you are using PHP 5.6.39.
  Supported PHP versions

Please consider upgrading your copy of PHP. PHP versions less than 5.6.0 are no longer supported by the PHP Group and will not receive security or bugfix updates.

If for some reason you are unable to upgrade your PHP version, you will need to download an older version of MediaWiki from our website. See our compatibility page for details of which versions are compatible with prior versions of PHP.

Is there a way to update PHP for my website without needing to use the MediaWiki software? If not, is there a way to retrieve the information on the website?

Thanks

答:
You have to install PHP 7.0.13 or an higher version.

Here you can find the latest version of php and upgrade it manually

Here you can find a step by step guide to do that


问:
How to store session id with request all?
I'm trying to save the passed course_id into lesson form in a DRY format.

I've tried saving each variable individually and it worked, however when I try to DRY up the code it is not working. Here is the code That I've tried.

```<code>public function store(StoreLessonsRequest $request)
{
    if (! Gate::allows('lesson_create')) {
        return abort(401);
    }
    $request = $this->saveFiles($request);
    $lesson = Lesson::create($request->all() +
    $lesson->course_id = session()->get('id') +

        + ['position' => Lesson::where('course_id', $request->course_id)->max('position') + 1]);

    foreach ($request->input('lesson_materials_id', []) as $index => $id) {
        $model          = config('medialibrary.media_model');
        $file           = $model::find($id);
        $file->model_id = $lesson->id;
        $file->save();
    }

    return redirect()->route('admin.exams.create', ['course_id' => $request->course_id]);
}
</code>```

I expected the course_id to save, but is giving me an error of Unsupported operand types.

答:
Here is how I finally solved it. First I've declared the variable then I've passed it through.</p>

```<code>   public function store(StoreLessonsRequest $request)
    {
        if (! Gate::allows('lesson_create')) {
            return abort(401);
        }

        $request = $this->saveFiles($request);
        $seesion = session()->get('id');
        $lesson = Lesson::create($request->all()

            + ['position' => Lesson::where('course_id', $request->course_id)->max('position') + 1] + ['course_id' => $seesion] );

        foreach ($request->input('lesson_materials_id', []) as $index => $id) {
            $model          = config('medialibrary.media_model');
            $file           = $model::find($id);
            $file->model_id = $lesson->id;
            $file->save();
        }
</code>```

Body:
I'm trying to save the passed course_id into lesson form in a DRY format.

I've tried saving each variable individually and it worked, however when I try to DRY up the code it is not working. Here is the code That I've tried.

public function store(StoreLessonsRequest $request)
{
    if (! Gate::allows('lesson_create')) {
        return abort(401);
    }
    $request = $this->saveFiles($request);
    $lesson = Lesson::create($request->all() +
    $lesson->course_id = session()->get('id') +

        + ['position' => Lesson::where('course_id', $request->course_id)->max('position') + 1]);

    foreach ($request->input('lesson_materials_id', []) as $index => $id) {
        $model          = config('medialibrary.media_model');
        $file           = $model::find($id);
        $file->model_id = $lesson->id;
        $file->save();
    }

    return redirect()->route('admin.exams.create', ['course_id' => $request->course_id]);
}

I expected the course_id to save, but is giving me an error of Unsupported operand types.

Body:
Here is how I finally solved it. First I've declared the variable then I've passed it through.

   public function store(StoreLessonsRequest $request)
    {
        if (! Gate::allows('lesson_create')) {
            return abort(401);
        }

        $request = $this->saveFiles($request);
        $seesion = session()->get('id');
        $lesson = Lesson::create($request->all()

            + ['position' => Lesson::where('course_id', $request->course_id)->max('position') + 1] + ['course_id' => $seesion] );

        foreach ($request->input('lesson_materials_id', []) as $index => $id) {
            $model          = config('medialibrary.media_model');
            $file           = $model::find($id);
            $file->model_id = $lesson->id;
            $file->save();
        }


问:
Remove specific character from string (SQL Server 2012)
I have a view from which I want to remove a specific character in one of the columns. Specifically the character 'B' from the 'Fund' column below.

I tried using the following version of TRIM

```<code>  SELECT
       TRIM('B' FROM [Port_Ticker]) as "Fund"
      ,[BENCH_Ticker] as "Index ID"
      ,format(cast([VALUE_DATE] as Date),'dd/MM/yyyy') as "Updat"
      ,([Port_Risk_Contrib] / 10000000) as "StDev Fund"
      ,([Active_risk_contrib] / 10000000) as "TE"
      ,([BENCH_RISK_CONTRIB] / 100) as "StDev BM"
  FROM [DM_PORTFOLIO_ANALYSIS].[basedata].[PortfolioRiskFigures]
  where [BLOCK_FACTOR] = 'Total'
  and [Port_ticker] =
  'B1023'
  order by [VALUE_DATE] asc
</code>```

Which gives me the error

Msg 156, Level 15, State 1, Line 3.
   Incorrect syntax near the keyword 'FROM'.

答:
You can use replace() to do this. In this case it will search for 'B' and replace it with an empty string -> ''. Please note that this function will replace all 'B' from this column.

```<code> SELECT
       REPLACE([Port_Ticker], 'B', '') as "Fund"
      ,[BENCH_Ticker] as "Index ID"
      ,format(cast([VALUE_DATE] as Date),'dd/MM/yyyy') as "Updat"
      ,([Port_Risk_Contrib] / 10000000) as "StDev Fund"
      ,([Active_risk_contrib] / 10000000) as "TE"
      ,([BENCH_RISK_CONTRIB] / 100) as "StDev BM"
  FROM [DM_PORTFOLIO_ANALYSIS].[basedata].[PortfolioRiskFigures]
  where [BLOCK_FACTOR] = 'Total'
  and [Port_ticker] = 'B1023'
  order by [VALUE_DATE] asc
</code>```

Body:
I have a view from which I want to remove a specific character in one of the columns. Specifically the character 'B' from the 'Fund' column below.

I tried using the following version of TRIM

  SELECT
       TRIM('B' FROM [Port_Ticker]) as "Fund"
      ,[BENCH_Ticker] as "Index ID"
      ,format(cast([VALUE_DATE] as Date),'dd/MM/yyyy') as "Updat"
      ,([Port_Risk_Contrib] / 10000000) as "StDev Fund"
      ,([Active_risk_contrib] / 10000000) as "TE"
      ,([BENCH_RISK_CONTRIB] / 100) as "StDev BM"
  FROM [DM_PORTFOLIO_ANALYSIS].[basedata].[PortfolioRiskFigures]
  where [BLOCK_FACTOR] = 'Total'
  and [Port_ticker] =
  'B1023'
  order by [VALUE_DATE] asc

Which gives me the error

Msg 156, Level 15, State 1, Line 3.
   Incorrect syntax near the keyword 'FROM'.

Body:
You can use replace() to do this. In this case it will search for 'B' and replace it with an empty string -> ''. Please note that this function will replace all 'B' from this column.

 SELECT
       REPLACE([Port_Ticker], 'B', '') as "Fund"
      ,[BENCH_Ticker] as "Index ID"
      ,format(cast([VALUE_DATE] as Date),'dd/MM/yyyy') as "Updat"
      ,([Port_Risk_Contrib] / 10000000) as "StDev Fund"
      ,([Active_risk_contrib] / 10000000) as "TE"
      ,([BENCH_RISK_CONTRIB] / 100) as "StDev BM"
  FROM [DM_PORTFOLIO_ANALYSIS].[basedata].[PortfolioRiskFigures]
  where [BLOCK_FACTOR] = 'Total'
  and [Port_ticker] = 'B1023'
  order by [VALUE_DATE] asc


问:
How to consume Kafka Topic in Consumer MQ Topic
I have a requirement where I need to consume Kafka Topic and write it into MQ Topic. Can someone advise me the best way to do it, I am new to Kafka.

I have read about the IBM MQ Connector in confluent but could not get the idea how to implement it.

答:
The best way to move data from Kafka to MQ is to use the IBM MQ sink connector: https://github.com/ibm-messaging/kafka-connect-mq-sink

This is a Kafka Connect connector. The README contains details for building and running it.


问:
Set UIButton's background as a CAGradientLayer
How can I set the background of a UIButton to a CAGradientLayer?

I have tried the following:

func applyGradient(colors: [UIColor], locations: [NSNumber]?) -> Void {
    let gradient: CAGradientLayer = CAGradientLayer()
    gradient.frame = self.bounds
    gradient.colors = colors.map { $0.cgColor }
    gradient.locations = locations
    self.layer.insertSublayer(gradient, at: 0)
}
```

<p>which I got from Set Background Gradient on Button in Swift</p>

<p>and then to use it:</p>

<pre class="lang-swift prettyprint-override"><code>let startButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Get Started", for: .normal)
    button.setTitleColor(AppSettings.PURPL_COLOR, for: .normal)
    button.titleLabel?.font = UIFont(name: "Rubik-Medium", size: 16.0)
    return button
}()

startButton.applyGradient(colors: [.red, .blue], locations: nil)
</code>```

Also, I am setting the width of the button to the view's width and the height to 50.

However, when I run it, this is what I get:

The background gradient is not applied.

答:
Bounds of the button will be 0 when you call the method applyGradient. So create a UIButton subclass and change the gradient layer frame in layoutSublayers method

```<code>class GradientButton: UIButton {
    let gradient: CAGradientLayer = CAGradientLayer()
    internal override init(frame: CGRect) {
        super.init(frame: frame)
    }
    internal required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    required init(_ colors: [UIColor], locations: [NSNumber]?) {
        super.init(frame: .zero)
        applyGradient(colors,locations:locations)
    }
    func applyGradient(_ colors: [UIColor], locations: [NSNumber]?) {
        gradient.colors = colors
        gradient.locations = locations
        gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
        gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
        layer.insertSublayer(gradient, at: 0)
    }
    override func layoutSublayers(of layer: CALayer) {
        super.layoutSublayers(of: layer)
        gradient.frame = self.bounds
    }
}
</code>```

And create the button with color and location values

```<code>let button = GradientButton([.red,.blue], locations: nil)
</code>```

Body:
How can I set the background of a UIButton to a CAGradientLayer?

I have tried the following:

func applyGradient(colors: [UIColor], locations: [NSNumber]?) -> Void {
    let gradient: CAGradientLayer = CAGradientLayer()
    gradient.frame = self.bounds
    gradient.colors = colors.map { $0.cgColor }
    gradient.locations = locations
    self.layer.insertSublayer(gradient, at: 0)
}

which I got from Set Background Gradient on Button in Swift

and then to use it:

let startButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Get Started", for: .normal)
    button.setTitleColor(AppSettings.PURPL_COLOR, for: .normal)
    button.titleLabel?.font = UIFont(name: "Rubik-Medium", size: 16.0)
    return button
}()

startButton.applyGradient(colors: [.red, .blue], locations: nil)

Also, I am setting the width of the button to the view's width and the height to 50.

However, when I run it, this is what I get:

The background gradient is not applied.

Body:
Bounds of the button will be 0 when you call the method applyGradient. So create a UIButton subclass and change the gradient layer frame in layoutSublayers method

class GradientButton: UIButton {
    let gradient: CAGradientLayer = CAGradientLayer()
    internal override init(frame: CGRect) {
        super.init(frame: frame)
    }
    internal required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    required init(_ colors: [UIColor], locations: [NSNumber]?) {
        super.init(frame: .zero)
        applyGradient(colors,locations:locations)
    }
    func applyGradient(_ colors: [UIColor], locations: [NSNumber]?) {
        gradient.colors = colors
        gradient.locations = locations
        gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
        gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
        layer.insertSublayer(gradient, at: 0)
    }
    override func layoutSublayers(of layer: CALayer) {
        super.layoutSublayers(of: layer)
        gradient.frame = self.bounds
    }
}

And create the button with color and location values

let button = GradientButton([.red,.blue], locations: nil)


问:
How to store post id in local storage from Single.php file
The following code in Single.php file is not working as expected. $post->ID and is_user_logged_in()   are getting null values. If all works fine i can have the post id as array in local storage.

```<code><script>
    window.onload = function() {
        var logged_in='<?php echo is_user_logged_in() ?>';
        if (logged_in==false || logged_in==0) {

                var myArray =  JSON.parse(localStorage.getItem('articles') )|| [];
                var article_postid='<?php echo $post->ID ?>';

                //check already read? if not push into array
                index = is_exist.call(myArray, article_postid);
                if(!index){
                    myArray.push(article_postid);
                    localStorage.setItem('articles', JSON.stringify(myArray));
                }
        }
    }
    var is_exist = function(article_postid) {
        // Per spec, the way to identify NaN is that it is not equal to itself
        var findNaN = article_postid !== article_postid;
        var indexOf;
        if(!findNaN && typeof Array.prototype.indexOf === 'function') {
            indexOf = Array.prototype.indexOf;
        } else {
            indexOf = function(article_postid) {
                var i = -1, index = -1;
                for(i = 0; i < this.length; i++) {
                    var item = this[i];
                    if((findNaN && item !== item) || item === article_postid) {
                        index = i;
                        break;
                    }
                }
                return index;
            };
        }
        return indexOf.call(this, article_postid) > -1;
    };
    </script>
</code>```

答:
Please try this code.
Add this code to your activated theme's functions.php file and check.</p>

```<code>function add_js_code_to_footer(){

    if( is_singular( 'post' ) ){
    global $post;
    ?>
        <script>
            window.onload = function() {
                var logged_in='<?php echo is_user_logged_in() ?>';
                if (logged_in==false || logged_in==0) {

                        var myArray =  JSON.parse(localStorage.getItem('articles') )|| [];
                        var article_postid='<?php echo $post->ID ?>';

                        //check already read? if not push into array
                        index = is_exist.call(myArray, article_postid);
                        if(!index){
                            myArray.push(article_postid);
                            localStorage.setItem('articles', JSON.stringify(myArray));
                        }
                }
            }
            var is_exist = function(article_postid) {
                // Per spec, the way to identify NaN is that it is not equal to itself
                var findNaN = article_postid !== article_postid;
                var indexOf;
                if(!findNaN && typeof Array.prototype.indexOf === 'function') {
                    indexOf = Array.prototype.indexOf;
                } else {
                    indexOf = function(article_postid) {
                        var i = -1, index = -1;
                        for(i = 0; i < this.length; i++) {
                            var item = this[i];
                            if((findNaN && item !== item) || item === article_postid) {
                                index = i;
                                break;
                            }
                        }
                        return index;
                    };
                }
                return indexOf.call(this, article_postid) > -1;
            };
        </script>

    <?php
    }

}
add_action("wp_footer","add_js_code_to_footer");
</code>```

Body:
Please try this code.
Add this code to your activated theme's functions.php file and check.

function add_js_code_to_footer(){

    if( is_singular( 'post' ) ){
    global $post;
    ?>
        <script>
            window.onload = function() {
                var logged_in='<?php echo is_user_logged_in() ?>';
                if (logged_in==false || logged_in==0) {

                        var myArray =  JSON.parse(localStorage.getItem('articles') )|| [];
                        var article_postid='<?php echo $post->ID ?>';

                        //check already read? if not push into array
                        index = is_exist.call(myArray, article_postid);
                        if(!index){
                            myArray.push(article_postid);
                            localStorage.setItem('articles', JSON.stringify(myArray));
                        }
                }
            }
            var is_exist = function(article_postid) {
                // Per spec, the way to identify NaN is that it is not equal to itself
                var findNaN = article_postid !== article_postid;
                var indexOf;
                if(!findNaN && typeof Array.prototype.indexOf === 'function') {
                    indexOf = Array.prototype.indexOf;
                } else {
                    indexOf = function(article_postid) {
                        var i = -1, index = -1;
                        for(i = 0; i < this.length; i++) {
                            var item = this[i];
                            if((findNaN && item !== item) || item === article_postid) {
                                index = i;
                                break;
                            }
                        }
                        return index;
                    };
                }
                return indexOf.call(this, article_postid) > -1;
            };
        </script>

    <?php
    }

}
add_action("wp_footer","add_js_code_to_footer");


问:
How to set auto focus in mat-select?
In my angular project have angular material and use mat-select. Mat-select is the first element for my form in my case set auto focus while page was loaded successfully but I wasn't able to set auto focus on mat-select. Anyone can help me to find the way to set auto focus in mat-select.

```<code>@ViewChild("name") nameField: ElementRef;

ngOninit() {
  this.nameField.nativeElement.focus();
}
</code>```

html

```<code><div>
 <mat-select [(ngModel)]="nameField" #name>
    <mat-option *ngFor="let option of options2" [value]="option.id">
      {{ option.name }}
    </mat-option>
 </mat-select>
</div>
</code>```

答:
As this is the First hit that shows up on Google I'll provide what I found:

Note that I did this specifically for a mat-select as there is no real inner html element that the reference could be attached to.

What I found works is getting a reference to the element through view-child and then calling

```<code>reference._elementRef.nativeElement.focus();
</code>```

Hope this helps at least someone :)

Title: How to set auto focus in mat-select?

Body:
In my angular project have angular material and use mat-select. Mat-select is the first element for my form in my case set auto focus while page was loaded successfully but I wasn't able to set auto focus on mat-select. Anyone can help me to find the way to set auto focus in mat-select.

@ViewChild("name") nameField: ElementRef;

ngOninit() {
  this.nameField.nativeElement.focus();
}

html

 <mat-select [(ngModel)]="nameField" #name>
    <mat-option *ngFor="let option of options2" [value]="option.id">
      {{ option.name }}
    </mat-option>
 </mat-select>

Body:
As this is the First hit that shows up on Google I'll provide what I found:

Note that I did this specifically for a mat-select as there is no real inner html element that the reference could be attached to.

What I found works is getting a reference to the element through view-child and then calling

reference._elementRef.nativeElement.focus();

Hope this helps at least someone :)


问:
How to display multiple addresses on a single map
I have a list of Lat and Longs that I would like to display as points/markers on a map.  How do I do this.  I have been able to do one address using geocodingParams option, but can't see how to do it with multiples.  I will have a list of addresses that I would like to geocode and display or I can convert addresses to lat/long and then display.  I'm very new to this as you can tell!
Thanks for any help you may be able to give this newbie.</p>

答: Check out the documentation. There's an example for putting multiple markers on the map: https://developer.here.com/api-explorer/maps-js/v3.0/markers/markers-on-the-map</p>