问:
How to transfer variables from a ts fie to another, angular
I defined a property here in my function

```<code>evs: string
...
openArticle(url){
    this.evs = url
    console.log(this.evs)
    this.navCtrl.navigateForward('/url-page')

  }
</code>```

And I a trying to pass the value of 'this.evs' to another ts file and use its value but I do not know how to do this. I tried exporting it like this.

```<code>export const webpage = this.evs
</code>```

but this.evs has no value until someone performs the openArticle function ad so I keep getting the error. "Cannot read property 'evs' of undefined"

What i need to do is tranfer the variable to the 'url-page' page and use the value of this.evs only after the openArticle function has bee called. How do I go about this?

答:
As per my understanding you are trying to share data between two components.
So choose one of them as per your requirements.

Parent to Child: Sharing Data via Input().

Child to Parent: Sharing Data via Output() and EventEmitter.

Unrelated Components: Sharing Data with a Service.

This link will be helpful.

Body:
I defined a property here in my function

evs: string
...
openArticle(url){
    this.evs = url
    console.log(this.evs)
    this.navCtrl.navigateForward('/url-page')

  }

And I a trying to pass the value of 'this.evs' to another ts file and use its value but I do not know how to do this. I tried exporting it like this.

export const webpage = this.evs

but this.evs has no value until someone performs the openArticle function ad so I keep getting the error. "Cannot read property 'evs' of undefined"

What i need to do is tranfer the variable to the 'url-page' page and use the value of this.evs only after the openArticle function has bee called. How do I go about this?


来源: stackexchange

问:
Clang-Format does not properly allign function arguments
I'm trying to format my code this way :

```<code>int foo(int a,
        int b,
        int c)
{
}
</code>```

However, all my attempts led to this results :

```<code>int foo(int a,
   int b,
   int c)
{
}
</code>```

Here is my clang-format configuration, running on Manjaro :

```<code># Under Visual studio, the plugin https://marketplace.visualstudio.com/items?itemName=LLVMExtensions.ClangFormat makes the use of the clang formatter easier.

Language: Cpp

AccessModifierOffset: -4
AlignAfterOpenBracket: Align #AlwaysBreak
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignConsecutiveMacros: true
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: false
AllowAllConstructorInitializersOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: Always
AllowShortCaseLabelsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Always
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: true

BinPackArguments: true
BinPackParameters: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Allman
BreakBeforeTernaryOperators: false
BreakConstructorInitializers: AfterColon
BreakInheritanceList: AfterColon
BreakStringLiterals: true

ColumnLimit: 120
CompactNamespaces: true
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4

ContinuationIndentWidth: 4
Cpp11BracedListStyle: true

DerivePointerAlignment: false

FixNamespaceComments: true

IndentCaseLabels: false
IndentPPDirectives: BeforeHash
IndentWidth: 4
IndentWrappedFunctionNames: false

KeepEmptyLinesAtTheStartOfBlocks: false

MaxEmptyLinesToKeep: 1

NamespaceIndentation: Inner

PointerAlignment: Middle

ReflowComments: true

SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: false
SpaceBeforeParens: Never
SpaceBeforeRangeBasedForLoopColon: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 4
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false

TabWidth: 4
UseTab: Never

## Penalites: This decides what order things should be done if a line is too long.
## For instance, using the policies specified here:  https://stackoverflow.com/questions/26635370/in-clang-format-what-do-the-penalties-do

PenaltyBreakAssignment: 5
PenaltyBreakBeforeFirstCallParameter: 5
PenaltyBreakComment: 10
PenaltyBreakFirstLessLess: 0
PenaltyBreakString: 10
PenaltyBreakTemplateDeclaration : 30
PenaltyExcessCharacter: 30
PenaltyReturnTypeOnItsOwnLine: 30
</code>```

Does anyone knows how to force this alignement ?

FYI, already tried : Clang-format: Align Function Parameter Names and clang-format: break function parameters

Thanks a lot

Cheers

答:
As I said, I already tried these solutions without success... Setting AlignConsecutiveDeclarations to true generates

```<code>Scene(const std::filesystem::path           scene_directory,
    Object3D *                            parent,
    Magnum::SceneGraph::DrawableGroup3D * group);
</code>```

EDIT 1 : Found out the issue ! It was induced by my IDE for some unknown reasons. Copy pasting into a text editor shows the formatting is correct.. Thanks for the help !

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to format my code this way :

int foo(int a,
        int b,
        int c)
{
}

However, all my attempts led to this results :

int foo(int a,
   int b,
   int c)
{
}

Here is my clang-format configuration, running on Manjaro :

# Under Visual studio, the plugin https://marketplace.visualstudio.com/items?itemName=LLVMExtensions.ClangFormat makes the use of the clang formatter easier.

Language: Cpp

AccessModifierOffset: -4
AlignAfterOpenBracket: Align #AlwaysBreak
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignConsecutiveMacros: true
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: false
AllowAllConstructorInitializersOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: Always
AllowShortCaseLabelsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Always
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: true

BinPackArguments: true
BinPackParameters: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Allman
BreakBeforeTernaryOperators: false
BreakConstructorInitializers: AfterColon
BreakInheritanceList: AfterColon
BreakStringLiterals: true

ColumnLimit: 120
CompactNamespaces: true
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4

ContinuationIndentWidth: 4
Cpp11BracedListStyle: true

DerivePointerAlignment: false

FixNamespaceComments: true

IndentCaseLabels: false
IndentPPDirectives: BeforeHash
IndentWidth: 4
IndentWrappedFunctionNames: false

KeepEmptyLinesAtTheStartOfBlocks: false

MaxEmptyLinesToKeep: 1

NamespaceIndentation: Inner

PointerAlignment: Middle

ReflowComments: true

SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: false
SpaceBeforeParens: Never
SpaceBeforeRangeBasedForLoopColon: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 4
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false

TabWidth: 4
UseTab: Never

## Penalites: This decides what order things should be done if a line is too long.
## For instance, using the policies specified here:  https://stackoverflow.com/questions/26635370/in-clang-format-what-do-the-penalties-do

PenaltyBreakAssignment: 5
PenaltyBreakBeforeFirstCallParameter: 5
PenaltyBreakComment: 10
PenaltyBreakFirstLessLess: 0
PenaltyBreakString: 10
PenaltyBreakTemplateDeclaration : 30
PenaltyExcessCharacter: 30
PenaltyReturnTypeOnItsOwnLine: 30

Does anyone knows how to force this alignement ?

FYI, already tried : Clang-format: Align Function Parameter Names and clang-format: break function parameters

Thanks a lot

Cheers

Body:
As I said, I already tried these solutions without success... Setting AlignConsecutiveDeclarations to true generates

Scene(const std::filesystem::path           scene_directory,
    Object3D *                            parent,
    Magnum::SceneGraph::DrawableGroup3D * group);

EDIT 1 : Found out the issue ! It was induced by my IDE for some unknown reasons. Copy pasting into a text editor shows the formatting is correct.. Thanks for the help !


问:
FIlter an array based an another array string item
I know my question is very simple and so sorry for asking it

I have two arrays for countries and in each of two array there are two object

```<code>array1[0].name = "US"

arrary1[0].code = "1"
</code>```

In this array, all the countries are listes

but in the another array I have a few country.

```<code> array2[0].countryName = "US"

 arrary2[0].countryCode = "1"
</code>```

I want to filter the first array that only shows the country that are in the second array

```<code> let counrtyInfos = array1.filter{ $0.name == array2.first?.countryName}
</code>```

In this code, it's only take the first index value, I don't know how to apply this filter to all of the second array.
Thanks for your help

答:
Try this code:</p>

```<code>let array2Names = array2.compactMap({ $0.name })
let counrtyInfos = array1.filter({ array2Names.contains($0.name) })!
</code>```

Body:
I know my question is very simple and so sorry for asking it

I have two arrays for countries and in each of two array there are two object

array1[0].name = "US"

arrary1[0].code = "1"

In this array, all the countries are listes

but in the another array I have a few country.

 array2[0].countryName = "US"

 arrary2[0].countryCode = "1"

I want to filter the first array that only shows the country that are in the second array

 let counrtyInfos = array1.filter{ $0.name == array2.first?.countryName}

In this code, it's only take the first index value, I don't know how to apply this filter to all of the second array.
Thanks for your help

Body:
Try this code:

let array2Names = array2.compactMap({ $0.name })
let counrtyInfos = array1.filter({ array2Names.contains($0.name) })!


问:
SQL Server date format to Datetimeoffset with specifc format
I have database table that has datetime field in SQL Server.

I have to send as below sample.
Can you please help how to get this dateformat?

Example:  2020-06-10T13:11:00-05:00

Thanks

答:
If you were on a supported version of SQL Server, this is actually quite trivial. If we assume the value in the table is 2020-06-10T13:11:00 it would just need a CONVERT and SWITCHOFFSET:

```<code>SELECT V.Dt,
       SWITCHOFFSET(CONVERT(datetimeoffset(0),V.dt),'-05:00')
FROM (VALUES(CONVERT(datetime2(0),'2020-06-10T13:11:00')))V(Dt);
</code>```

If it's actually a UTC time, and you need to change it to (I assume) Central, then it would be:

```<code>SELECT V.Dt,
       CONVERT(datetimeoffset(0),V.dt) AT TIME ZONE 'Central Standard Time'
FROM (VALUES(CONVERT(datetime2(0),'2020-06-10T18:11:00')))V(Dt);
</code>```

Instead, you're going to have to do some varchar manipulation, as you're using a version  of SQL Server that is completely unsupported:

```<code>--If switching the offset
SELECT V.Dt,
       CONVERT(datetimeoffset(0),CONVERT(varchar(20),V.Dt,126) + '-05:00')
FROM (VALUES(CONVERT(datetime2(0),'2020-06-10T13:11:00')))V(Dt);

--If changing the offset
SELECT V.Dt,
       CONVERT(datetimeoffset(0),CONVERT(varchar(20),DATEADD(HOUR, -5,V.Dt),126) + '-05:00')
FROM (VALUES(CONVERT(datetime2(0),'2020-06-10T18:11:00')))V(Dt);
</code>```

Note that both of these are DST agnositic, as it SWITCHOFFSET. Only AT TIME ZONE will consider the DST.

Body:
If you were on a supported version of SQL Server, this is actually quite trivial. If we assume the value in the table is 2020-06-10T13:11:00 it would just need a CONVERT and SWITCHOFFSET:

SELECT V.Dt,
       SWITCHOFFSET(CONVERT(datetimeoffset(0),V.dt),'-05:00')
FROM (VALUES(CONVERT(datetime2(0),'2020-06-10T13:11:00')))V(Dt);

If it's actually a UTC time, and you need to change it to (I assume) Central, then it would be:

SELECT V.Dt,
       CONVERT(datetimeoffset(0),V.dt) AT TIME ZONE 'Central Standard Time'
FROM (VALUES(CONVERT(datetime2(0),'2020-06-10T18:11:00')))V(Dt);

Instead, you're going to have to do some varchar manipulation, as you're using a version  of SQL Server that is completely unsupported:

--If switching the offset
SELECT V.Dt,
       CONVERT(datetimeoffset(0),CONVERT(varchar(20),V.Dt,126) + '-05:00')
FROM (VALUES(CONVERT(datetime2(0),'2020-06-10T13:11:00')))V(Dt);

--If changing the offset
SELECT V.Dt,
       CONVERT(datetimeoffset(0),CONVERT(varchar(20),DATEADD(HOUR, -5,V.Dt),126) + '-05:00')
FROM (VALUES(CONVERT(datetime2(0),'2020-06-10T18:11:00')))V(Dt);

Note that both of these are DST agnositic, as it SWITCHOFFSET. Only AT TIME ZONE will consider the DST.


答:
I think I figured out a solution -- see below. Basically x, y, and z are 1D arrays while X, Y, and Z are 2D arrays that contour accepts and it worked. I will say I did look around to figure this out..so it wasn't on my own.</p>

```<code>def grid(x, y, z, resX=100, resY=100):
    #prepare to create grid
    xi = np.linspace(min(x), max(x), resX)
    yi = np.linspace(min(y), max(y), resY)

    #grid x, y, z
    X, Y = np.meshgrid(xi, yi)
    Z = griddata((x, y), z, (X, Y), method='linear')
    return X, Y, Z
</code>```

Title: How to convert a scatter plot to a contour plot?

Body:
I would like to convert a scatter plot to a contour plot. How do I go about doing this with the data I have? Here is the code:

import numpy as np
import matplotlib.pyplot as plt
x = np.array([-75.55846, -75.5459 , -75.56686, -75.55276, -75.57951, -75.58955,
   -75.59967, -75.53964, -75.65485, -75.55292, -75.59622, -75.57392,
   -75.47077, -75.58644, -75.68264, -75.56732, -75.59502, -75.37198,
   -75.59585, -75.57081, -75.40989, -75.50928, -75.54841, -75.72734,
   -75.36676, -75.79303, -75.36966, -75.69282, -75.42498, -75.57986,
   -75.58644, -75.64551, -75.45509, -75.47098])
y = np.array([38.07759, 38.07541, 38.06712, 38.09973, 38.06692, 38.09264,
   38.08731, 38.0822 , 38.36981, 38.06027, 38.07962, 38.08531,
   37.93448, 38.07716, 37.71758, 38.08925, 38.0975 , 38.33174,
   38.05731, 38.05515, 38.0547 , 38.1398 , 38.066  , 38.27009,
   37.93415, 38.24889, 38.19691, 38.03272, 38.19954, 37.91286,
   37.97847, 38.29755, 38.01239, 37.93453])
z = np.array([17.526, 21.336, 19.558, 17.78 , 20.828, 20.828, 20.066, 21.082,
   18.542, 20.32 , 19.812, 19.05 , 16.51 , 20.066, 25.654, 16.51 ,
   18.542, 17.018, 20.828, 21.844, 21.59 , 16.764, 20.828, 19.558,
   19.812, 22.606, 25.146, 19.558, 20.574, 24.13 , 35.306, 19.558,
   23.876, 18.796])
fig, ax = plt.subplots(figsize=(8,8))
ax.scatter(x, y, c=z)
plt.show()

Body:
I think I figured out a solution -- see below. Basically x, y, and z are 1D arrays while X, Y, and Z are 2D arrays that contour accepts and it worked. I will say I did look around to figure this out..so it wasn't on my own.

def grid(x, y, z, resX=100, resY=100):
    #prepare to create grid
    xi = np.linspace(min(x), max(x), resX)
    yi = np.linspace(min(y), max(y), resY)

    #grid x, y, z
    X, Y = np.meshgrid(xi, yi)
    Z = griddata((x, y), z, (X, Y), method='linear')
    return X, Y, Z


问:
Print out and make http request only once in a python face recognition script?
First of all, I would like to wish good health to everyone!

I want to create a "party greeter", similar to this one: https://robotzero.one/face-recognition-party-greeter-raspberry-pi/, but using my IP Camera and Ubuntu OS. The intend is to make a web request when a face is recognized. The web request will make echo dot say something using IFTTT.

I am using this script to face recognition: https://github.com/ageitgey/face_recognition/blob/master/examples/facerec_ipcamera_knn.py

I commented the line 210, because I don't need to see the streaming video, and inserted a print function that shows the name of the found person:

```<code>        for name, (top, right, bottom, left) in predictions:
          print("- Found {}".format(name))
</code>```

The problem is that when a face is detected it keeps printing the message in the console. Few seconds of a face showing results in dozens of lines in the console with the same message.

I need somehow to limit this and make it shows the message only once. The http request also should be send only once.

Can anyone help me with this?

答:
Change it to something like this:</p>

```<code>found_name = None
for name, (top, right, bottom, left) in predictions:
    if name == some_condition:
       found_name = name
       break
print("- Found {}".format(found_name))
</code>```

Body:
First of all, I would like to wish good health to everyone!

I want to create a "party greeter", similar to this one: https://robotzero.one/face-recognition-party-greeter-raspberry-pi/, but using my IP Camera and Ubuntu OS. The intend is to make a web request when a face is recognized. The web request will make echo dot say something using IFTTT.

I am using this script to face recognition: https://github.com/ageitgey/face_recognition/blob/master/examples/facerec_ipcamera_knn.py

I commented the line 210, because I don't need to see the streaming video, and inserted a print function that shows the name of the found person:

        for name, (top, right, bottom, left) in predictions:
          print("- Found {}".format(name))

The problem is that when a face is detected it keeps printing the message in the console. Few seconds of a face showing results in dozens of lines in the console with the same message.

I need somehow to limit this and make it shows the message only once. The http request also should be send only once.

Can anyone help me with this?

Body:
Change it to something like this:

found_name = None
for name, (top, right, bottom, left) in predictions:
    if name == some_condition:
       found_name = name
       break
print("- Found {}".format(found_name))


问:
Sitecore: Item display name does not support parenthesis
I changed the display name of an item from Item1 to (This is the new title)

However, in the tree, while the closing ) shows up, the opening appears encoded.
It shows as:

```<code>(This is the new title)
</code>```

How do I fix this please?

答:
This is a known bug, introduced in 9.3 iirc. Reference number 393368. As far as I'm aware, there isn't a patch yet for it, but you can patch it yourself by replacing the faulty pipeline.

Look at Sitecore.Pipelines.Save.Save class in Sitecore.Kernel. In the deep nested Process() method, you'll see this code (reflected with dotPeek):

```<code>if (this.NeedsHtmlTagEncode(field1))
  field1.Value = WebUtil.SafeEncode(field1.Value);
</code>```

The NeedsHtmlTagEncode returns true for DisplayName (for some unknown reason). You can workaround this issue by replacing the Save processor with one that inherits the old one and overrides the protected virtual bool NeedsHtmlTagEncode(SaveArgs.SaveField field) method and just let it return false. Then you just patch out the existing processor with your own one with the xpath /sitecore/processors/saveUI/processor[@type='Sitecore.Pipelines.Save.Save, Sitecore.Kernel'].

Body:
I changed the display name of an item from Item1 to (This is the new title)

However, in the tree, while the closing ) shows up, the opening appears encoded.
It shows as:

(This is the new title)

How do I fix this please?

Body:
This is a known bug, introduced in 9.3 iirc. Reference number 393368. As far as I'm aware, there isn't a patch yet for it, but you can patch it yourself by replacing the faulty pipeline.

Look at Sitecore.Pipelines.Save.Save class in Sitecore.Kernel. In the deep nested Process() method, you'll see this code (reflected with dotPeek):

if (this.NeedsHtmlTagEncode(field1))
  field1.Value = WebUtil.SafeEncode(field1.Value);

The NeedsHtmlTagEncode returns true for DisplayName (for some unknown reason). You can workaround this issue by replacing the Save processor with one that inherits the old one and overrides the protected virtual bool NeedsHtmlTagEncode(SaveArgs.SaveField field) method and just let it return false. Then you just patch out the existing processor with your own one with the xpath /sitecore/processors/saveUI/processor[@type='Sitecore.Pipelines.Save.Save, Sitecore.Kernel'].


问:
Getting the top N values and their coordinates from a 2D Numpy array
I have a 2D numpy array "bigrams" of shape (851, 851) with float values inside. I want to get the top ten values from this array and I want their coordinates.

I know that np.amax(bigrams) can return the single highest value, so that's basically what I want but then for the top ten.

As a numpy-noob, I wrote some code using a loop to get the top values per row and then using np.where() to get the coordinates, but i feel there must be a smarter way to solve this..

答:
You can flatten and use argsort.

```<code>idxs = np.argsort(bigrams.ravel())[-10:]
rows, cols = idxs//851, idxs%851
print(bigrams[rows,cols])
</code>```

An alternative would be to do a partial sorting with argpartition.

```<code>partition = np.argpartition(bigrams.ravel(),-10)[-10:]
max_ten = bigrams[partition//851,partition%851]
</code>```

You will get the top ten values and their coordinates, but they won't be sorted. You can sort this smaller array of ten values later if you want.

Body:
You can flatten and use argsort.

idxs = np.argsort(bigrams.ravel())[-10:]
rows, cols = idxs//851, idxs%851
print(bigrams[rows,cols])

An alternative would be to do a partial sorting with argpartition.

partition = np.argpartition(bigrams.ravel(),-10)[-10:]
max_ten = bigrams[partition//851,partition%851]

You will get the top ten values and their coordinates, but they won't be sorted. You can sort this smaller array of ten values later if you want.


问:
bash: npm: command not found?
I'm learning laravel and follwing this tutorial,

But when I went try and install npm, is says bash: npm: command not found

答: If you already installed npm globally on your system, and you are still getting the above error message by using VSCode terminal. Just close your VSCode application and reopen again, that should resolve the issue.

Title: bash: npm: command not found?


问:
Do interpreters actually pre compile in memory?
Ok guys I thought I'd take my old CS notes and look through compiler theory a little more. I have to say I can't for the life in me remember how all this stuff works but I do have a nice sample application from my college days that helps me understand a few things.

This sample application takes the made up language and compiles it down to an intermediate assembly code like language. There is then a simple VM implementation that takes this intermediate language and executes the statements.

The thing I cant get my head around is, if I this were a straight up interpretor and not a compiler would it still be building up these intermeditary commands in memory to be executed at the end. Or does an interpretor actually "execute" descreet sections of the code chunks at a time?

答:
I have written or worked with interpreters that act directly upon parsing tokens in the input, that act directly on an abstract-syntax tree (AST) built by the parser, and that translate the AST to a form designed for efficient execution.  So the answer is, it depends.

If your target machine has 8K of RAM, a direct-parsing interpreter would be a sensible choice (think FORTH).

If you are using interpreters to teach or learn about the structure and semantics of programming languages, building and interpreting an AST is a good choice.

If you are using an interpreter for portability and you want fast execution, compiling to a register-based virtual machine is a good choice.  (David Gregg and others have shown there is less interpretive overhead in a register-based VM like the Lua VM than in a stack-based VM like the Java VM.)

OwnerDisplayName: Owen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Owen

OwnerDisplayName: Norman Ramsey


问:
How to let a bot post/send a message every 5 minutes or because of another event?
I thought that would be a simple task but somehow i can even mess this up.
So i just want to have my bot send a message (to troll my friends) a specific message every 5 minutes.
So i found this which doesnt work or any other code. I dont even get an error message. So im pretty much clueless, which sucks.

```<code>import discord
import asyncio

client = discord.Client()

async def my_background_task():
    await client.wait_until_ready()
    counter = 0
    channel = discord.Object(id='channel_id_here')
    while not client.is_closed:
        counter += 1
        await client.send_message(channel, counter)
        await asyncio.sleep(60) # task runs every 60 seconds

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

client.loop.create_task(my_background_task())
client.run('token')
</code>```

Anyway here is my boiled down code, without all of the Bot commands.

```<code>import discord
from discord.ext.commands import Bot, has_permissions

import secrets
import numpy as np
import re

TOKEN = 'mytokenasastring'
BOT = Bot(command_prefix='!')
#... some commands for my bot for my friends and myself
BOT.loop.create_task(my_background_task())
BOT.run(TOKEN)
</code>```

So i just added the above code like this

```<code>async def my_background_task():
await BOT.wait_until_ready()
counter = 0
channel = discord.Object(id='mytestchannelidasastring') #i also tried as int but also doenst work
while not BOT.is_closed:
    counter += 1
    await BOT.send_message(channel, counter)
    await asyncio.sleep(60) # task runs every 60 seconds
</code>```

then vs code tells my Bot doenst have a send_message method. so i change the code of the send_message to this

```<code>await channel.send(counter)
</code>```

But now i get the warning/error form VS code that channel doenst have a send method so i get the (real?!) channel like this

```<code>BOT.get_channel(id='mychannelidasstring')
</code>```

and it still doesn't work or i dont get any kind of error message of any kind... pls help or i will go mad....

答:
It looks as though you're using some of the old async's (v0.16.x) docs/tutorials, which can be seen from send_message() and writing IDs as strings. I'd recommend you try to find more recent tutorials and read the recent docs instead.

See here for all the major changes from then into the most recent version, rewrite (v1.x)

As for your code, here is what it should look like:

async def my_background_task():
    await client.wait_until_ready() # ensures cache is loaded
    counter = 0
    channel = client.get_channel(id=112233445566778899) # replace with target channel id
    while not client.is_closed():
        counter += 1
        await channel.send(counter)
        await asyncio.sleep(60) # or 300 if you wish for it to be 5 minutes

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    client.loop.create_task(my_background_task()) # best to put it in here

client.run("token")
```

References:

Rewrite docs

Client.wait_until_ready()

Client.get_channel()

TextChannel.send()

Client.is_closed()

asyncio.sleep()

loop.create_task()

Body:
I thought that would be a simple task but somehow i can even mess this up.
So i just want to have my bot send a message (to troll my friends) a specific message every 5 minutes.
So i found this which doesnt work or any other code. I dont even get an error message. So im pretty much clueless, which sucks.

import discord
import asyncio

client = discord.Client()

async def my_background_task():
    await client.wait_until_ready()
    counter = 0
    channel = discord.Object(id='channel_id_here')
    while not client.is_closed:
        counter += 1
        await client.send_message(channel, counter)
        await asyncio.sleep(60) # task runs every 60 seconds

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

client.loop.create_task(my_background_task())
client.run('token')

Anyway here is my boiled down code, without all of the Bot commands.

import discord
from discord.ext.commands import Bot, has_permissions

import secrets
import numpy as np
import re

TOKEN = 'mytokenasastring'
BOT = Bot(command_prefix='!')
#... some commands for my bot for my friends and myself
BOT.loop.create_task(my_background_task())
BOT.run(TOKEN)

So i just added the above code like this

async def my_background_task():
await BOT.wait_until_ready()
counter = 0
channel = discord.Object(id='mytestchannelidasastring') #i also tried as int but also doenst work
while not BOT.is_closed:
    counter += 1
    await BOT.send_message(channel, counter)
    await asyncio.sleep(60) # task runs every 60 seconds

then vs code tells my Bot doenst have a send_message method. so i change the code of the send_message to this

await channel.send(counter)

But now i get the warning/error form VS code that channel doenst have a send method so i get the (real?!) channel like this

BOT.get_channel(id='mychannelidasstring')

and it still doesn't work or i dont get any kind of error message of any kind... pls help or i will go mad....

Body:
It looks as though you're using some of the old async's (v0.16.x) docs/tutorials, which can be seen from send_message() and writing IDs as strings. I'd recommend you try to find more recent tutorials and read the recent docs instead.

See here for all the major changes from then into the most recent version, rewrite (v1.x)

As for your code, here is what it should look like:

async def my_background_task():
    await client.wait_until_ready() # ensures cache is loaded
    counter = 0
    channel = client.get_channel(id=112233445566778899) # replace with target channel id
    while not client.is_closed():
        counter += 1
        await channel.send(counter)
        await asyncio.sleep(60) # or 300 if you wish for it to be 5 minutes

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    client.loop.create_task(my_background_task()) # best to put it in here

client.run("token")

References:

Rewrite docs

Client.wait_until_ready()

Client.get_channel()

TextChannel.send()

Client.is_closed()

asyncio.sleep()

loop.create_task()


问:
How can I combine multiple scroll event listeners into one?
I have the following function that zooms out on images after they enter the viewport. Right now it's attaching as many event listeners as there are elements. For performance reasons I'd like to combine these into one event listener for all elements, but I don't know how. Here is my code:

HTML

```<code><div class="image-wrapper">
    <div class="image-container elem-1">
        <div class="zoom-images">
            <img class="zoom" src="test" alt="test">
        </div>
    </div>
    <div class="image-container elem-2">
        <div class="zoom-images">
            <img class="zoom" src="test" alt="test">
        </div>
    </div>
    <div class="image-container elem-3">
        <div class="zoom-images">
            <img class="zoom" src="test" alt="test">
        </div>
    </div>
</div>
</code>```

JAVASCRIPT

```<code>$('.zoom').each(function() {
    var el = $(this);
    var inViewport = false;
    var isZooming = false;
    originY = 0;
    window.addEventListener('scroll', throttle(zoomImage, 250), {passive: true});
    function zoomImage() {
        originY = $(window).scrollTop();
        if (el.isInViewport()) {
            if (!inViewport) {
                inViewport = true;
            }
        } else {
            if (inViewport) {
                inViewport = false;
            }
        }
        if (inViewport) {
            if (!isZooming) {
                window.requestAnimationFrame(function () {
                    el.addClass('is-zooming');
                });
                isZooming = true;
            }
        } else {
            if (isZooming) {
                window.requestAnimationFrame(function () {
                    el.removeClass('is-zooming');
                });
                isZooming = false;
            }
        }
    };
    $.fn.isInViewport = function() {
        var elementTop = $(this).offset().top;
        var elementBottom = elementTop + $(this).outerHeight();
        var viewportTop = $(window).scrollTop();
        var viewportBottom = viewportTop + $(window).height();
        return elementBottom > viewportTop && elementTop < viewportBottom;
    };
});
</code>```

Any help would be greatly appreciated! Thanks a lot!

答:
I found the solution. For anyone who is interested, I solved it like this:</p>

```<code>window.addEventListener('scroll', throttle(check_if_in_view, 220), {
    capture: true,
    passive: true
});
var $animation_elements = $('.zoom-images');
var $window = $(window);
function check_if_in_view() {
    var window_height = $window.height();
    var window_top_position = $window.scrollTop();
    var window_bottom_position = (window_top_position + window_height);
    $.each($animation_elements, function() {
        var $element = $(this);
        var $zoom = $(this).children('img.zoom');
        var element_height = $element.outerHeight();
        var element_top_position = $element.offset().top;
        var element_bottom_position = (element_top_position + element_height);
        if ((element_bottom_position >= window_top_position) &&
            (element_top_position <= window_bottom_position)) {
            requestAnimationFrame( function() {
                $zoom.addClass('is-zooming');
            });
        } else {
            requestAnimationFrame( function() {
                $zoom.removeClass('is-zooming');
            });
        }
    });
};
</code>```

Body:
I have the following function that zooms out on images after they enter the viewport. Right now it's attaching as many event listeners as there are elements. For performance reasons I'd like to combine these into one event listener for all elements, but I don't know how. Here is my code:

HTML

JAVASCRIPT

$('.zoom').each(function() {
    var el = $(this);
    var inViewport = false;
    var isZooming = false;
    originY = 0;
    window.addEventListener('scroll', throttle(zoomImage, 250), {passive: true});
    function zoomImage() {
        originY = $(window).scrollTop();
        if (el.isInViewport()) {
            if (!inViewport) {
                inViewport = true;
            }
        } else {
            if (inViewport) {
                inViewport = false;
            }
        }
        if (inViewport) {
            if (!isZooming) {
                window.requestAnimationFrame(function () {
                    el.addClass('is-zooming');
                });
                isZooming = true;
            }
        } else {
            if (isZooming) {
                window.requestAnimationFrame(function () {
                    el.removeClass('is-zooming');
                });
                isZooming = false;
            }
        }
    };
    $.fn.isInViewport = function() {
        var elementTop = $(this).offset().top;
        var elementBottom = elementTop + $(this).outerHeight();
        var viewportTop = $(window).scrollTop();
        var viewportBottom = viewportTop + $(window).height();
        return elementBottom > viewportTop && elementTop < viewportBottom;
    };
});

Any help would be greatly appreciated! Thanks a lot!

Body:
I found the solution. For anyone who is interested, I solved it like this:

window.addEventListener('scroll', throttle(check_if_in_view, 220), {
    capture: true,
    passive: true
});
var $animation_elements = $('.zoom-images');
var $window = $(window);
function check_if_in_view() {
    var window_height = $window.height();
    var window_top_position = $window.scrollTop();
    var window_bottom_position = (window_top_position + window_height);
    $.each($animation_elements, function() {
        var $element = $(this);
        var $zoom = $(this).children('img.zoom');
        var element_height = $element.outerHeight();
        var element_top_position = $element.offset().top;
        var element_bottom_position = (element_top_position + element_height);
        if ((element_bottom_position >= window_top_position) &&
            (element_top_position <= window_bottom_position)) {
            requestAnimationFrame( function() {
                $zoom.addClass('is-zooming');
            });
        } else {
            requestAnimationFrame( function() {
                $zoom.removeClass('is-zooming');
            });
        }
    });
};


问:
How To Send an email from Jenkins to the email of the developer who made the changes on the repo(i.e committing or pushing)?
So my goal is to have Jenkins send an email to developer who was involved with any code changes in the repo in Mercurial. I have set up my hooks on Mercurial and now whenever I do any sort of changes on the repo a build executes on Jenkins which builds without any issue. The problem now is its only sending it to the email that I have configured in Jenkins and not the email of the developer who made the changes. On Mercurial I made sure to make the user the email I primarily use. I was pretty sure the code below would be able to access the email of the developer who made the changes:

```<code>pipeline {
   agent any

   stages {
      stage('Hello') {
         steps {
            echo 'Hello World'
         }
      }
   }

   post {
    always {
    emailext body: 'A Test EMail', recipientProviders: [[$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider']], subject: 'Test'
    }
}
}
</code>```

Given that it hasnt I am suspecting that Jenkins is not aware of the email of the developer who made the changes. How do I tell Jenkins about the email of the developer who made the changes? I also made sure to install all of the email plugins for Jenkins btw but still no luck.

答:
Add Build Step and select execute windows batch command

Get the log of recent commit and select username from the result
"hg log --limit 1"

Configure this email in Email Extension Plugin

Body:
So my goal is to have Jenkins send an email to developer who was involved with any code changes in the repo in Mercurial. I have set up my hooks on Mercurial and now whenever I do any sort of changes on the repo a build executes on Jenkins which builds without any issue. The problem now is its only sending it to the email that I have configured in Jenkins and not the email of the developer who made the changes. On Mercurial I made sure to make the user the email I primarily use. I was pretty sure the code below would be able to access the email of the developer who made the changes:

pipeline {
   agent any

   stages {
      stage('Hello') {
         steps {
            echo 'Hello World'
         }
      }
   }

   post {
    always {
    emailext body: 'A Test EMail', recipientProviders: [[$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider']], subject: 'Test'
    }
}
}

Given that it hasnt I am suspecting that Jenkins is not aware of the email of the developer who made the changes. How do I tell Jenkins about the email of the developer who made the changes? I also made sure to install all of the email plugins for Jenkins btw but still no luck.


问:
Ansible: Run modules on a target host in a virtual enviroment
I want to run the os_server module on a target host which has a virtual enviroment where openstacksdk is installed. If I try to run the script as shown below it results in a error "conflicting action statements: virtualenv, os_server". How can I specify a virtual enviroment correctly so that ansible uses it? I don't want to install openstacksdk globally and just use the venv.</p>

```<code>- name: Create Server
  virtualenv: "/home/user/otc2/bin/activate"
  os_server:
    state: present
    auto_ip: false
    ...
</code>```

答: You would set the ansible_python_interpreter hostvar for that host to point to the python binary inside the virtualenv on the remote machine, which appears to be /home/user/otc2/bin/python based on your posted snippet

Body:
I want to run the os_server module on a target host which has a virtual enviroment where openstacksdk is installed. If I try to run the script as shown below it results in a error "conflicting action statements: virtualenv, os_server". How can I specify a virtual enviroment correctly so that ansible uses it? I don't want to install openstacksdk globally and just use the venv.

- name: Create Server
  virtualenv: "/home/user/otc2/bin/activate"
  os_server:
    state: present
    auto_ip: false
    ...


问:
How can this MYSQL query be better
I have a table that has all the photos from a user. For some reason (dont care why) some users can be deleted (using DELETE FROM) from the users table, but the photos are kept on the photos tables.

I need to know how many photos are from users that actually exists on the users table.

The first solution I came up with is this:

```<code>SELECT COUNT(DISTINCT user_id) FROM photos WHERE user_id IN (SELECT id FROM users)
</code>```

But I'm not sure if doing two Queries is the best one. Is there a better way to do this?

答:
The best way to do this would be to use a foriegn key constraint between the two tables, and implement cascading deletes.  More info available in the MySQL manual:

http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

As commenters have pointed out, this requires the use of the InnoDB storage engine.  This is the default storage engine as of MySQL 5.5.5.

ContentLicense: CC BY-SA 3.0

Title: How can this MYSQL query be better

Body:
I have a table that has all the photos from a user. For some reason (dont care why) some users can be deleted (using DELETE FROM) from the users table, but the photos are kept on the photos tables.

I need to know how many photos are from users that actually exists on the users table.

The first solution I came up with is this:

SELECT COUNT(DISTINCT user_id) FROM photos WHERE user_id IN (SELECT id FROM users)

But I'm not sure if doing two Queries is the best one. Is there a better way to do this?


问:
Form $ref is undefined inside of method?
I have a very simple Vuetify form with ref="form". When I press submit, I want to validate and programmatically submit the form, however for some reason this.$refs.form returns undefined.

I'm almost hoping it's something dumb like a typo because this is so seemingly simple!

<template>
  <v-form
    v-if="!submitted"
    ref="form"
    v-model="valid"
    name="contactForm"
    data-netlify="true"
    data-netlify-honeypot="bot-field"
    method="POST"
    @submit.prevent="submit">
    <input
      type="hidden"
      name="form-name"
      value="contactForm">

    ...input fields

    <v-row justify="center">
      <v-col
        sm="12"
        class="text-center">
        <v-btn
          :disabled="!valid || sendingForm"
          color="accent"
          depressed
          :ripple="false"
          x-large
          type="submit">
          {{ sendingForm ? 'Loading...' : 'Submit' }}
        </v-btn>
      </v-col>
    </v-row>

      Don't fill this out:
      <input
        type="text"
        name="bot-field">

  </v-form>
</template>

```

I have tried removing the v-if on the form, removing the type="submit/adding @click="submit on the button, removing @submit.prevent="submit from the form... nothing seems to be working! Has anybody run into something like this? Thanks!

答:
I ended up going a slightly different route to solve this. I relied on the Vuetify form docs as well as a Netlify article about integrating forms with Vue.

```<code>  <template>
    <v-form
      v-if="!submitted"
      ref="form"
      v-model="valid"
      name="contactForm"
      data-netlify="true"
      data-netlify-honeypot="bot-field"
      method="POST"
      @submit.prevent="submit">
      <input
        type="hidden"
        name="form-name"
        value="contactForm">
      <v-row>
        <v-col
          cols="12"
          md="6">
          <v-text-field
            v-model="form.firstName"
            color="primary"
            label="First Name *"
            outlined
            :rules="nameRules"
            required />
        </v-col>
        <v-col
          cols="12"
          md="6">
          <v-text-field
            v-model="form.lastName"
            color="primary"
            label="Last Name *"
            outlined
            :rules="nameRules"
            required />
        </v-col>
      </v-row>
      <v-row>
        <v-col cols="12">
          <v-text-field
            v-model="form.email"
            color="primary"
            label="Email *"
            type="email"
            :rules="emailRules"
            outlined
            required />
        </v-col>
      </v-row>
      <v-row justify="center">
        <v-col cols="12">
          <v-textarea
            v-model="form.message"
            color="primary"
            label="Message *"
            outlined
            :rules="nameRules"
            required />
        </v-col>
        <v-col
          sm="12"
          class="text-center">
          <v-btn
            :disabled="!valid || sendingForm"
            color="accent"
            depressed
            :ripple="false"
            x-large
            type="submit">
            {{ sendingForm ? 'Loading...' : 'Submit' }}
          </v-btn>
        </v-col>
      </v-row>
      <p class="d-none">
        <label for="bot-field">Don't fill this out: </label>
        <input
          type="text"
          name="bot-field">
      </p>
    </v-form>
  </template>

  <script>
    import axios from 'axios';

    export default {
      data: () => ({
        ...other stuff,
        emailRules: [
           v => !!v || 'E-mail is required',
           v => /.+@.+\..+/.test(v) || 'E-mail must be valid',
        ],
        form: {
          email: '',
          firstName: '',
          lastName: '',
          message: '',
        },
        nameRules: [
          v => !!v || 'Name is required.',
        ],
      }),

      methods: {
        encode (data) {
          return Object.keys(data)
           .map(
             key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`
           )
          .join("&");
        },
        submit () {
          this.sendingForm = true;

          const axiosConfig = {
            header: { 'Content-Type': 'application/x-www-form-urlencoded' }
          };

          axios
            .post(
              '/',
              this.encode({
                'form-name': 'contactForm',
                ...this.form
              }),
              axiosConfig
            )
            .then(() => this.submitted = true)
            .catch(err => console.log(err))
            .finally(() => this.sendingForm = false);
          }
       }
  </script>
</code>```

Because validation is handled with required and :rules, I don't need to manually validate it in the submit function. And because it's tied to Netlify Forms, I have to run an axios POST with encoded form fields.

FWIW, I realized that when console logging this.$refs, then form appears to be undefined. However, if I console log this.$refs.form, then it gives me the ref as expected.

Body:
I have a very simple Vuetify form with ref="form". When I press submit, I want to validate and programmatically submit the form, however for some reason this.$refs.form returns undefined.

I'm almost hoping it's something dumb like a typo because this is so seemingly simple!

<template>
  <v-form
    v-if="!submitted"
    ref="form"
    v-model="valid"
    name="contactForm"
    data-netlify="true"
    data-netlify-honeypot="bot-field"
    method="POST"
    @submit.prevent="submit">
    <input
      type="hidden"
      name="form-name"
      value="contactForm">

    ...input fields

    <v-row justify="center">
      <v-col
        sm="12"
        class="text-center">
        <v-btn
          :disabled="!valid || sendingForm"
          color="accent"
          depressed
          :ripple="false"
          x-large
          type="submit">
          {{ sendingForm ? 'Loading...' : 'Submit' }}
        </v-btn>
      </v-col>
    </v-row>

      Don't fill this out:
      <input
        type="text"
        name="bot-field">

  </v-form>
</template>

I have tried removing the v-if on the form, removing the type="submit/adding @click="submit on the button, removing @submit.prevent="submit from the form... nothing seems to be working! Has anybody run into something like this? Thanks!

Body:
I ended up going a slightly different route to solve this. I relied on the Vuetify form docs as well as a Netlify article about integrating forms with Vue.

  <template>
    <v-form
      v-if="!submitted"
      ref="form"
      v-model="valid"
      name="contactForm"
      data-netlify="true"
      data-netlify-honeypot="bot-field"
      method="POST"
      @submit.prevent="submit">
      <input
        type="hidden"
        name="form-name"
        value="contactForm">
      <v-row>
        <v-col
          cols="12"
          md="6">
          <v-text-field
            v-model="form.firstName"
            color="primary"
            label="First Name *"
            outlined
            :rules="nameRules"
            required />
        </v-col>
        <v-col
          cols="12"
          md="6">
          <v-text-field
            v-model="form.lastName"
            color="primary"
            label="Last Name *"
            outlined
            :rules="nameRules"
            required />
        </v-col>
      </v-row>
      <v-row>
        <v-col cols="12">
          <v-text-field
            v-model="form.email"
            color="primary"
            label="Email *"
            type="email"
            :rules="emailRules"
            outlined
            required />
        </v-col>
      </v-row>
      <v-row justify="center">
        <v-col cols="12">
          <v-textarea
            v-model="form.message"
            color="primary"
            label="Message *"
            outlined
            :rules="nameRules"
            required />
        </v-col>
        <v-col
          sm="12"
          class="text-center">
          <v-btn
            :disabled="!valid || sendingForm"
            color="accent"
            depressed
            :ripple="false"
            x-large
            type="submit">
            {{ sendingForm ? 'Loading...' : 'Submit' }}
          </v-btn>
        </v-col>
      </v-row>
      <p class="d-none">
        <label for="bot-field">Don't fill this out: </label>
        <input
          type="text"
          name="bot-field">
      </p>
    </v-form>
  </template>

  <script>
    import axios from 'axios';

    export default {
      data: () => ({
        ...other stuff,
        emailRules: [
           v => !!v || 'E-mail is required',
           v => /.+@.+\..+/.test(v) || 'E-mail must be valid',
        ],
        form: {
          email: '',
          firstName: '',
          lastName: '',
          message: '',
        },
        nameRules: [
          v => !!v || 'Name is required.',
        ],
      }),

      methods: {
        encode (data) {
          return Object.keys(data)
           .map(
             key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`
           )
          .join("&");
        },
        submit () {
          this.sendingForm = true;

          const axiosConfig = {
            header: { 'Content-Type': 'application/x-www-form-urlencoded' }
          };

          axios
            .post(
              '/',
              this.encode({
                'form-name': 'contactForm',
                ...this.form
              }),
              axiosConfig
            )
            .then(() => this.submitted = true)
            .catch(err => console.log(err))
            .finally(() => this.sendingForm = false);
          }
       }
  </script>

Because validation is handled with required and :rules, I don't need to manually validate it in the submit function. And because it's tied to Netlify Forms, I have to run an axios POST with encoded form fields.

FWIW, I realized that when console logging this.$refs, then form appears to be undefined. However, if I console log this.$refs.form, then it gives me the ref as expected.


问:
Init message from the bot in aiml
I'm programming a bot in aiml using programAB and I wonder if there is anyway to make the bot start the conversation,like 'Hello, how are you?', not just waiting for the human to say anything. </p>

答: You can send a message to the bot first in the code then take the answer of the bot show it and start the chat.  </p>

Title: Init message from the bot in aiml


问:
how xdp ebpf change checksum tcphdr after update dest port
how xdp ebpf change checksum tcphdr after update dest port ?

// Check tcp header size
struct tcphdr *tcph = data + nh_off;
nh_off += sizeof(struct tcphdr);
if (data + nh_off > data_end) {
    return XDP_PASS;
}
tcph->dest = bpf_ntohs(5555);
// ... i'm trying change checksum of tcphdr, it's not work for me.
tcph->check = 0;
tcph->check = checksum((unsigned short *)tcph, sizeof(struct tcphdr));

return XDP_TX;
```

<p>this is the function code with which i am trying to change the checksum of a tcp packet</p>

<pre class="lang-c prettyprint-override"><code>static inline unsigned short checksum(unsigned short *buf, int bufsz) {
    unsigned long sum = 0;

    while (bufsz > 1) {
        sum += *buf;
        buf++;
        bufsz -= 2;
    }

    if (bufsz == 1) {
        sum += *(unsigned char *)buf;
    }

    sum = (sum & 0xffff) + (sum >> 16);
    sum = (sum & 0xffff) + (sum >> 16);

    return ~sum;
}
</code>```

I load an xdp program for the lo interface, and I want to proxy the packet to port 5555 in the same network interface.

答:
maybe I didn’t figure it out, but from the example you proposed, I only change the property of the structure I need and recount the ipv4 packet checksum:

```<code>    __u16 new_port = bpf_ntohs(5555);
    __u32 csum = 0;
    update_header_field(&tcph->check, &tcph->dest, &new_port);
    /* Update IPv4 header checksum */
    iph->check = 0;
    __u16 *p_iph_16 = (__u16 *)iph;
    #pragma clang loop unroll(full)
    for (int i = 0; i < (int)sizeof(*iph) >> 1; i++)
        csum += *p_iph_16++;
    iph->check = ~((csum & 0xffff) + (csum >> 16));

    return XDP_TX;
</code>```

but the result is the same, the request does not get to the server running on port 5555.

Body:
how xdp ebpf change checksum tcphdr after update dest port ?

// Check tcp header size
struct tcphdr *tcph = data + nh_off;
nh_off += sizeof(struct tcphdr);
if (data + nh_off > data_end) {
    return XDP_PASS;
}
tcph->dest = bpf_ntohs(5555);
// ... i'm trying change checksum of tcphdr, it's not work for me.
tcph->check = 0;
tcph->check = checksum((unsigned short *)tcph, sizeof(struct tcphdr));

return XDP_TX;

this is the function code with which i am trying to change the checksum of a tcp packet

static inline unsigned short checksum(unsigned short *buf, int bufsz) {
    unsigned long sum = 0;

    while (bufsz > 1) {
        sum += *buf;
        buf++;
        bufsz -= 2;
    }

    if (bufsz == 1) {
        sum += *(unsigned char *)buf;
    }

    sum = (sum & 0xffff) + (sum >> 16);
    sum = (sum & 0xffff) + (sum >> 16);

    return ~sum;
}

I load an xdp program for the lo interface, and I want to proxy the packet to port 5555 in the same network interface.

Body:
maybe I didn’t figure it out, but from the example you proposed, I only change the property of the structure I need and recount the ipv4 packet checksum:

    __u16 new_port = bpf_ntohs(5555);
    __u32 csum = 0;
    update_header_field(&tcph->check, &tcph->dest, &new_port);
    /* Update IPv4 header checksum */
    iph->check = 0;
    __u16 *p_iph_16 = (__u16 *)iph;
    #pragma clang loop unroll(full)
    for (int i = 0; i < (int)sizeof(*iph) >> 1; i++)
        csum += *p_iph_16++;
    iph->check = ~((csum & 0xffff) + (csum >> 16));

    return XDP_TX;

but the result is the same, the request does not get to the server running on port 5555.


答:
Try using discord.tasks.loop.

from discord.ext import tasks

counter = 0

@tasks.loop(minutes=1.0, count=None)
async def my_background_task():
    global counter
    channel = BOT.get_channel(123456789) # channel id as an int
    counter += 1
    await channel.send(f'{counter}')
my_background_task.start()
```

to loop your troll function every minute.

Title: How to let a bot post/send a message every 5 minutes or because of another event?

Body:
Try using discord.tasks.loop.

from discord.ext import tasks

counter = 0

@tasks.loop(minutes=1.0, count=None)
async def my_background_task():
    global counter
    channel = BOT.get_channel(123456789) # channel id as an int
    counter += 1
    await channel.send(f'{counter}')
my_background_task.start()

to loop your troll function every minute.


问:
Upload an attachment to azure devops [REST API]
I'm having a hard time adding a attachments in my azure devops repo via api...

```<code>public static void putAttachments(Integer id) {
        try {
            URL url = new URL(
                    "https://dev.azure.com/marcoparra0034/AgileFr/_apis/wit/attachments?api-version=5.1&fileName=imageAs.png");
            HttpURLConnection con = ResApiMain.apiConnectionAttachments(PAT, url);
            File file = new File("C:\\Users\\marco.parra\\Pictures\\Screenshots\\new.png");
            String base64Image = encodeFileToBase64Binary(file);

//                  String jsonInputString = "[{\"op\":\"add\",\"path\":\"/fields/System.Title\",\"value\":\"" + "tpain"
//                          + "\"}]";
            base64Image = "[" + base64Image + "]";
            System.out.println("Base xs" + base64Image);

            try (OutputStream os = con.getOutputStream()) {
                byte[] input = Base64.decodeBase64(base64Image.getBytes("utf-8"));
                System.out.println(new String(input));
                os.write(input, 0, input.length);
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }

            try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println(response.toString());
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
            con.disconnect();
        } catch (Exception ex) {

        }
</code>```

This is the connection method

```<code>public static HttpURLConnection apiConnectionAttachments(String PAT, URL url) {
        HttpURLConnection con = null;
        try {
            String AuthStr = ":" + PAT;
            Base64 base64 = new Base64();

            String encodedPAT = new String(base64.encode(AuthStr.getBytes()));
            con = (HttpURLConnection) url.openConnection();
            con.setRequestProperty("Authorization", "Basic " + encodedPAT);
            con.setDoOutput(true);
            System.out.println("URL - " + url.toString());
            System.out.println("PAT - " + encodedPAT);

            // Image Requierements
//          con.setRequestProperty("Content-Type", "image/jpeg");
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("X-HTTP-Method-Override", "PATCH");
            con.setRequestMethod("POST");

            con.setRequestProperty("Content-Type", "application/octet-stream");
//      con.setRequestProperty("Accept", "application/json");

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return con;
    }
</code>```

When i run this it show the next error code

```<code>Server returned HTTP response code: 405 for URL: https://dev.azure.com/marcoparra0034/AgileFr/_apis/wit/attachments?api-version=5.1&fileName=imageAs.png
</code>```

Update i see how to work with python and c# but i can´t follow this logic to create an attachment

https://github.com/Microsoft/azure-devops-python-api/blob/1bacd2a3f0128a6d184cf75e2c6f8859d46f270a/vsts/vsts/work_item_tracking/v4_1/work_item_tracking_client.py#L56

Expectations Example

```<code>{
  "id": "a5cedde4-2dd5-4fcf-befe-fd0977dd3433",
  "url": "https://dev.azure.com/fabrikam/_apis/wit/attachments/a5cedde4-2dd5-4fcf-befe-fd0977dd3433?fileName=imageAsFileAttachment.png"
}
</code>```

https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/attachments/create?view=azure-devops-rest-5.1

Any help would be appreciated....

答: I solve this issue commenting line con.setRequestProperty("X-HTTP-Method-Override", "PATCH"); </p>

Body:
I'm having a hard time adding a attachments in my azure devops repo via api...

public static void putAttachments(Integer id) {
        try {
            URL url = new URL(
                    "https://dev.azure.com/marcoparra0034/AgileFr/_apis/wit/attachments?api-version=5.1&fileName=imageAs.png");
            HttpURLConnection con = ResApiMain.apiConnectionAttachments(PAT, url);
            File file = new File("C:\\Users\\marco.parra\\Pictures\\Screenshots\\new.png");
            String base64Image = encodeFileToBase64Binary(file);

//                  String jsonInputString = "[{\"op\":\"add\",\"path\":\"/fields/System.Title\",\"value\":\"" + "tpain"
//                          + "\"}]";
            base64Image = "[" + base64Image + "]";
            System.out.println("Base xs" + base64Image);

            try (OutputStream os = con.getOutputStream()) {
                byte[] input = Base64.decodeBase64(base64Image.getBytes("utf-8"));
                System.out.println(new String(input));
                os.write(input, 0, input.length);
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }

            try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println(response.toString());
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
            con.disconnect();
        } catch (Exception ex) {

        }

This is the connection method

public static HttpURLConnection apiConnectionAttachments(String PAT, URL url) {
        HttpURLConnection con = null;
        try {
            String AuthStr = ":" + PAT;
            Base64 base64 = new Base64();

            String encodedPAT = new String(base64.encode(AuthStr.getBytes()));
            con = (HttpURLConnection) url.openConnection();
            con.setRequestProperty("Authorization", "Basic " + encodedPAT);
            con.setDoOutput(true);
            System.out.println("URL - " + url.toString());
            System.out.println("PAT - " + encodedPAT);

            // Image Requierements
//          con.setRequestProperty("Content-Type", "image/jpeg");
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("X-HTTP-Method-Override", "PATCH");
            con.setRequestMethod("POST");

            con.setRequestProperty("Content-Type", "application/octet-stream");
//      con.setRequestProperty("Accept", "application/json");

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return con;
    }

When i run this it show the next error code

Server returned HTTP response code: 405 for URL: https://dev.azure.com/marcoparra0034/AgileFr/_apis/wit/attachments?api-version=5.1&fileName=imageAs.png

Update i see how to work with python and c# but i can´t follow this logic to create an attachment

https://github.com/Microsoft/azure-devops-python-api/blob/1bacd2a3f0128a6d184cf75e2c6f8859d46f270a/vsts/vsts/work_item_tracking/v4_1/work_item_tracking_client.py#L56

Expectations Example

{
  "id": "a5cedde4-2dd5-4fcf-befe-fd0977dd3433",
  "url": "https://dev.azure.com/fabrikam/_apis/wit/attachments/a5cedde4-2dd5-4fcf-befe-fd0977dd3433?fileName=imageAsFileAttachment.png"
}

https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/attachments/create?view=azure-devops-rest-5.1

Any help would be appreciated....


问:
TIdHTTPServer file upload
I'm trying to upload files to a Indy(ver. 10.5.5) TIdHTTPServer.

I've been searching for solutions but no luck thus far, what I've found was for older versions of Indy which were not compatible with the version shipped with Delphi 2010.

What I'm hoping is to achieve simply upload a file using "multipart/form-data" to the server and decode it, simple as that, any help is appreciated.

答:
I started xxm as a way to build websites with Delphi, and have scripts with both HTML and Pascal code re-compile with a press of the browser's refresh button after changes made.

It uses a generic interface that 'plugs into' IIS, Apache, Internet Explorer, FireFox, and there's a stand-alone HTTP exe also. The interface exposes IxxmParameterPostFile on a parameter when a file is uploaded.

See demo 4 Upload for an example.

Title: TIdHTTPServer file upload


问:
How to delete and recreate from scratch an existing EF Code First database
I am using EF Code First with EF 5 in VS 2012. I use PM update-database command and I have a simple seed method to fill some tables with sample data.

I would like to delete and recreate my x.mdb. The update history seems to be out of sync. If I comment out all my DBSets in my context, update-database runs with no error but leaves some tables in the DB. As I have no valuable data in the DB it seems to the simplest to reset the all thing.

How can I accomplish this?

答:
Since this question is gonna be clicked some day by new EF Core users and I find the top answers somewhat unnecessarily destructive, I will show you a way to start "fresh". Beware, this deletes all of your data.

Delete all tables on your MS SQL server. Also delete the __EFMigrations table.

Type dotnet ef database update

EF Core will now recreate the database from zero up until your latest migration.


问:
How to change the color of one Details Label in power bi Donut chart
See this image for reference:

I am trying to show the Unmatched set's details label['12316 (31.4%)'] in RED Color instead of black color(highlighted in yellow in the attached pic for ref).

Note - I have checked Format under visualizations and when I change the color in details label, both sets are changing.

How to do that without affecting Matched set['26901 (68.6%)'] in the same donut chart.

Attached the working area pic for ref.

答:
Searched in many places and discussed with persons who worked a lot in power bi stuffs. At this point of time, there is no option to edit particular details label alone in Donut Chart.

This is at idea/feedback level alone. May be , hopes Power Bi will implement this in nearby future.

If you also want this in power bi, let the power bi community to know this things and give your votes at power bi site's feedback - https://ideas.powerbi.com/forums/265200-power-bi-ideas/suggestions/40505656-conditional-formatting-donut-charts


问:
How to permanently disable foreign key check
I have to cooperate with an old school programmer. A long time ago he set up MySQL database. When he created it, he used his primary language as a language for naming tables, columns etc.

Now I would like to have a relation graph for this database and I need it for Prisma to figure out relations between tables, thus I would like to add foreign keys, but I cannot add them easily as he does violate them.

I suppose the easiest thing to do would be to disable foreign key check SET foreign_key_checks = 0;, but this only ever lasts session. Is there a way around this?

Can I do something SET foreign_key_checks = 0;, but for every connected user, and ideal after DB restart too?

答:
https://dev.mysql.com/doc/refman/8.0/en/set-variable.html

Sets it only current session, even same user upon next reconnect won't have this setting.

SET [SESSION] key = value (SESSION is default and thus optional)

Sets it to all users, till next restart of MySQL server happens.

SET GLOBAL key = value

Same as global, but will also apply after restart. This will, in fact, change the config file of the MySQL server.

SET PERSIST key = value (PERSIST is only available since v8)

There is also PERSIST_ONLY which will apply the effect only after a restart.


问:
How to load json file data to existing couchbase bucket through command line or manually?
As i have created a data file in JSON format and I want to know how to load that JSON file to existing Couchbase Server bucket through command line or manually?</p>

答:
To add it manually, you can simply copy and paste the contents into the UI.

Go to Buckets -> click "Documents" next to the bucket you want -> click "Add Document" on the top right.

First, enter whatever key you want. Next, paste the JSON contents.


问:
How to identify 2 specific variables in a pandas column and perform caps on the 2nd letter of the variables only
I have a column of data in a pandas dataframe and I wanted to only capitalize the 2nd letters for 2 of the variables in the column. E.g. I only want to capitalize "Et Appeal" to "ET Appeal" and "Ip Application" to "IP Application" while leaving the rest of the variables unchanged.

How do I iterate over each row in that specific column and variables and thereafter return the dataframe with the capitalization?

I have defined a function as follows:

```<code>def capitalize_nth(s):
    return s[0] + s[1].capitalize() + s[2:]
</code>```

Column Data in pandas dataframe

答:
This is a bit hacky but works for what you need:

>>> s = pd.Series(['Ip Application', 'Et Appeal', 'Enquiry on situation', 'Stolen', 'Waiver for goods'])
>>> [x[0] + x[1].upper() + x[2:] if len(x.split()[0]) == 2 else x for x in s]
['IP Application', 'ET Appeal', 'Enquiry on situation', 'Stolen', 'Waiver for goods']
```

Body:
I have a column of data in a pandas dataframe and I wanted to only capitalize the 2nd letters for 2 of the variables in the column. E.g. I only want to capitalize "Et Appeal" to "ET Appeal" and "Ip Application" to "IP Application" while leaving the rest of the variables unchanged.

How do I iterate over each row in that specific column and variables and thereafter return the dataframe with the capitalization?

I have defined a function as follows:

def capitalize_nth(s):
    return s[0] + s[1].capitalize() + s[2:]

Column Data in pandas dataframe


问:
Cloud Storage Set CORS to allow download Firebase function
I have a firebase function which serves a website as per below:

```<code>const app = express();
app.use(express.static("my-website"));
exports.app = functions.https.onRequest(app);
</code>```

Where my-website has my-website/subfolder/index.html and my-website/subfolder/index.js. I have deployed the function and it successfully serves up index.html and index.js. However, index.js is attempting to download a file from Cloud Storage but is getting the following error:

```<code>Access to XMLHttpRequest at 'https://storage.cloud.google.com/my-project.appspot.com/my-project-files/data.csv' from origin 'https://us-central1-my-project.cloudfunctions.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

I am not using the firebase cloud storage web library, because the code is already written using the d3.js library as per below, and I can't change it:

```<code>d3.queue()
    .defer(
      d3.csv,
      "https://storage.cloud.google.com/my-project.appspot.com/my-project-files/data.csv"
    )
    .defer(d3.json, "data/config.json")
    .defer(d3.json, "data/geog.json")
    .await(ready);
</code>```

This code generates the following request:

```<code>:authority: storage.cloud.google.com
:method: GET
:path: /my-project.appspot.com/my-project-files/data.csv
:scheme: https
accept: text/csv,*/*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: no-cache
origin: https://us-central1-my-project.cloudfunctions.net
pragma: no-cache
referer: https://us-central1-my-project.cloudfunctions.net/app/my-website/subfolder/index.html
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36
</code>```

I have set a CORS policy on my bucket to allow requests from my cloud functions, gsutil cors get gs://my-project.appspot.com returns:

```<code>[{"maxAgeSeconds": 3600,
"method": ["GET"],
"origin": ["https://us-central1-my-project.cloudfunctions.net"],
"responseHeader": ["Content-Type"]}]
</code>```

I am not sure where to go from here. What am I doing wrong?

答: This is a fairly common error for people setting up webapps. To make sure that sites are secure and to prevent code injections, browsers prevent cross-origin requests. Mozilla has a great manual on how to solve this. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors</p>

Body:
I have a firebase function which serves a website as per below:

const app = express();
app.use(express.static("my-website"));
exports.app = functions.https.onRequest(app);

Where my-website has my-website/subfolder/index.html and my-website/subfolder/index.js. I have deployed the function and it successfully serves up index.html and index.js. However, index.js is attempting to download a file from Cloud Storage but is getting the following error:

Access to XMLHttpRequest at 'https://storage.cloud.google.com/my-project.appspot.com/my-project-files/data.csv' from origin 'https://us-central1-my-project.cloudfunctions.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am not using the firebase cloud storage web library, because the code is already written using the d3.js library as per below, and I can't change it:

d3.queue()
    .defer(
      d3.csv,
      "https://storage.cloud.google.com/my-project.appspot.com/my-project-files/data.csv"
    )
    .defer(d3.json, "data/config.json")
    .defer(d3.json, "data/geog.json")
    .await(ready);

This code generates the following request:

:authority: storage.cloud.google.com
:method: GET
:path: /my-project.appspot.com/my-project-files/data.csv
:scheme: https
accept: text/csv,*/*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: no-cache
origin: https://us-central1-my-project.cloudfunctions.net
pragma: no-cache
referer: https://us-central1-my-project.cloudfunctions.net/app/my-website/subfolder/index.html
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36

I have set a CORS policy on my bucket to allow requests from my cloud functions, gsutil cors get gs://my-project.appspot.com returns:

[{"maxAgeSeconds": 3600,
"method": ["GET"],
"origin": ["https://us-central1-my-project.cloudfunctions.net"],
"responseHeader": ["Content-Type"]}]

I am not sure where to go from here. What am I doing wrong?


问:
How to display particular position on the MapView?
I have a position, which I need to display. The format is like:

```<code>lat: 59.915494, lng: 30.409456
</code>```

Also I need to display current position of the user. The following code:

```<code>    MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this, mapView);
    mapView.getOverlays().add(myLocationOverlay);
    myLocationOverlay.enableMyLocation();
</code>```

doesn't center map on the current position.

答:
In order to adjust where the map is centered on or zoomed into you need to get the MapController.

```<code>MapController controller = mMapView.getController();
controller.animateTo(geoPoint);
// Or if you just want it to snap there
controller.setCenter(geoPoint);

controller.setZoom(5);
</code>```

That point that you want to show you're going to need to add an Overlay.  Here is the documentation for that and a nice tutorial on how to do it.

Body:
I have a position, which I need to display. The format is like:

lat: 59.915494, lng: 30.409456

Also I need to display current position of the user. The following code:

    MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this, mapView);
    mapView.getOverlays().add(myLocationOverlay);
    myLocationOverlay.enableMyLocation();

doesn't center map on the current position.

Body:
In order to adjust where the map is centered on or zoomed into you need to get the MapController.

MapController controller = mMapView.getController();
controller.animateTo(geoPoint);
// Or if you just want it to snap there
controller.setCenter(geoPoint);

controller.setZoom(5);

That point that you want to show you're going to need to add an Overlay.  Here is the documentation for that and a nice tutorial on how to do it.


问:
Get parse error with no reason Typescript, Vue, vue-property-decorator, VSCode
I'm completely new to Typescript and Vue.js, I couldn't have found any solution here.

The below code gives me parsing error : '}' expected

I checked all the brackets pairs and to my eye nothing's wrong.

The base code is here. I forked it from completely working base example.
https://github.com/hanachan1026/vue-firebase-startup-kit

```<code>// Hello.vue
<template>
  <section class="section">
    <div class="container">
      <h1 class="title">
        Hello
        {{userName}}
      </h1>
      <p>Firebase rocks!</p>
      <img id="img1" src="" alt="img1" />
    </div>
  </section>
</template>

<script lang="ts">
import { storage } from "../scripts/firebase";
import Vue from "vue";
import { Component } from "vue-property-decorator";

@Component
export default class Home extends Vue {
  created() {
    const storageRef = storage.ref();

    const imagesRef = storageRef.child('images');

    const fileName = 'IMG_1009.JPG';

    const imgRef = imagesRef.child(fileName);

    imgRef.getDownloadURL().then(function (url) {
      const img: HTMLImageElement = <HTMLImageElement>document.getElementById('img1');

      img.src = url;
    }).catch(function(error) {
      console.log(error); // <= parse error here. why?
    });
  }

  get userName(): string {
    if (this.$store.state.user) {
      return this.$store.state.user.displayName;
    }
    return "";
  }
}
</script>
</code>```

I know this isn't easy to answer because there would be tons of reasons.
If you have any similarly experiences I would like any comments. Thank you.

*add

```<code>➤ npm run serve

> vue_kit@0.1.0 serve /Users/me/show-cam-img-demo
> vue-cli-service serve

 INFO  Starting development server...
Starting type checking service...
Using 1 worker with 2048MB memory limit
98% after emitting CopyPlugin

 ERROR  Failed to compile with 1 errors                                                                                3:34:02 PM

 error  in ./src/views/Hello.vue

Module Error (from ./node_modules/eslint-loader/index.js):

/Users/me/show-cam-img-demo/src/views/Hello.vue
  35:24  error  Parsing error: '}' expected

✖ 1 problem (1 error, 0 warnings)

 @ ./src/router/index.ts 4:0-37 9:13-17
 @ ./src/main.ts
 @ multi (webpack)-dev-server/client?http://192.168.1.37:8080/sockjs-node (webpack)/hot/dev-server.js ./src/main.ts

No type errors found
Version: typescript 3.8.3
Time: 20252ms
</code>```

答:
the error occurs in eslint. you have to config eslint for typescript and vue.
tslint with vue-tslint-loader was the solution till 2019.

Body:
I'm completely new to Typescript and Vue.js, I couldn't have found any solution here.

The below code gives me parsing error : '}' expected

I checked all the brackets pairs and to my eye nothing's wrong.

The base code is here. I forked it from completely working base example.
https://github.com/hanachan1026/vue-firebase-startup-kit

// Hello.vue
<template>

        Hello
        {{userName}}

Firebase rocks!

</template>

I know this isn't easy to answer because there would be tons of reasons.
If you have any similarly experiences I would like any comments. Thank you.

*add

➤ npm run serve

> vue_kit@0.1.0 serve /Users/me/show-cam-img-demo
> vue-cli-service serve

 INFO  Starting development server...
Starting type checking service...
Using 1 worker with 2048MB memory limit
98% after emitting CopyPlugin

 ERROR  Failed to compile with 1 errors                                                                                3:34:02 PM

 error  in ./src/views/Hello.vue

Module Error (from ./node_modules/eslint-loader/index.js):

/Users/me/show-cam-img-demo/src/views/Hello.vue
  35:24  error  Parsing error: '}' expected

✖ 1 problem (1 error, 0 warnings)

 @ ./src/router/index.ts 4:0-37 9:13-17
 @ ./src/main.ts
 @ multi (webpack)-dev-server/client?http://192.168.1.37:8080/sockjs-node (webpack)/hot/dev-server.js ./src/main.ts

No type errors found
Version: typescript 3.8.3
Time: 20252ms


问:
Axios not catching error in catch and weird thing going on in then
I have an app in Vuejs with a server in node that will respond to the axios call that the app make.

When the server respond with an error, axios will not catch it and proceed with to call the .then

Moreover the response is different depending on if it's an error or not :
If it's not an error, i can check the status in response.status
If it's an error, I have to check in response.response.status

Here's an example of what I have to do to handle errors :

```<code>function post(url, data, headers = {}){
  return new Promise((resolve, reject) => {
    axios.post(BASE_URL+url, data, { headers: headers }).then(response => {
      if(response.response != undefined && response.response.status >= 400)
        return reject(response.response.data.message);
      resolve(response.data);
    }).catch(err => reject(err.message));
  });
}
</code>```

Is there any way for axios to catch a response error in the .catch so that I can simplify this ugly code that doesn't make much sense ?

答:
function post(url, data, headers = {}){
  return axios.post(BASE_URL+url, data, { headers: headers }).then(response => {
      if(response.response != undefined && response.response.status >= 400)
        return Promise.reject(response.response.data.message);
      return response.data
    });
  });
}
```

Body:
I have an app in Vuejs with a server in node that will respond to the axios call that the app make.

When the server respond with an error, axios will not catch it and proceed with to call the .then

Moreover the response is different depending on if it's an error or not :
If it's not an error, i can check the status in response.status
If it's an error, I have to check in response.response.status

Here's an example of what I have to do to handle errors :

function post(url, data, headers = {}){
  return new Promise((resolve, reject) => {
    axios.post(BASE_URL+url, data, { headers: headers }).then(response => {
      if(response.response != undefined && response.response.status >= 400)
        return reject(response.response.data.message);
      resolve(response.data);
    }).catch(err => reject(err.message));
  });
}

Is there any way for axios to catch a response error in the .catch so that I can simplify this ugly code that doesn't make much sense ?


问:
Do not include drawableLeft when aligning items
I have Two textViews, one under another, like this:

and this is how it looks from code

```<code>   <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableStart="@drawable/ic_some_sign"
        android:text="Some text in here" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="June 2015" />
</code>```

What I want is to move red circle out of alignment, so two views would be aligned only by text.

so it would look like this:

I can add an ImageVIew and it would do the trick, but I'm curious if there is any other way.

Thanks

答:
Use a view or imageView like a red circle shape and two textViews and put them in a constraintLayout like this. </p>

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ImageView
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_margin="8dp"
        android:id="@+id/imageRedCircle"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toEndOf="@+id/imageRedCircle"
        app:layout_constraintTop_toTopOf="@id/imageRedCircle"
        android:text="Some text in here"
        android:id="@+id/textViewSomeText"
        app:layout_constraintBottom_toBottomOf="@id/imageRedCircle"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="June 2015"
        app:layout_constraintStart_toStartOf="@id/textViewSomeText"
        app:layout_constraintTop_toBottomOf="@id/textViewSomeText"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Body:
I have Two textViews, one under another, like this:

and this is how it looks from code

   <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableStart="@drawable/ic_some_sign"
        android:text="Some text in here" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="June 2015" />

What I want is to move red circle out of alignment, so two views would be aligned only by text.

so it would look like this:

I can add an ImageVIew and it would do the trick, but I'm curious if there is any other way.

Thanks

Body:
Use a view or imageView like a red circle shape and two textViews and put them in a constraintLayout like this.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ImageView
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_margin="8dp"
        android:id="@+id/imageRedCircle"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toEndOf="@+id/imageRedCircle"
        app:layout_constraintTop_toTopOf="@id/imageRedCircle"
        android:text="Some text in here"
        android:id="@+id/textViewSomeText"
        app:layout_constraintBottom_toBottomOf="@id/imageRedCircle"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="June 2015"
        app:layout_constraintStart_toStartOf="@id/textViewSomeText"
        app:layout_constraintTop_toBottomOf="@id/textViewSomeText"/>

</androidx.constraintlayout.widget.ConstraintLayout>


问:
Creating a local SVN branch
I am working on an SVN repository and do not want to create a new SVN branch. Instead of that, I want to create a branch local to my machine, something which could be done easily with Git.

But I am currently using SVN and need to branch out from an already-modified SVN version. In essence, I want following:

svn_repo_version = 2259

working_copy = modified 2259

new_local_svn_branch = based on modified 2259

What is the best way to go about it?

答:
Subversion is a centralized version control system. Some of the advantages of a centralized system is that it forces everyone to play with the same codebase. You can't hide your work for months at a time, then suddenly plop it down two days before a major release. The bad part is that you can't truly have a private branch and not have it show up in the repository.

There's no reason why you shouldn't be able to create your own branch. In fact, I use to give our developers a special "private" directory where they could put their own code, and do private branching. I had a pre-commit script that only allowed the owner of the branch to make changes, although I had it setup, so anyone could see it.

If you're worried that your private branches might clog up the branches directory, remember you can remove a branch from the branches directory when you're done. Or, you can request a parallel private directory where you can put your stuff.

If you really want to create a true private area where you can use Subversion and check in code without it appearing in the main repository, you have two choices I know of:

SVK: This is a front end distributed version control system that uses Subversion on its backend. You can create your own Subversion repository, and post changes back and forth between your local repository and the master repository.

Git: Git comes with a tool called git-svn which allows you to pull data off of a Subversion repository into a local Git repository. You can then use your local Git repository to do your branching, and later push your changed back into Subversion. There's even a Git version of Tortoise.

The only caveat is that you will have to get your hands dirty with the command line interface with both of these tools.

Title: Creating a local SVN branch


问:
How to create BigQuery Data Transfer w/ Python + Service Account?
I'm trying to create a new data transfer job in BigQuery using Python and google-cloud-bigquery-datatransfer but I run into the error:

google.api_core.exceptions.PermissionDenied: 403 User does not have sufficient permission: bigquery.transfers.update is required on project PROJECT_ID

I've included my code below which isn't terribly interesting. I am running this while setting GOOGLE_APPLICATION_CREDENTIALS=/path/to/secrets/service-account.json. This service account has Owner status because I thought that upping its privileges might get me past the permissions error.

Now I'm starting to think that this API doesn't work at all with a service account, or am I crazy? I see authorization_code and CheckValidAuth in the documentation but it says they're optional.

Does the Google BigQuery Data Transfer API work with service accounts?

import os
import boto3
from google.cloud import bigquery_datatransfer_v1
import google.protobuf.json_format

client = bigquery_datatransfer_v1.DataTransferServiceClient()

parent = client.project_path('PROJECT_ID')

transfer_config = {
    "destination_dataset_id": "neilo",
    "display_name": "NeilO Data Transfer Test",
    "data_source_id": "amazon_s3",
    "params": {
        "destination_table_name_template": "test_table",
        "data_path": "s3://bucket/path/to/files/*.csv.gz",
        "access_key_id": os.environ['AWS_ACCESS_KEY_ID'],
        "secret_access_key": os.environ['AWS_SECRET_ACCESS_KEY'],
        "file_format": "CSV"
    },
    "schedule": "daily"
}

transfer_config = google.protobuf.json_format.ParseDict(
    transfer_config, bigquery_datatransfer_v1.types.TransferConfig())

response = client.create_transfer_config(parent, transfer_config)
```

The problem is

答:
The problem was that I mistyped GOOGLE_APPLICATION_CREDENTIALS when I set it so I was inadvertently using the wrong service account. I added the following code to verify the correct project:

from google.cloud import bigquery
assert bigquery.Client().project == 'PROJECT_ID'
```

I also made sure that the service account has the bigquery.transfers.update permission using the minimal built-in role of Editor:

Body:
I'm trying to create a new data transfer job in BigQuery using Python and google-cloud-bigquery-datatransfer but I run into the error:

google.api_core.exceptions.PermissionDenied: 403 User does not have sufficient permission: bigquery.transfers.update is required on project PROJECT_ID

I've included my code below which isn't terribly interesting. I am running this while setting GOOGLE_APPLICATION_CREDENTIALS=/path/to/secrets/service-account.json. This service account has Owner status because I thought that upping its privileges might get me past the permissions error.

Now I'm starting to think that this API doesn't work at all with a service account, or am I crazy? I see authorization_code and CheckValidAuth in the documentation but it says they're optional.

Does the Google BigQuery Data Transfer API work with service accounts?

import os
import boto3
from google.cloud import bigquery_datatransfer_v1
import google.protobuf.json_format

client = bigquery_datatransfer_v1.DataTransferServiceClient()

parent = client.project_path('PROJECT_ID')

transfer_config = {
    "destination_dataset_id": "neilo",
    "display_name": "NeilO Data Transfer Test",
    "data_source_id": "amazon_s3",
    "params": {
        "destination_table_name_template": "test_table",
        "data_path": "s3://bucket/path/to/files/*.csv.gz",
        "access_key_id": os.environ['AWS_ACCESS_KEY_ID'],
        "secret_access_key": os.environ['AWS_SECRET_ACCESS_KEY'],
        "file_format": "CSV"
    },
    "schedule": "daily"
}

transfer_config = google.protobuf.json_format.ParseDict(
    transfer_config, bigquery_datatransfer_v1.types.TransferConfig())

response = client.create_transfer_config(parent, transfer_config)

The problem is

Body:
The problem was that I mistyped GOOGLE_APPLICATION_CREDENTIALS when I set it so I was inadvertently using the wrong service account. I added the following code to verify the correct project:

from google.cloud import bigquery
assert bigquery.Client().project == 'PROJECT_ID'

I also made sure that the service account has the bigquery.transfers.update permission using the minimal built-in role of Editor:


问:
Read and Write Data into Python Files
Please advise how I'm getting the following error:

```<code>File "/Users/<username>/PycharmProjects/OOP/csv_write.py", line 8
  print(f'Column names are {", ".join(row)}')
                                           ^
SyntaxError: invalid syntax
</code>```

Code:

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
```
<p>As I'm trying to read from the file and display the information as follows as per the link.</p>
<p>employee_birthday.txt :</p>
```name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
```

This question has been resolved and thank you for the responses below.

答:
Try this for that line the traceback is referring to:

f-strings apply for py3.5 and greater versions, see if either of these work:

```<code>print('Column names are',", ".join(row))
</code>```

OR

```<code>print('Column names are %s'%", ".join(row))
</code>```

OR

```<code>print('Column names are {}'.format(", ".join(row)))
</code>```

Title: Read and Write Data into Python Files

Body:
Please advise how I'm getting the following error:

File "/Users/<username>/PycharmProjects/OOP/csv_write.py", line 8
  print(f'Column names are {", ".join(row)}')
                                           ^
SyntaxError: invalid syntax

Code:

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')

As I'm trying to read from the file and display the information as follows as per the link.

employee_birthday.txt :

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March

This question has been resolved and thank you for the responses below.

Body:
Try this for that line the traceback is referring to:

f-strings apply for py3.5 and greater versions, see if either of these work:

print('Column names are',", ".join(row))

OR

print('Column names are %s'%", ".join(row))

OR

print('Column names are {}'.format(", ".join(row)))


问:
Strategy for maximum throughput having 6 Kafka Consumers when the processing of each message requires a long time
Consider this scenario: Kafka topic with 6 partitions. Spring Java Kafka Consumer Application with 6 replicas so that each of them deals with one of the partitions.

The problem I'm facing is the processing of each message in the consumer takes a long time (~20 seconds), since it needs to call a really slow external system.

So even though I've provisioned 6 partitions/replicas I end up having a bottleneck in which the 6 consumers block ~20 seconds per message, which means a throughput of 6 messages every 20 seconds!!

Could you suggest ways to speed up this scenario taking into account that I can't modify the behaviour of the external system?

答:
Increase the number of partitions and concurrency on each instance.

The number of partitions must be >= instances * concurrency.