问:
Toggle Axes/Grid in p5.js "below" a drawing
I'm currently experimenting with generative art/creative coding. I'm using p5.js to generate some ellipses following a invisible circle, which I can adjust with some controls (changing scale, direction and so on...).

UI without axes

Now I want to add some functionality to toggle some axes/grid etc like this:

UI with axes

I know, that p5.js draws 60 times per second and that I could redraw everything every frame (which I think I could achieve by storing all ellipses etc and redraw them every frame, but to me this seems like a bad practice, because I would have to store a lot of information just for redrawing some "metadrawings").

So my question is: How can I toggle axes/grid without storing the whole drawing in a perfomant way? My first thought was to use two up to N canvases for "metadrawing" like axes, grid and so on and clear or redraw them, if I toggle them.

答:
I've kinda managed it now to solve my problem (other recommendations using best practices welcome! :) ).

I've added three div's (one wrapper for meta drawings, one wrapper for the main drawings and one wrapper for the two other wrappers). Then I just place the main-drawing-wrapper above my meta-drawing-wrapper using css. I'm also using p5.js instance mode to have separate sketches.

HTML:

```<code><div id="drawings-wrapper">
    <div id="meta-drawing-wrapper">
    </div>
    <div id="main-drawing-wrapper">
    </div>
</div>
</code>```

CSS:

```<code>#drawings-wrapper {
    position: absolute;
}

#meta-drawing-wrapper, #main-drawing-wrapper {
    position: absolute;
    top: 0;
    left: 0
}

#meta-drawing-wrapper {
    z-index: 0;
}

#main-drawing-wrapper {
    z-index: 10
}
</code>```

JS:

```<code>new p5((sketch) => {...} // meta drawing

new p5((sketch) => {...} // main drawing
</code>```

Result:

Body:
I've kinda managed it now to solve my problem (other recommendations using best practices welcome! :) ).

I've added three div's (one wrapper for meta drawings, one wrapper for the main drawings and one wrapper for the two other wrappers). Then I just place the main-drawing-wrapper above my meta-drawing-wrapper using css. I'm also using p5.js instance mode to have separate sketches.

HTML:

<div id="drawings-wrapper">
    <div id="meta-drawing-wrapper">
    </div>
    <div id="main-drawing-wrapper">
    </div>
</div>

CSS:

#drawings-wrapper {
    position: absolute;
}

#meta-drawing-wrapper, #main-drawing-wrapper {
    position: absolute;
    top: 0;
    left: 0
}

#meta-drawing-wrapper {
    z-index: 0;
}

#main-drawing-wrapper {
    z-index: 10
}

JS:

new p5((sketch) => {...} // meta drawing

new p5((sketch) => {...} // main drawing

Result:


来源: stackexchange

问:
Creating an ABPerson object
This problem is almost certainly gonna have a really simple answer, but I just can't see it. I'm programming an app for the iPhone in Xcode and I'm trying to create an instance of an ABPerson object, but can't. In my .h file, I am importing as follows:

```<code>#import <AddressBook/AddressBook.h>
#import <AddressBook/ABPerson.h>
</code>```

Then when I try to create it using "ABPerson *person;", it gives the error, "Unknown type name 'ABPerson'".

I have searched the internet and there doesn't seem to be much on the use of ABPerson and where I have seen it used, they have done it like this and its worked fine.

Ultimately, I want to create a VCard containing the details of somebody which the user can then save to their phone so if you know of another way of doing this which would eliminate this problem, that would also be great.

Thanks,

Matthew

答: Have you added the AddressBook framework to your app? Look in XCode4, look at your project file -> Build Phases -> Link Binary with Libraries. </p>

ContentLicense: CC BY-SA 3.0

Title: Creating an ABPerson object

Body:
This problem is almost certainly gonna have a really simple answer, but I just can't see it. I'm programming an app for the iPhone in Xcode and I'm trying to create an instance of an ABPerson object, but can't. In my .h file, I am importing as follows:

#import <AddressBook/AddressBook.h>
#import <AddressBook/ABPerson.h>

Then when I try to create it using "ABPerson *person;", it gives the error, "Unknown type name 'ABPerson'".

I have searched the internet and there doesn't seem to be much on the use of ABPerson and where I have seen it used, they have done it like this and its worked fine.

Ultimately, I want to create a VCard containing the details of somebody which the user can then save to their phone so if you know of another way of doing this which would eliminate this problem, that would also be great.

Thanks,

Matthew


问:
How to pass a variable to predicate expression?
I'm creating Expression<Func<Entity, bool>> expression tree dynamically:

int id = ...;
Expression<Func<Entity, int>> keySelector = e => e.Id;
BinaryExpression equals = Expression.Equal(
   keySelector.Body,
   Expression.Constant(id, keySelector.Body.Type)); //replace this with a variable

var predicate = Expression.Lambda<Func<Entity, bool>>(equals, keySelector.Parameters[0]);
```

which produces equivalent of e => e.Id == 1.

How do I pass a variable instead of a constant: e => e.Id == id

答:
You need to change the const to something that you can change a property of:

```<code>class IDHolder
{
    public int Id { get; set; }
}
</code>```

now you bind your expression to instance of IDHolder like so:

```<code>var idHolder = new IDHolder { Id = 0 };
Expression<Func<Entity, int>> keySelector = e => e.Id;

BinaryExpression equals = Expression.Equal(
    keySelector.Body,

    Expression.Property(
        Expression.Constant(idHolder, typeof(IDHolder)),
    nameof(IDHolder.Id))

    );

var predicate = Expression.Lambda<Func<Entity, bool>>(equals, keySelector.Parameters[0]);
</code>```

the predicate becomes slightly more complicated yet nothing that would make EF break:

```<code>x => x.Id == idHandler.Id
</code>```

you can test this by compiling the predicate and running simple tests changing Id and the entity:

```<code>var func = predicate.Compile();

idHolder.Id = 5;

Console.WriteLine(func(new Entity { Id = 0 }).ToString());  // false
Console.WriteLine(func(new Entity { Id = 5 }).ToString());  // true

idHolder.Id = 6;

Console.WriteLine(func(new Entity { Id = 6 }).ToString());   // true
</code>```

note that this approach is not thread safe and will result in strange behavior if you cache predicate and idHolder and use that in web api project or anything potentially using this predicate concurrently.  To just auto translate some conditions from requests it would be better to just create the expression each time you need to use it in EF. There is no significant performance hit while creating expressions; the costly operation is the compilation and that is never done by EF.

Or maybe I misunderstood your question and you simply need a way to change the value of id, and as suggested by @Jochem Van Hespen you need a function:

```<code>public Expression<Func<Entity,bool>> GetPredicate(int id){

    Expression<Func<Entity, int>> keySelector = e => e.Id;
    BinaryExpression equals = Expression.Equal(
       keySelector.Body,
       Expression.Constant(id, keySelector.Body.Type));

    var predicate = Expression.Lambda<Func<Entity, bool>>(equals, keySelector.Parameters[0]);
    return predicate;
    }
</code>```

and you can use it like this:

```<code> _dbContext.Set<Entity>().Where(GetPredicate(4))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm creating Expression<Func<Entity, bool>> expression tree dynamically:

int id = ...;
Expression<Func<Entity, int>> keySelector = e => e.Id;
BinaryExpression equals = Expression.Equal(
   keySelector.Body,
   Expression.Constant(id, keySelector.Body.Type)); //replace this with a variable

var predicate = Expression.Lambda<Func<Entity, bool>>(equals, keySelector.Parameters[0]);

which produces equivalent of e => e.Id == 1.

How do I pass a variable instead of a constant: e => e.Id == id

Body:
You need to change the const to something that you can change a property of:

class IDHolder
{
    public int Id { get; set; }
}

now you bind your expression to instance of IDHolder like so:

var idHolder = new IDHolder { Id = 0 };
Expression<Func<Entity, int>> keySelector = e => e.Id;

BinaryExpression equals = Expression.Equal(
    keySelector.Body,

    Expression.Property(
        Expression.Constant(idHolder, typeof(IDHolder)),
    nameof(IDHolder.Id))

    );

var predicate = Expression.Lambda<Func<Entity, bool>>(equals, keySelector.Parameters[0]);

the predicate becomes slightly more complicated yet nothing that would make EF break:

x => x.Id == idHandler.Id

you can test this by compiling the predicate and running simple tests changing Id and the entity:

var func = predicate.Compile();

idHolder.Id = 5;

Console.WriteLine(func(new Entity { Id = 0 }).ToString());  // false
Console.WriteLine(func(new Entity { Id = 5 }).ToString());  // true

idHolder.Id = 6;

Console.WriteLine(func(new Entity { Id = 6 }).ToString());   // true

note that this approach is not thread safe and will result in strange behavior if you cache predicate and idHolder and use that in web api project or anything potentially using this predicate concurrently.  To just auto translate some conditions from requests it would be better to just create the expression each time you need to use it in EF. There is no significant performance hit while creating expressions; the costly operation is the compilation and that is never done by EF.

Or maybe I misunderstood your question and you simply need a way to change the value of id, and as suggested by @Jochem Van Hespen you need a function:

public Expression<Func<Entity,bool>> GetPredicate(int id){

    Expression<Func<Entity, int>> keySelector = e => e.Id;
    BinaryExpression equals = Expression.Equal(
       keySelector.Body,
       Expression.Constant(id, keySelector.Body.Type));

    var predicate = Expression.Lambda<Func<Entity, bool>>(equals, keySelector.Parameters[0]);
    return predicate;
    }

and you can use it like this:

 _dbContext.Set<Entity>().Where(GetPredicate(4))


问:
How to add image/video to a specific object on loaded scene from Blender
I have a scene imported from Blender. I have a few screens inside the scene and I would like to add either an image/video on those screens.

Note: I'm using the OOP model to create the app

I have the scene imported with the gltfLoader and I wait for all the resources to be loaded

```<code> this.resources.on('ready', () => {

            // Setup
            this.controlRoom = new ControlRoom()
            this.tvScreen4x4 = new tvScreen4x4()

        })
</code>```

ControlRoom is the actual scene and the other one is just one mesh from all the screens.

```<code>import * as THREE from 'three'
import Experience from "../../Experience.js"

export default class tvScreen4x4 {

    constructor() {
        this.experience = new Experience()
        this.scene = this.experience.scene
        this.resources = this.experience.resources

        // Setup
        this.setTexture()
        this.setMaterial()
        this.updateMesh()
    }

    setTexture() {
        this.texture = {}
        this.texture.normal = this.resources.items.tvScreen4x4
    }

    setMaterial() {
        this.material = new THREE.MeshStandardMaterial({
            map: this.texture.normal
        })
    }

    updateMesh() {

        this.scene.traverse((child) => {
            if (child instanceof THREE.Mesh && child.name === 'tv_4x4_screen') {

                child.material = this.material
                child.material.needsUpdate = true

                console.log(child.material);

            }
        })
    }
}
</code>```
```<code>this.resources.items.tvScreen4x4
</code>```

Is returning this the item from my custom source.js

```<code>export default [
    {
        name: 'controlRoom',
        type: 'gltfModel',
        path: 'models/controlroom.gltf'
    },
    {
        name: 'tvScreen4x4',
        type: 'texture',
        path: 'textures/screen.jpg'
    },
    {
        name: 'tvScreen5x4',
        type: 'texture',
        path: 'textures/screen.jpg'
    },
    {
        name: 'tvScreen6x4',
        type: 'texture',
        path: 'textures/screen.jpg'
    }
]
</code>```

The console.log(child.material) returns the following:

What I am doing wrong that the texture doesn't show on that screen? The console log returns the correct map.

答:
I have found the fix for my issue. The code was correct and the scene was imported as it should. One thing I haven't done right is how I exported the Blender scene.

When exporting the scene i should have ticked the UVs and in the Geometry section. Like below.

So it was more of a blender issue rather than a Three.js

Body:
I have a scene imported from Blender. I have a few screens inside the scene and I would like to add either an image/video on those screens.

Note: I'm using the OOP model to create the app

I have the scene imported with the gltfLoader and I wait for all the resources to be loaded

 this.resources.on('ready', () => {

            // Setup
            this.controlRoom = new ControlRoom()
            this.tvScreen4x4 = new tvScreen4x4()

        })

ControlRoom is the actual scene and the other one is just one mesh from all the screens.

import * as THREE from 'three'
import Experience from "../../Experience.js"

export default class tvScreen4x4 {

    constructor() {
        this.experience = new Experience()
        this.scene = this.experience.scene
        this.resources = this.experience.resources

        // Setup
        this.setTexture()
        this.setMaterial()
        this.updateMesh()
    }

    setTexture() {
        this.texture = {}
        this.texture.normal = this.resources.items.tvScreen4x4
    }

    setMaterial() {
        this.material = new THREE.MeshStandardMaterial({
            map: this.texture.normal
        })
    }

    updateMesh() {

        this.scene.traverse((child) => {
            if (child instanceof THREE.Mesh && child.name === 'tv_4x4_screen') {

                child.material = this.material
                child.material.needsUpdate = true

                console.log(child.material);

            }
        })
    }
}

this.resources.items.tvScreen4x4

Is returning this the item from my custom source.js

export default [
    {
        name: 'controlRoom',
        type: 'gltfModel',
        path: 'models/controlroom.gltf'
    },
    {
        name: 'tvScreen4x4',
        type: 'texture',
        path: 'textures/screen.jpg'
    },
    {
        name: 'tvScreen5x4',
        type: 'texture',
        path: 'textures/screen.jpg'
    },
    {
        name: 'tvScreen6x4',
        type: 'texture',
        path: 'textures/screen.jpg'
    }
]

The console.log(child.material) returns the following:

What I am doing wrong that the texture doesn't show on that screen? The console log returns the correct map.


问:
Compare 2 columns in same excel sheet in pandas
In excel sheet i want to compare the 2 columns. The column names like file_1 and file_2. by using these 2 cols want to create the another col like 'diff' by using excel formula [countifs]. In case , if file_1 and file_2 column records matched it should be 0 (Zero) in diff column otherwise it should be 1. But, i am not as excepted result. Could please help anyone.

here is my inputs :

```<code>   file_1    file_2
    G          G
    A          B
    C          F
    E          H
    A          C
    H          E
</code>```

Output Dataframe :

```<code>    file_1       file_2       diff
     G          G              0
     A          B              1
     C          F              1
     E          H              0
     A          C              0
     H          E              0
</code>```

Sample code :

```<code>     df = pd.read_excel('file1.xlsx')
     df1 = df[df['file_1'].isin(df['file_2'])]
     df['diff'] = df1
     print(df)
</code>```

答:
I think the statement:

df1 = df[df['file_1'].isin(df['file_2'])]

builds a dataframe (df1) where each row is a row from the original dataframe (df) when the value in column "file_1" (in the current row) is available in ANY  row of column "file_2". It compares each value of column "file_1"with all values of column "file_2"

So, from your code, the df1 output is:

```<code>    file_1 file_2
0   G   G
2   C   F
3   E   H
5   H   E
</code>```

I would suggest to use a simple statement like the following:

df2 = np.where(df.file_1 == df.file_2, 0,1)

It compares value in column "file_1" with the value in column "file_2"for each row and same row.

The code looks like the following:

```<code>import pandas as pd
import numpy as np
df = pd.read_excel('file1.xlsx')
df2 = np.where(df.file_1 == df.file_2, 0,1)
df['diff'] = df2
print(df)
</code>```

The output is:

```<code>  file_1 file_2  diff
0      G      G     0
1      A      B     1
2      C      F     1
3      E      H     1
4      A      C     1
5      H      E     1
</code>```

Body:
In excel sheet i want to compare the 2 columns. The column names like file_1 and file_2. by using these 2 cols want to create the another col like 'diff' by using excel formula [countifs]. In case , if file_1 and file_2 column records matched it should be 0 (Zero) in diff column otherwise it should be 1. But, i am not as excepted result. Could please help anyone.

here is my inputs :

   file_1    file_2
    G          G
    A          B
    C          F
    E          H
    A          C
    H          E

Output Dataframe :

    file_1       file_2       diff
     G          G              0
     A          B              1
     C          F              1
     E          H              0
     A          C              0
     H          E              0

Sample code :

     df = pd.read_excel('file1.xlsx')
     df1 = df[df['file_1'].isin(df['file_2'])]
     df['diff'] = df1
     print(df)

Body:
I think the statement:

df1 = df[df['file_1'].isin(df['file_2'])]

builds a dataframe (df1) where each row is a row from the original dataframe (df) when the value in column "file_1" (in the current row) is available in ANY  row of column "file_2". It compares each value of column "file_1"with all values of column "file_2"

So, from your code, the df1 output is:

    file_1 file_2
0   G   G
2   C   F
3   E   H
5   H   E

I would suggest to use a simple statement like the following:

df2 = np.where(df.file_1 == df.file_2, 0,1)

It compares value in column "file_1" with the value in column "file_2"for each row and same row.

The code looks like the following:

import pandas as pd
import numpy as np
df = pd.read_excel('file1.xlsx')
df2 = np.where(df.file_1 == df.file_2, 0,1)
df['diff'] = df2
print(df)

The output is:

  file_1 file_2  diff
0      G      G     0
1      A      B     1
2      C      F     1
3      E      H     1
4      A      C     1
5      H      E     1


问:
C++/CLI, XAML, and event handlers
I'm new to the Windows world, and I think I'm getting lost in the weeds on a problem. I'd love some advice from people with experience with C++/CLI and WPF and XAML.

I have some win32 code, and I need to run a WPF GUI. I found this MS walkthrough sample, which uses C++/CLI. I adapted it to my purposes, and it works great.

Next, I wanted to rip out the programmatic WPF stuff and use XAML instead. This is so I can hand off the XAML to a designer person and take myself out of the UI design loop, where I most assuredly don't belong. After reading the "WPF Interoperation Projects" section of WPF and Win32 Interoperation on MSDN, I decided to go with the XamlReader::Load option and load uncompiled XAML at runtime. My XAML markup is a Canvas UIElement which I programmatically add as a child of my root Grid C++/CLI element. This works great.

Now I want to add event handler to controls in the XAML. This is where I have started to run into trouble. I'm sure that my general ignorance of the Windows world is 95% of what's killing me here.

I started with Rob Relyea's page outlining the various XAML-and-event-handler options.

I decided to try compiling the XAML as a C# DLL. It's basically the same XAML as what I used in the runtime Load case. I instantiate the object and programmatically add as it as a child, just like before. But ... I get nothing but a black window. No exceptions get thrown either. I'm baffled.

My question is, am I even headed down the right path? The page on XAML-and-event-handlers says you can use event handlers defined in uncompiled XAML in .Net Framework 4. Should I bite the bullet and just go to VS 2010 (I'm presently on VS 2008) so I can use .Net Framework 4 and just stick with uncompiled XAML? Are there any gotchas with doing things that way?

Or, if you do think the compiled C# DLL is a reasonable path, do you have any ideas on how I can debug the problems I'm having?

Or, is there a better and completely different approach?

Thanks in advance for your advice.

Polly

答:
Thanks to everyone for the responses. On the matter of getting stuck on the C# DLL, I found this C++/CLI sample: http://msdn.microsoft.com/en-us/library/aa970266.aspx. Using that, I found my error, and was able to load the WPF without problems.

However, the whole motivation for loading the C# DLL was that I had understood that that was the way to attach event handlers programmatically. Following AresAvatar's suggestion, I found that I could use FindName to attach the handlers -- both within the C# DLL, but it also worked with my original loose-XAML approach. So, I didn't need the C# DLL after all!

It's all working nicely now. Again, thanks for all of your help and suggestions.

Title: C++/CLI, XAML, and event handlers


问:
Remove "sysadmin@thingsboard.org'" from the database to install Thingsboard
I am trying to install Thingsboard on Windows 10. But I get the error: "org.thingsboard.server.dao.exception.DataValidationException: User with email 'sysadmin@thingsboard.org'  already present in database!"

Would anyone please help me to resolve this problem?

Thank you.

答:
Thingsboard uses /usr/share/thingsboard/data/.firstLaunch file to see if installation is needed on startup. If .firstLaunch file exists, Thingsboard will just start, but if does not exist, Thingsboard will try to install and populate database.

If you already have Thingsboard database configured, just create empty .firstLaunch file in /usr/share/thingsboard/data directory and error will not occur anymore.

Check this link to see how it works: https://github.com/thingsboard/thingsboard/blob/99afad3f6fa9e27fbf81c531ca3917b597df1e24/msa/tb/docker/start-tb.sh#L27


问:
Drop first row when index doesn't start at 0
I want to drop the first row of a dataframe subset which is a subset of the main dataframe main. The first row of the dataframe has index = 31, so when I try dropping the first row I get the following error:

```<code>>>> subset.drop(0, axis=1)
KeyError: '[0] not found in axis'
</code>```

I want to perform this drop on multiple dataframes, so I cannot drop index 31 on every dataframe. Is it possible to drop the first row when the index isn't equal to 0?

答:
Simpliest is select all rows without first by position:

```<code>df = df.iloc[1:]
</code>```

Or with drop is possible select first value, but if duplicated values, then all rows are removed:

```<code>df = df.drop(df.index[0])
</code>```

Your solution try remove column 0:

```<code>subset.drop(0, axis=1)
</code>```

Body:
I want to drop the first row of a dataframe subset which is a subset of the main dataframe main. The first row of the dataframe has index = 31, so when I try dropping the first row I get the following error:

>>> subset.drop(0, axis=1)
KeyError: '[0] not found in axis'

I want to perform this drop on multiple dataframes, so I cannot drop index 31 on every dataframe. Is it possible to drop the first row when the index isn't equal to 0?

Body:
Simpliest is select all rows without first by position:

df = df.iloc[1:]

Or with drop is possible select first value, but if duplicated values, then all rows are removed:

df = df.drop(df.index[0])

Your solution try remove column 0:

subset.drop(0, axis=1)


问:
Why is git doing a rebase in multiple steps?
I had to rebase a feature branch on a develop branch.

So I just did a rebase and it had me do this rebase operation in 5 steps.

I could see these markers:

```<code>REBASE 1/5
REBASE 2/5
REBASE 3/5
REBASE 4/5
</code>```

The first git rebase <branch> command gave me some conflicts.
So I edited the files, added them and finally did a git rebase --continue command.
But it asked me: No changes - did you forget to use 'git add'?
I then had to issue the git rebase --skip command, which showed additional conflict files not shown at the first step.
And I had to repeat the operation multiple times, in this case, some 5 times, to finally have a Applying: displayed showing there were no more conflicts and that the rebase had completed.

答:
Let's say that your local and remote branch looked like this before the rebase:

```<code>remote:  A -- B
          \
local:     C -- D -- E -- F -- G
</code>```

A rebase of local against remote would result in the following branch diagram:

```<code>remote:  A -- B
               \
local:          C' -- D' -- E' -- F' -- G'
</code>```

That is, the rebase starts using the new base of A -- B for your branch.  It then reapplies the 5 commits C through G on top of this new base.  Each "step" of the rebase, as you perceive it, involves applying one of these commits on top of the new base.

Regarding fixing the same thing multiple times, a merge conflict will be triggered if a given line or lines both have been changed in the HEAD commit of the new base and the commit being applied.  If that keeps happening, the same region of code will keep getting flagged with a conflict.

An exact example would be your resolving a line of code to merge with the HEAD of the initial new base (commit B in the above diagram).  With each successive applied commit, you reintroduce the old logic, which then needs to be resolved again.  You may consider a rebase as being like a slow motion merge, where the changes get layered on bit by bit, like baking a cake.

Body:
I had to rebase a feature branch on a develop branch.

So I just did a rebase and it had me do this rebase operation in 5 steps.

I could see these markers:

REBASE 1/5
REBASE 2/5
REBASE 3/5
REBASE 4/5

The first git rebase <branch> command gave me some conflicts.
So I edited the files, added them and finally did a git rebase --continue command.
But it asked me: No changes - did you forget to use 'git add'?
I then had to issue the git rebase --skip command, which showed additional conflict files not shown at the first step.
And I had to repeat the operation multiple times, in this case, some 5 times, to finally have a Applying: displayed showing there were no more conflicts and that the rebase had completed.

Body:
Let's say that your local and remote branch looked like this before the rebase:

remote:  A -- B
          \
local:     C -- D -- E -- F -- G

A rebase of local against remote would result in the following branch diagram:

remote:  A -- B
               \
local:          C' -- D' -- E' -- F' -- G'

That is, the rebase starts using the new base of A -- B for your branch.  It then reapplies the 5 commits C through G on top of this new base.  Each "step" of the rebase, as you perceive it, involves applying one of these commits on top of the new base.

Regarding fixing the same thing multiple times, a merge conflict will be triggered if a given line or lines both have been changed in the HEAD commit of the new base and the commit being applied.  If that keeps happening, the same region of code will keep getting flagged with a conflict.

An exact example would be your resolving a line of code to merge with the HEAD of the initial new base (commit B in the above diagram).  With each successive applied commit, you reintroduce the old logic, which then needs to be resolved again.  You may consider a rebase as being like a slow motion merge, where the changes get layered on bit by bit, like baking a cake.


问:
CASE statements for creating a dynamic Excel spreadsheet from my configuration in the DB
I want to make dynamic representation of the settings of the system from my DataBase. Before I manually edited a Excel spreadsheet with the new configration.

I've created a Case statement with 8 different possible configuration from my system and the Case statement will at least be called 20 times with 20 unique ID's. f.eks. = 112 AS keyword1, = 113 AS keyword2, etc.

So now I've done some research and I've made some nice progress but now my question is:
Whats the best way to optimize my query?

```<code>-- Quick overview of all case conditions
-- 1. 'A,R,RO,H'
-- 2. 'A,R,H'
-- 3. 'A,R,RO'
-- 4. 'A,R'
-- 5. 'A,RO,H
-- 6. 'A,RO'
-- 7. 'A,H'
-- 8. 'A'

SELECT dtg.itemtypegroupname AS 'DTG', dt.itemtypename AS 'DT',
(SELECT (CASE
-- 1)
WHEN itxk.keyreq = 1 AND itxk.readonly = 1 AND itxk.hidden = 1 THEN 'A,R,RO,H'
-- 2)
WHEN itxk.keyreq = 1 AND itxk.readonly = 0 AND itxk.hidden = 1 THEN 'A,R,H'
-- 3)
WHEN itxk.keyreq = 1 AND itxk.readonly = 1 AND itxk.hidden = 0 THEN 'A,R,RO'
-- 4)
WHEN itxk.keyreq = 1 AND itxk.readonly = 0 AND itxk.hidden = 0 THEN 'A,R'
-- 5)
WHEN itxk.keyreq = 0 AND itxk.readonly = 1 AND itxk.hidden = 1 THEN 'A,RO,H'
-- 6)
WHEN itxk.keyreq = 0 AND itxk.readonly = 1 AND itxk.hidden = 0 THEN 'A,RO'
-- 7)
WHEN itxk.keyreq = 0 AND itxk.readonly = 0 AND itxk.hidden = 1 THEN 'A,H'
-- 8)
WHEN itxk.keyreq = 0 AND itxk.readonly = 0 AND itxk.hidden = 0 THEN 'A'
 END)
 FROM [x].[itemtypexkeyword] itxk WHERE itxk.itemtypenum = dt.itemtypenum AND
itxk.keytypenum = 112) AS Keyword1
FROM [x].[doctype] dt
INNER JOIN x.itemtypegroup dtg ON dt.itemtypegroupnum = dtg.itemtypegroupnum
</code>```

Within each CASE statement I'm going to have a FROM WHERE = 112 ETC.
Is there a way to minimize the amount of lines maybe to put the case into a variable or what's possible?

Below is what I dont want to do because of optimization.

```<code>SELECT dtg.itemtypegroupname AS 'DTG', dt.itemtypename AS 'DT',
(SELECT (CASE
-- 1)
WHEN itxk.keyreq = 1 AND itxk.readonly = 1 AND itxk.hidden = 1 THEN 'A,R,RO,H'
-- 2)
WHEN itxk.keyreq = 1 AND itxk.readonly = 0 AND itxk.hidden = 1 THEN 'A,R,H'
-- 3)
WHEN itxk.keyreq = 1 AND itxk.readonly = 1 AND itxk.hidden = 0 THEN 'A,R,RO'
-- 4)
WHEN itxk.keyreq = 1 AND itxk.readonly = 0 AND itxk.hidden = 0 THEN 'A,R'
-- 5)
WHEN itxk.keyreq = 0 AND itxk.readonly = 1 AND itxk.hidden = 1 THEN 'A,RO,H'
-- 6)
WHEN itxk.keyreq = 0 AND itxk.readonly = 1 AND itxk.hidden = 0 THEN 'A,RO'
-- 7)
WHEN itxk.keyreq = 0 AND itxk.readonly = 0 AND itxk.hidden = 1 THEN 'A,H'
-- 8)
WHEN itxk.keyreq = 0 AND itxk.readonly = 0 AND itxk.hidden = 0 THEN 'A'
 END)
 FROM [x].[itemtypexkeyword] itxk WHERE itxk.itemtypenum = dt.itemtypenum AND
itxk.keytypenum = 112) AS keyword1,
(SELECT (CASE
-- 1)
WHEN itxk.keyreq = 1 AND itxk.readonly = 1 AND itxk.hidden = 1 THEN 'A,R,RO,H'
-- 2)
WHEN itxk.keyreq = 1 AND itxk.readonly = 0 AND itxk.hidden = 1 THEN 'A,R,H'
-- 3)
WHEN itxk.keyreq = 1 AND itxk.readonly = 1 AND itxk.hidden = 0 THEN 'A,R,RO'
-- 4)
WHEN itxk.keyreq = 1 AND itxk.readonly = 0 AND itxk.hidden = 0 THEN 'A,R'
-- 5)
WHEN itxk.keyreq = 0 AND itxk.readonly = 1 AND itxk.hidden = 1 THEN 'A,RO,H'
-- 6)
WHEN itxk.keyreq = 0 AND itxk.readonly = 1 AND itxk.hidden = 0 THEN 'A,RO'
-- 7)
WHEN itxk.keyreq = 0 AND itxk.readonly = 0 AND itxk.hidden = 1 THEN 'A,H'
-- 8)
WHEN itxk.keyreq = 0 AND itxk.readonly = 0 AND itxk.hidden = 0 THEN 'A'
 END)
 FROM [x].[itemtypexkeyword] itxk WHERE itxk.itemtypenum = dt.itemtypenum AND
itxk.keytypenum = 113) AS keyword2
FROM [x].[doctype] dt
INNER JOIN hsi.itemtypegroup dtg ON dt.itemtypegroupnum = dtg.itemtypegroupnum
</code>```

My Out put looks great I just need some advice so i can cut some SQL lines away if you know what i mean :)

答:
You can do it like this:

```<code>SELECT dtg.itemtypegroupname AS 'DTG', dt.itemtypename AS 'DT',
( SELECT 'A' + CASE WHEN itxk.keyreq = 1 THEN ', R' ELSE '' END
             + CASE WHEN itxk.readonly = 1 THEN ', RO' ELSE '' END
             + CASE WHEN itxk.hidden = 1 THEN ', H' ELSE '' END
FROM    [x].[itemtypexkeyword] itxk
WHERE   itxk.itemtypenum = dt.itemtypenum
AND     itxk.keytypenum = 112
) AS Keyword1
FROM [x].[doctype] dt
INNER JOIN x.itemtypegroup dtg ON dt.itemtypegroupnum = dtg.itemtypegroupnum
</code>```

Or with IIF():

```<code>SELECT dtg.itemtypegroupname AS 'DTG', dt.itemtypename AS 'DT',
( SELECT 'A' + IIF( itxk.keyreq = 1, ', R', '')
             + IIF( itxk.readonly = 1, ', RO', '')
             + IIF( itxk.hidden = 1, ', H', '')
FROM    [x].[itemtypexkeyword] itxk
WHERE   itxk.itemtypenum = dt.itemtypenum
AND     itxk.keytypenum = 112
) AS Keyword1
FROM [x].[doctype] dt
INNER JOIN x.itemtypegroup dtg ON dt.itemtypegroupnum = dtg.itemtypegroupnum
</code>```

Above solutions will increase readability but not performance.

Body:
I want to make dynamic representation of the settings of the system from my DataBase. Before I manually edited a Excel spreadsheet with the new configration.

I've created a Case statement with 8 different possible configuration from my system and the Case statement will at least be called 20 times with 20 unique ID's. f.eks. = 112 AS keyword1, = 113 AS keyword2, etc.

So now I've done some research and I've made some nice progress but now my question is:
Whats the best way to optimize my query?

-- Quick overview of all case conditions
-- 1. 'A,R,RO,H'
-- 2. 'A,R,H'
-- 3. 'A,R,RO'
-- 4. 'A,R'
-- 5. 'A,RO,H
-- 6. 'A,RO'
-- 7. 'A,H'
-- 8. 'A'

SELECT dtg.itemtypegroupname AS 'DTG', dt.itemtypename AS 'DT',
(SELECT (CASE
-- 1)
WHEN itxk.keyreq = 1 AND itxk.readonly = 1 AND itxk.hidden = 1 THEN 'A,R,RO,H'
-- 2)
WHEN itxk.keyreq = 1 AND itxk.readonly = 0 AND itxk.hidden = 1 THEN 'A,R,H'
-- 3)
WHEN itxk.keyreq = 1 AND itxk.readonly = 1 AND itxk.hidden = 0 THEN 'A,R,RO'
-- 4)
WHEN itxk.keyreq = 1 AND itxk.readonly = 0 AND itxk.hidden = 0 THEN 'A,R'
-- 5)
WHEN itxk.keyreq = 0 AND itxk.readonly = 1 AND itxk.hidden = 1 THEN 'A,RO,H'
-- 6)
WHEN itxk.keyreq = 0 AND itxk.readonly = 1 AND itxk.hidden = 0 THEN 'A,RO'
-- 7)
WHEN itxk.keyreq = 0 AND itxk.readonly = 0 AND itxk.hidden = 1 THEN 'A,H'
-- 8)
WHEN itxk.keyreq = 0 AND itxk.readonly = 0 AND itxk.hidden = 0 THEN 'A'
 END)
 FROM [x].[itemtypexkeyword] itxk WHERE itxk.itemtypenum = dt.itemtypenum AND
itxk.keytypenum = 112) AS Keyword1
FROM [x].[doctype] dt
INNER JOIN x.itemtypegroup dtg ON dt.itemtypegroupnum = dtg.itemtypegroupnum

Within each CASE statement I'm going to have a FROM WHERE = 112 ETC.
Is there a way to minimize the amount of lines maybe to put the case into a variable or what's possible?

Below is what I dont want to do because of optimization.

SELECT dtg.itemtypegroupname AS 'DTG', dt.itemtypename AS 'DT',
(SELECT (CASE
-- 1)
WHEN itxk.keyreq = 1 AND itxk.readonly = 1 AND itxk.hidden = 1 THEN 'A,R,RO,H'
-- 2)
WHEN itxk.keyreq = 1 AND itxk.readonly = 0 AND itxk.hidden = 1 THEN 'A,R,H'
-- 3)
WHEN itxk.keyreq = 1 AND itxk.readonly = 1 AND itxk.hidden = 0 THEN 'A,R,RO'
-- 4)
WHEN itxk.keyreq = 1 AND itxk.readonly = 0 AND itxk.hidden = 0 THEN 'A,R'
-- 5)
WHEN itxk.keyreq = 0 AND itxk.readonly = 1 AND itxk.hidden = 1 THEN 'A,RO,H'
-- 6)
WHEN itxk.keyreq = 0 AND itxk.readonly = 1 AND itxk.hidden = 0 THEN 'A,RO'
-- 7)
WHEN itxk.keyreq = 0 AND itxk.readonly = 0 AND itxk.hidden = 1 THEN 'A,H'
-- 8)
WHEN itxk.keyreq = 0 AND itxk.readonly = 0 AND itxk.hidden = 0 THEN 'A'
 END)
 FROM [x].[itemtypexkeyword] itxk WHERE itxk.itemtypenum = dt.itemtypenum AND
itxk.keytypenum = 112) AS keyword1,
(SELECT (CASE
-- 1)
WHEN itxk.keyreq = 1 AND itxk.readonly = 1 AND itxk.hidden = 1 THEN 'A,R,RO,H'
-- 2)
WHEN itxk.keyreq = 1 AND itxk.readonly = 0 AND itxk.hidden = 1 THEN 'A,R,H'
-- 3)
WHEN itxk.keyreq = 1 AND itxk.readonly = 1 AND itxk.hidden = 0 THEN 'A,R,RO'
-- 4)
WHEN itxk.keyreq = 1 AND itxk.readonly = 0 AND itxk.hidden = 0 THEN 'A,R'
-- 5)
WHEN itxk.keyreq = 0 AND itxk.readonly = 1 AND itxk.hidden = 1 THEN 'A,RO,H'
-- 6)
WHEN itxk.keyreq = 0 AND itxk.readonly = 1 AND itxk.hidden = 0 THEN 'A,RO'
-- 7)
WHEN itxk.keyreq = 0 AND itxk.readonly = 0 AND itxk.hidden = 1 THEN 'A,H'
-- 8)
WHEN itxk.keyreq = 0 AND itxk.readonly = 0 AND itxk.hidden = 0 THEN 'A'
 END)
 FROM [x].[itemtypexkeyword] itxk WHERE itxk.itemtypenum = dt.itemtypenum AND
itxk.keytypenum = 113) AS keyword2
FROM [x].[doctype] dt
INNER JOIN hsi.itemtypegroup dtg ON dt.itemtypegroupnum = dtg.itemtypegroupnum

My Out put looks great I just need some advice so i can cut some SQL lines away if you know what i mean :)

Body:
You can do it like this:

SELECT dtg.itemtypegroupname AS 'DTG', dt.itemtypename AS 'DT',
( SELECT 'A' + CASE WHEN itxk.keyreq = 1 THEN ', R' ELSE '' END
             + CASE WHEN itxk.readonly = 1 THEN ', RO' ELSE '' END
             + CASE WHEN itxk.hidden = 1 THEN ', H' ELSE '' END
FROM    [x].[itemtypexkeyword] itxk
WHERE   itxk.itemtypenum = dt.itemtypenum
AND     itxk.keytypenum = 112
) AS Keyword1
FROM [x].[doctype] dt
INNER JOIN x.itemtypegroup dtg ON dt.itemtypegroupnum = dtg.itemtypegroupnum

Or with IIF():

SELECT dtg.itemtypegroupname AS 'DTG', dt.itemtypename AS 'DT',
( SELECT 'A' + IIF( itxk.keyreq = 1, ', R', '')
             + IIF( itxk.readonly = 1, ', RO', '')
             + IIF( itxk.hidden = 1, ', H', '')
FROM    [x].[itemtypexkeyword] itxk
WHERE   itxk.itemtypenum = dt.itemtypenum
AND     itxk.keytypenum = 112
) AS Keyword1
FROM [x].[doctype] dt
INNER JOIN x.itemtypegroup dtg ON dt.itemtypegroupnum = dtg.itemtypegroupnum

Above solutions will increase readability but not performance.


问:
Local authentication problem in release apk flutter
I have faced this issue recently. The local authentication would work flawlessly on flutter run and  --release, --profile . But when I make the APK and then install it, the local auth does not work, the app crashes. There is no error in the app when i run the same app but when the cable is connected to my computer.

Here, the function call begins,

```<code>onPressed: () {
                              bool enable = preferences.getBool('bioAuth');
                              if (enable == null || enable == false) {
                                showSnack('Biometric Auth not Enabled...');
                              } else {
                                biometricLogin(
                                    context: context, mainCol: mainCol);
                              }

                            },
</code>```

Here is the biometricLogin Function.

```<code>void biometricLogin({context, mainCol}) async {
bool authenticated =
    await checkBiometric(context: context, mainCol: mainCol);

if (authenticated == null || authenticated == false) {
  showSnack('BioAuth not valid...');
} else {
  bool isGoogle = preferences.getBool('googleSignIn');
  bool isApple = preferences.getBool('appleSignin');
  if (isGoogle) {
    showSnack('Logging in...');
    User user = await _auth.signInWIthGoogleCreds();
    print(user);
    if (user == null) {
      showSnack('Try logging in through Google again...');
    }
  } else if (isApple) {
    showSnack('Logging in...');
    User user = await _auth.signInWIthAppleCreds();
    print(user);
    if (user == null) {
      showSnack('Try logging in through Apple again...');
    }
  } else {
    User user;
    showSnack('Logging in...');
    var email = preferences.getString('email');
    var password = preferences.getString('pass');
    user = await _auth.signIn(email, password);
    if (user != null) {
      await preferences.setBool('loggedIn', true);
    } else {
      showSnack('Something went wrong');
    }
  }
}
</code>```

}

And here is checkBiometrics function .

```<code>Future<bool> checkBiometric({context, mainCol}) async {
if (bioAuth == null || bioAuth == false) {
  showSnack('Biometrics not Enabled');
  return false;
} else {
  try {
    canCheckBiometrics = await auth.canCheckBiometrics;
    if (!mounted) return false;
    List<BiometricType> availableBiometrics;
    availableBiometrics = await auth.getAvailableBiometrics();
    bool authenticated = false;
    if (Platform.isIOS) {
      const iosStrings = const IOSAuthMessages(
          cancelButton: 'cancel',
          goToSettingsButton: 'settings',
          goToSettingsDescription: 'Please set up your Touch ID.',
          lockOut: 'Please re-enable your Touch ID');
      if (availableBiometrics.contains(BiometricType.face) ||
          availableBiometrics.contains(BiometricType.fingerprint)) {
        authenticated = await auth.authenticateWithBiometrics(
          localizedReason: "Please authenticate to login",
          useErrorDialogs: true,
          iOSAuthStrings: iosStrings,
          stickyAuth: true,
        );
      } else
        authenticated = false;
    } else {
      authenticated = await auth.authenticateWithBiometrics(
        localizedReason: 'Touch your finger on the sensor to login',
        useErrorDialogs: true,
        stickyAuth: true,
      );
    }
    return authenticated;
  } catch (e) {
    showSnack("error using biometric auth: $e");
  }
  setState(() {
    authenticated = authenticated ? true : false;
  });
  return authenticated;
}
</code>```

}

As far as I understand. The app doesnot goes ahead of checkBiometrics, because it crashes just by pressing the button.

答:
On Android, you can check only for the existence of fingerprint hardware prior to API 29 (Android Q). Therefore, if you would like to support other biometrics types (such as face scanning) and you want to support SDKs lower than Q, do not call getAvailableBiometrics. Simply call authenticate with biometricOnly: true. This will return an error if there was no hardware available.

check this out

Body:
I have faced this issue recently. The local authentication would work flawlessly on flutter run and  --release, --profile . But when I make the APK and then install it, the local auth does not work, the app crashes. There is no error in the app when i run the same app but when the cable is connected to my computer.

Here, the function call begins,

onPressed: () {
                              bool enable = preferences.getBool('bioAuth');
                              if (enable == null || enable == false) {
                                showSnack('Biometric Auth not Enabled...');
                              } else {
                                biometricLogin(
                                    context: context, mainCol: mainCol);
                              }

                            },

Here is the biometricLogin Function.

void biometricLogin({context, mainCol}) async {
bool authenticated =
    await checkBiometric(context: context, mainCol: mainCol);

if (authenticated == null || authenticated == false) {
  showSnack('BioAuth not valid...');
} else {
  bool isGoogle = preferences.getBool('googleSignIn');
  bool isApple = preferences.getBool('appleSignin');
  if (isGoogle) {
    showSnack('Logging in...');
    User user = await _auth.signInWIthGoogleCreds();
    print(user);
    if (user == null) {
      showSnack('Try logging in through Google again...');
    }
  } else if (isApple) {
    showSnack('Logging in...');
    User user = await _auth.signInWIthAppleCreds();
    print(user);
    if (user == null) {
      showSnack('Try logging in through Apple again...');
    }
  } else {
    User user;
    showSnack('Logging in...');
    var email = preferences.getString('email');
    var password = preferences.getString('pass');
    user = await _auth.signIn(email, password);
    if (user != null) {
      await preferences.setBool('loggedIn', true);
    } else {
      showSnack('Something went wrong');
    }
  }
}

}

And here is checkBiometrics function .

Future<bool> checkBiometric({context, mainCol}) async {
if (bioAuth == null || bioAuth == false) {
  showSnack('Biometrics not Enabled');
  return false;
} else {
  try {
    canCheckBiometrics = await auth.canCheckBiometrics;
    if (!mounted) return false;
    List<BiometricType> availableBiometrics;
    availableBiometrics = await auth.getAvailableBiometrics();
    bool authenticated = false;
    if (Platform.isIOS) {
      const iosStrings = const IOSAuthMessages(
          cancelButton: 'cancel',
          goToSettingsButton: 'settings',
          goToSettingsDescription: 'Please set up your Touch ID.',
          lockOut: 'Please re-enable your Touch ID');
      if (availableBiometrics.contains(BiometricType.face) ||
          availableBiometrics.contains(BiometricType.fingerprint)) {
        authenticated = await auth.authenticateWithBiometrics(
          localizedReason: "Please authenticate to login",
          useErrorDialogs: true,
          iOSAuthStrings: iosStrings,
          stickyAuth: true,
        );
      } else
        authenticated = false;
    } else {
      authenticated = await auth.authenticateWithBiometrics(
        localizedReason: 'Touch your finger on the sensor to login',
        useErrorDialogs: true,
        stickyAuth: true,
      );
    }
    return authenticated;
  } catch (e) {
    showSnack("error using biometric auth: $e");
  }
  setState(() {
    authenticated = authenticated ? true : false;
  });
  return authenticated;
}

}

As far as I understand. The app doesnot goes ahead of checkBiometrics, because it crashes just by pressing the button.


问:
recording `open` syscalls on mac
I would like to know what calls are made to open(2) in a bash script.

I wrote the following program which intercepts syscalls:

#include <fcntl.h>
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>

#define DYLD_INTERPOSE(_replacment,_replacee) \
__attribute__((used)) static struct{ const void* replacment; const void* replacee; } _interpose_##_replacee \
__attribute__ ((section ("__DATA,__interpose"))) = { (const void*)(unsigned long)&_replacment, (const void*)(unsigned long)&_replacee };

static
int
my_open(const char *filename, int oflag, mode_t mode)
{
    printf("$jason$ open: %s\n", filename);
    return open(filename, oflag, mode);
}
DYLD_INTERPOSE(my_open, open)
```
<p>Which I then ran using:</p>
<pre class="lang-sh prettyprint-override"><code>clang -dynamiclib libfile.c -o libfile.dylib
export DYLD_INSERT_LIBRARIES=libfile.dylib
touch /tmp/testingtesting
</code>```

It doesn't work.

I tried it with a program that I compiled and it works fine. I tried it with programs compiled by brew and it works fine. I read the source code for touch.c. It calls open(2).

I then disabled SIP and it worked fine. So, I concluded that it was SIP that was causing the problem. I don't want to disable SIP though.

What should I do? I was thinking about just allowing dtrace: csrutil enable --without dtrace. Because I think dtrace can track syscalls but I'm not sure if that is a safe option.

答:
General library injection has become essentially unsupported on recent versions of macOS.

You can however indeed do this with dtrace as you suspect, specifically the dtruss script. Unfortunately, the version of this script that ships with macOS is rather stale, so I'd recommend using my updated version of dtruss¹ as this will let you trace all sub-processes, which is pretty essential if you're tracing shell scripts. It also avoids having to run the command you're trying to trace with sudo, which might make it behave differently.

This command…

path/to/dtruss -d -e -f -t open  touch /tmp/testingtesting

…should work fine with the linked version. Explanation of the command line:

-d and -e show call timings. (Optional)

-f enables "follow" mode for also tracing spawned sub-processes - this isn't really interesting for the touch command, but you'll probably need it for tracing a bash script.

-t open limits tracing to the open syscall. (Leave this off to trace all syscalls. Caution: this could produce a LOT of output.)

With the stock version of dtruss, you can fall back to:

sudo dtruss -d -e -t open  touch /tmp/testingtesting - but notice that touch will be run as the root user in this case, and tracing sub-processes is not supported.

sudo dtruss -d -e -t open -n touch, and then run touch /tmp/testingtesting in another terminal. This avoids running touch as root, but it will trace all processes named touch.

The output of the traced syscalls will probably also be less clear when using the original version of dtruss as the updated version does a better job of formatting syscall arguments, particularly strings. (For open() specifically, the updated version prints the 'mode' argument for created file permisions as octal, which is usually what you want.)

And yes, you'll need to disable the dtrace portion of SIP for all features of dtrace to work, and this probably does open a small security risk, but I've not heard of any malware that attempts to exploit this.

Footnotes:

¹ I am not trying to self-promote my code. I simply don't know of a better solution - I had a very similar problem to the asker, and the built-in tool was not good enough, so I fixed it.

Title: recording `open` syscalls on mac

Body:
I would like to know what calls are made to open(2) in a bash script.

I wrote the following program which intercepts syscalls:

#include <fcntl.h>
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>

#define DYLD_INTERPOSE(_replacment,_replacee) \
__attribute__((used)) static struct{ const void* replacment; const void* replacee; } _interpose_##_replacee \
__attribute__ ((section ("__DATA,__interpose"))) = { (const void*)(unsigned long)&_replacment, (const void*)(unsigned long)&_replacee };

static
int
my_open(const char *filename, int oflag, mode_t mode)
{
    printf("$jason$ open: %s\n", filename);
    return open(filename, oflag, mode);
}
DYLD_INTERPOSE(my_open, open)

Which I then ran using:

clang -dynamiclib libfile.c -o libfile.dylib
export DYLD_INSERT_LIBRARIES=libfile.dylib
touch /tmp/testingtesting

It doesn't work.

I tried it with a program that I compiled and it works fine. I tried it with programs compiled by brew and it works fine. I read the source code for touch.c. It calls open(2).

I then disabled SIP and it worked fine. So, I concluded that it was SIP that was causing the problem. I don't want to disable SIP though.

What should I do? I was thinking about just allowing dtrace: csrutil enable --without dtrace. Because I think dtrace can track syscalls but I'm not sure if that is a safe option.


问:
How to find all the services attached to a default security group in AWS?
I am willing to make some changes to the rules of the default security groups in Production Environment of an AWS account to be compliant to some config rules. To know the impact after the changes made and then testing needs to be done on those parts. To reduce the efforts for testing, it will be better to know of all the services that can take a hit.

Thus, I need to find which are the different Amazon Web Services attached to the default security group in my custom VPC. Is there any AWS CLI command or any way from the AWS Console that I can find out all the different services (like EC2, RDS, etc.) attached to the default security group.

The Network interfaces (ENI) in EC2 Console only shows if an EC2 instance is attached. How to check if the security group is attached to other services?

Please let me know.

Thank you :)

答:
There is a possible solution, you can list all Security groups in AWS cli with your target information then run again its output to list vpcinfo for all the VPC.

here in action!!

```<code>aws ec2 describe-security-groups |grep 'GroupName\|VpcId\|GroupId' #listing all SG with info groupName/ID,vpcID.
</code>```

output of listing all SG info
now can run below one liner script to fetch all VPC info

```<code>aws ec2 describe-security-groups |grep 'GroupName\|VpcId\|GroupId' > list_sg_info.txt ; cat list_sg_info.txt|grep -i vpcid |sort -u |awk '{print $NF}'|tr '\"' ' '|while read vpcinfo; do  aws ec2 describe-vpcs --vpc-ids $vpcinfo|nl ; done
</code>```

Body:
There is a possible solution, you can list all Security groups in AWS cli with your target information then run again its output to list vpcinfo for all the VPC.

here in action!!

aws ec2 describe-security-groups |grep 'GroupName\|VpcId\|GroupId' #listing all SG with info groupName/ID,vpcID.

output of listing all SG info
now can run below one liner script to fetch all VPC info

aws ec2 describe-security-groups |grep 'GroupName\|VpcId\|GroupId' > list_sg_info.txt ; cat list_sg_info.txt|grep -i vpcid |sort -u |awk '{print $NF}'|tr '\"' ' '|while read vpcinfo; do  aws ec2 describe-vpcs --vpc-ids $vpcinfo|nl ; done


问:
How to completely disable Elasticsearch chaching?
I'm trying to measure Elasticsearch performance for some queries and make a benchmark. I'm looking for a way to completely disable the cache. I've already tried some ways but always my first request takes longer than the next queries. So I think even I disabled the cache, at some level it is still working! I've tried this:

1- GET my_index/_search?request_cache=false

2- POST /my_index/_cache/clear

3-

```<code> PUT /my_index/_settings
{ "index.requests.cache.enable": false }
</code>```

答:
I think you are disabling the elasticsearch cache correctly. the problem is that there is filesystem cache memory at OS level that you cannot disable it easily. every files and segment that have been read from harddisk will be cached in memory until new segment and files arrived. you can check this cache via free -g command and buffer column.
you can clear memory page cache via below command:

```<code># sync; echo 3 > /proc/sys/vm/drop_caches
</code>```

Body:
I'm trying to measure Elasticsearch performance for some queries and make a benchmark. I'm looking for a way to completely disable the cache. I've already tried some ways but always my first request takes longer than the next queries. So I think even I disabled the cache, at some level it is still working! I've tried this:

1- GET my_index/_search?request_cache=false

2- POST /my_index/_cache/clear

3-

 PUT /my_index/_settings
{ "index.requests.cache.enable": false }

Body:
I think you are disabling the elasticsearch cache correctly. the problem is that there is filesystem cache memory at OS level that you cannot disable it easily. every files and segment that have been read from harddisk will be cached in memory until new segment and files arrived. you can check this cache via free -g command and buffer column.
you can clear memory page cache via below command:

# sync; echo 3 > /proc/sys/vm/drop_caches


问:
Persistence for Hashmap<Integer,Object>
I'm getting these errors trying to mapping a Hashmap
i dont know how to solve this.
Netbeans 8.1
Jpa 2.1

Mapping

```<code>@Entity
@Table(name = "libros")
public class Libro implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "idlibro", nullable = false)
private int idlibro;

@Column(name = "isbn", nullable = false, length = 50, unique = true)
private long isbn;

@Column(name = "titulo", nullable = false, length = 200, unique = false)
private String titulo;

@Column(name = "anio", nullable = true, length = 4, unique = false)
private int anio;

@Column(name = "idioma", nullable = true, length = 50, unique = false)
private String idioma;

@JoinColumn(name = "idautor", referencedColumnName = "idautor", insertable=false, updatable=true)
@ManyToOne(optional = false)
private Autor elautor;

@Column(name = "genero", nullable = true, length = 50, unique = false)
private String genero;

@JoinColumn(name = "ideditorial", referencedColumnName = "ideditorial", insertable=false, updatable=true)
@ManyToOne(optional = false)
private Editorial laeditorial;

@ElementCollection
@MapKeyColumn(name="nrocopia")
@Column(name="ejemplares")
@CollectionTable(name="ejemplares", joinColumns=@JoinColumn(name="idejemplar"))
private HashMap<Integer, Ejemplar> ejemplarlibro;

@Column(name = "estado", nullable = true, length = 50, unique = false)
private String estado;
</code>```

Exception in thread "main" javax.persistence.PersistenceException: Exception        [EclipseLink-28019] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [BibliotecaTPFINALPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.IntegrityException

Descriptor Exceptions:

Exception [EclipseLink-138] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The attribute [ejemplarlibro] is of type [class java.util.HashMap] but the mapping uses transparent indirection (lazy loading), requiring it to be a superclass of [IndirectMap].
Mapping: org.eclipse.persistence.mappings.DirectMapMapping[ejemplarlibro]
Descriptor: RelationalDescriptor(Clases.Libro --> [DatabaseTable(libros)])

Runtime Exceptions:

```<code>at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createDeployFailedPersistenceException(EntityManagerSetupImpl.java:820)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:760)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:204)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getDatabaseSession(EntityManagerFactoryDelegate.java:182)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getDatabaseSession(EntityManagerFactoryImpl.java:527)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:140)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:177)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at Jpa.ControladorPersistencia.getEmf(ControladorPersistencia.java:20)
at Controladores.BibliotecaControlador.<init>(BibliotecaControlador.java:54)
at bibliotecatpfinal.BibliotecaMain.main(BibliotecaMain.java:46)
</code>```

Caused by: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [BibliotecaTPFINALPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:

答:
As @Neil Stockton says in his comment. The solution is to change your declaration of HashMap to the interface Map

```<code>private HashMap<Integer, Ejemplar> ejemplarlibro;
</code>```

becomes

```<code>private Map<Integer, Ejemplar> ejemplarlibro;
</code>```

Title: Persistence for Hashmap<Integer,Object>

Body:
I'm getting these errors trying to mapping a Hashmap
i dont know how to solve this.
Netbeans 8.1
Jpa 2.1

Mapping

@Entity
@Table(name = "libros")
public class Libro implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "idlibro", nullable = false)
private int idlibro;

@Column(name = "isbn", nullable = false, length = 50, unique = true)
private long isbn;

@Column(name = "titulo", nullable = false, length = 200, unique = false)
private String titulo;

@Column(name = "anio", nullable = true, length = 4, unique = false)
private int anio;

@Column(name = "idioma", nullable = true, length = 50, unique = false)
private String idioma;

@JoinColumn(name = "idautor", referencedColumnName = "idautor", insertable=false, updatable=true)
@ManyToOne(optional = false)
private Autor elautor;

@Column(name = "genero", nullable = true, length = 50, unique = false)
private String genero;

@JoinColumn(name = "ideditorial", referencedColumnName = "ideditorial", insertable=false, updatable=true)
@ManyToOne(optional = false)
private Editorial laeditorial;

@ElementCollection
@MapKeyColumn(name="nrocopia")
@Column(name="ejemplares")
@CollectionTable(name="ejemplares", joinColumns=@JoinColumn(name="idejemplar"))
private HashMap<Integer, Ejemplar> ejemplarlibro;

@Column(name = "estado", nullable = true, length = 50, unique = false)
private String estado;

Exception in thread "main" javax.persistence.PersistenceException: Exception        [EclipseLink-28019] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [BibliotecaTPFINALPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.IntegrityException

Descriptor Exceptions:

Exception [EclipseLink-138] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The attribute [ejemplarlibro] is of type [class java.util.HashMap] but the mapping uses transparent indirection (lazy loading), requiring it to be a superclass of [IndirectMap].
Mapping: org.eclipse.persistence.mappings.DirectMapMapping[ejemplarlibro]
Descriptor: RelationalDescriptor(Clases.Libro --> [DatabaseTable(libros)])

Runtime Exceptions:

at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createDeployFailedPersistenceException(EntityManagerSetupImpl.java:820)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:760)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:204)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getDatabaseSession(EntityManagerFactoryDelegate.java:182)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getDatabaseSession(EntityManagerFactoryImpl.java:527)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:140)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:177)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at Jpa.ControladorPersistencia.getEmf(ControladorPersistencia.java:20)
at Controladores.BibliotecaControlador.<init>(BibliotecaControlador.java:54)
at bibliotecatpfinal.BibliotecaMain.main(BibliotecaMain.java:46)

Caused by: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [BibliotecaTPFINALPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:

Body:
As @Neil Stockton says in his comment. The solution is to change your declaration of HashMap to the interface Map

private HashMap<Integer, Ejemplar> ejemplarlibro;

becomes

private Map<Integer, Ejemplar> ejemplarlibro;


问:
Why "message here" text seems like bold
I'm using jQuery to append
, and it's appending an extra close icon but I can't see why. If you run the code snippet below and click on "Add more" link, you'll see an additional times (x) icon, and the "message here" text seems bolded.

$(function() {

  $("#add").click(function() {
    $('

<input type="text" class="form-control" placeholder="Domain">

 message here

').appendTo("#DomainsList");
  });

  $("#DomainsList").on("click", ".remove", function() {
    $(this).closest('.domainName').remove();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<section id="DomainsList">
  <div class="row">
    <div class="col">
      <div class="input-group mb-2">
        <span class="input-group-text bg-white"><i class="fas fa-lock text-secondary"></i></span>
        <input type="text" class="form-control" placeholder="Domains">
      </div>
    </div>
    <div class="col">message here</div>
  </div>
</section>
<i class="fas fa-plus-circle"></i> Add More</code>```

答:
Little problem is interrupt your output. Your starting tag is  and closing tag is
 while you append message block inside #DomainsList that is the problem.

Look here for how to create and append multiple elements in jQuery, it's make your code easy to read

jQuery create and append multiple elements

Change:

```<code><i class="fas fa-times"></li>
</code>```

To:

```<code><i class="fas fa-times"></i>
</code>```

Here down is modified code:

$(function() {
  $("#add").click(function() {
    var appendBlock = '
' +
                            '
' +
                                '
' +
                                    '' +
                                        '' +
                                    '' +
                                    '<input type="text" class="form-control" placeholder="Domain">' +
                                    '' +
                                        '' +
                                            '' +
                                        '' +
                                    '' +
                                '
' +
                            '
' +
                            '
 message here
' +
                        '
';

    $("#DomainsList").append(appendBlock);
  });

  $("#DomainsList").on("click", ".remove", function() {
    $(this).closest('.domainName').remove();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<section id="DomainsList">
  <div class="row">
    <div class="col">
      <div class="input-group mb-2">
        <span class="input-group-text bg-white"><i class="fas fa-lock text-secondary"></i></span>
        <input type="text" class="form-control" placeholder="Domains">
      </div>
    </div>
    <div class="col">message here</div>
  </div>
</section>
<i class="fas fa-plus-circle"></i> Add More</code>```

Title: Why "message here" text seems like bold

Body:
I'm using jQuery to append
, and it's appending an extra close icon but I can't see why. If you run the code snippet below and click on "Add more" link, you'll see an additional times (x) icon, and the "message here" text seems bolded.

$(function() {

  $("#add").click(function() {
    $('

<input type="text" class="form-control" placeholder="Domain">

 message here

').appendTo("#DomainsList");
  });

  $("#DomainsList").on("click", ".remove", function() {
    $(this).closest('.domainName').remove();
  });
});

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

        <input type="text" class="form-control" placeholder="Domains">

message here

 Add More

Body:
Little problem is interrupt your output. Your starting tag is <i> and closing tag is <li> while you append message block inside #DomainsList that is the problem.

Look here for how to create and append multiple elements in jQuery, it's make your code easy to read

jQuery create and append multiple elements

Change:

<i class="fas fa-times"></li>

To:

<i class="fas fa-times"></i>

Here down is modified code:

$(function() {
  $("#add").click(function() {
    var appendBlock = '<div class="row domainName">' +
                            '<div class="col">' +
                                '<div class="input-group mb-2">' +
                                    '<span class="input-group-text bg-white">' +
                                        '<i class="fas fa-lock text-secondary"></i>' +
                                    '</span>' +
                                    '<input type="text" class="form-control" placeholder="Domain">' +
                                    '<span class="remove input-group-text bg-white">' +
                                        '<a href="javascript:void(0);">' +
                                            '<i class="fas fa-times"></i>' +
                                        '</a>' +
                                    '</span>' +
                                '</div>' +
                            '</div>' +
                            '<div class="col"> message here </div>' +
                        '</div>';

    $("#DomainsList").append(appendBlock);
  });

  $("#DomainsList").on("click", ".remove", function() {
    $(this).closest('.domainName').remove();
  });
});

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<section id="DomainsList">
  <div class="row">
    <div class="col">
      <div class="input-group mb-2">
        <span class="input-group-text bg-white"><i class="fas fa-lock text-secondary"></i></span>
        <input type="text" class="form-control" placeholder="Domains">
      </div>
    </div>
    <div class="col">message here</div>
  </div>
</section>
<a href="javascript:void(0);" id="add"><i class="fas fa-plus-circle"></i> Add More</a>


答:
A rebase works the way that the base of a branch (the point where the branch diverts from other branches) is modified to another commit. Thats what gives the operation it's name. The operation therefore changes the commit (including new timestamp) and it therefore has a new hash. Simply speaking, it is a complete new commit that is being created.

Since all following commits are dependent on the previous commit they need to be changed aswell, otherwise your history would be completely broken. For that reason, there are multiple steps involved (one per commit).

Apart from that, a rebase offers you more options like squashing commits together, edit commit messages, or picking/skipping specific commits. Obviously you cannot do this in one step, so it is being done step by step.

Title: Why is git doing a rebase in multiple steps?


问:
Regular Expression for UpperCase Letters In A String
For the life of me, I can't figure out why this regular expression is not working. It should find upper case letters in the given string and give me the count. Any ideas are welcome.

Here is the unit test code:

```<code>public class RegEx {

    @Test
    public void testCountTheNumberOfUpperCaseCharacters() {
        String testStr = "abcdefghijkTYYtyyQ";
        String regEx = "^[A-Z]+$";

        Pattern pattern = Pattern.compile(regEx);

        Matcher matcher = pattern.matcher(testStr);

        System.out.printf("Found %d, of capital letters in %s%n", matcher.groupCount(), testStr);

    }
}
</code>```

答:
Here's a solution for Java 9 and later that makes use of the results() method of Matcher, which returns a stream of the results, out of which the entries can be counted. The suggestion from @Sergey Kalinichenko to remove the ^ and $ anchors has also been incorporated into the regex string.

```<code>public class RegEx {
 @Test
 public void testCountTheNumberOfUpperCaseCharacters() {
    String testStr = "abcdefghijkTYYtyyQ";
    String regEx = "\\p{Lu}";

    Pattern pattern = Pattern.compile(regEx);
    Matcher matcher = pattern.matcher(testStr);
    long count = matcher.results().count();

    System.out.printf("Found %d of capital letters in %s%n", count, testStr);

 }
}
</code>```

Body:
For the life of me, I can't figure out why this regular expression is not working. It should find upper case letters in the given string and give me the count. Any ideas are welcome.

Here is the unit test code:

public class RegEx {

    @Test
    public void testCountTheNumberOfUpperCaseCharacters() {
        String testStr = "abcdefghijkTYYtyyQ";
        String regEx = "^[A-Z]+$";

        Pattern pattern = Pattern.compile(regEx);

        Matcher matcher = pattern.matcher(testStr);

        System.out.printf("Found %d, of capital letters in %s%n", matcher.groupCount(), testStr);

    }
}

Body:
Here's a solution for Java 9 and later that makes use of the results() method of Matcher, which returns a stream of the results, out of which the entries can be counted. The suggestion from @Sergey Kalinichenko to remove the ^ and $ anchors has also been incorporated into the regex string.

public class RegEx {
 @Test
 public void testCountTheNumberOfUpperCaseCharacters() {
    String testStr = "abcdefghijkTYYtyyQ";
    String regEx = "\\p{Lu}";

    Pattern pattern = Pattern.compile(regEx);
    Matcher matcher = pattern.matcher(testStr);
    long count = matcher.results().count();

    System.out.printf("Found %d of capital letters in %s%n", count, testStr);

 }
}


问:
Terrafrom import GCP IAM member from list of users
I want to import existing IAM users into terraform. I have created a module in the main.tf that looks like this

```<code>module "iam" {
  source = "./modules/iam"

  project_id      = var.project_id
  owners          = var.owners
}
</code>```

The variable is defined in the variable file as:

```<code> variable "owners" {
      type = list(string)
      default = [
        "user:test1@infarm.com",
        "user:test2@infarm.com",
      ]
    }
</code>```

The module itself contains a resource with a for_each loop as:

```<code>resource "google_project_iam_member" "owner" {
  role = "roles/owner"
  for_each = toset(concat(
    var.owners,
  ))
  member = each.value
}
</code>```

I have found the import statement from the terraform documentation and interpreted it as the following. According to the documentation this last part user:foo@example.com only applies to a single user. How can I adjust the import statement to apply to the variable list of users that I want?

```<code>terraform import module.iam.google_project_iam_member.owner "infarm-data roles/owner user:foo@example.com"
</code>```

答:
I found the answer to above import issue. The solution required two adjustments.

Reference to the specific item in the for_each loop ["user"] - as mentioned by @luk2302

quotes around the module statement to be interpreted correctly by the import (as shown below)

```<code>terraform import  'module.iam.google_project_iam_member.owner["user:foo@example.com"]' "infarm-data roles/owner user:foo@example.com"
</code>```

Hope this is helpful for someone else

Body:
I want to import existing IAM users into terraform. I have created a module in the main.tf that looks like this

module "iam" {
  source = "./modules/iam"

  project_id      = var.project_id
  owners          = var.owners
}

The variable is defined in the variable file as:

 variable "owners" {
      type = list(string)
      default = [
        "user:test1@infarm.com",
        "user:test2@infarm.com",
      ]
    }

The module itself contains a resource with a for_each loop as:

resource "google_project_iam_member" "owner" {
  role = "roles/owner"
  for_each = toset(concat(
    var.owners,
  ))
  member = each.value
}

I have found the import statement from the terraform documentation and interpreted it as the following. According to the documentation this last part user:foo@example.com only applies to a single user. How can I adjust the import statement to apply to the variable list of users that I want?

terraform import module.iam.google_project_iam_member.owner "infarm-data roles/owner user:foo@example.com"

Body:
I found the answer to above import issue. The solution required two adjustments.

Reference to the specific item in the for_each loop ["user"] - as mentioned by @luk2302

quotes around the module statement to be interpreted correctly by the import (as shown below)

terraform import  'module.iam.google_project_iam_member.owner["user:foo@example.com"]' "infarm-data roles/owner user:foo@example.com"

Hope this is helpful for someone else


问:
How to avoid permissions problems with node and nginx directory structure?
On my production server I'm successfully using nginx to host a static site and as a reverse proxy for a node app. Currently, the node app is in /home/myUserName/apps and the site is in /var/www/siteDomain.com/html.

On my local/development machine, the html directory is inside my apps directory (../apps/html). I want to have the same directory structure in production, so that I can clone my git repository and then just run npm install in case the package.json has changed (node_modules is in .gitignore).

I get permissions problems when using git and npm in /var/www/siteDomain.com because the owner is root and siteDomain.com is drwxr-xr-x. I can clone my repo using sudo git, but then all the subdirectories (including html) are owned by root which causes problems (would have to use sudo npm, which I read can make more problems, cannot manipulate files in ftp...).

The other way I could do it is clone the repo to /home/myUserName/apps, where everything is owned by my non-root user, and then change the nginx config file to point to /home/myUserName/apps/html as the root for the static site.

What is the best way to structure my directories so that I don't have permissions problems when using git and npm? Is pointing the html root to something outside of /var/www unusual or will it problems in the future?

P.S. my local machine is Windows, I'm not very experienced with linux (which is running on production server)

答:
You can create projects directory in /home/username/projectname

Run nginx without root permissions like described below.

Add/Change the following in your /etc/nginx/nginx.conf:

```<code>user nginx;
</code>```

You should create the user and grant permissions on the webroot directories recursively.

This way only master process runs as root. Because: Only root processes can listen to ports below 1024. A webserver typically runs at port 80 and/or 443. That means it needs to be started as root.

To run master process as non root user:

Change the ownership of the following:

```<code>    error_log
    access_log
    pid
    client_body_temp_path
    fastcgi_temp_path
    proxy_temp_path
    scgi_temp_path
    uwsgi_temp_path
</code>```

Change the listen directives to ports above 1024, log in as desired user and run nginx by nginx -c /path/to/nginx.conf.

And your node directory must be placed in /home/username/projectname.
Add node user, nginx user and git user to the common group and check projects permissions.

Body:
You can create projects directory in /home/username/projectname

Run nginx without root permissions like described below.

Add/Change the following in your /etc/nginx/nginx.conf:

user nginx;

You should create the user and grant permissions on the webroot directories recursively.

This way only master process runs as root. Because: Only root processes can listen to ports below 1024. A webserver typically runs at port 80 and/or 443. That means it needs to be started as root.

To run master process as non root user:

Change the ownership of the following:

    error_log
    access_log
    pid
    client_body_temp_path
    fastcgi_temp_path
    proxy_temp_path
    scgi_temp_path
    uwsgi_temp_path

Change the listen directives to ports above 1024, log in as desired user and run nginx by nginx -c /path/to/nginx.conf.

And your node directory must be placed in /home/username/projectname.
Add node user, nginx user and git user to the common group and check projects permissions.


问:
How memory allocation of variables or data in a program are done by compiler and OS
Want to get an overview on a few things about how exactly the memory for a variable is allocated.

In C programming,
Taking the context of "auto" variables, which are allocated on the stack section, I have the following question:

Does the compiler generate a logical address for the variables? If yes, then how? Won't the compiler need OS permission to generate or assign such addresses? If no, then is there some sort of indication or instruction that the compiler puts in the code segment asking the OS to allocate memory when running the executable?

Now taking the context of heap allocated variables,

Is the heap of the same size for all programs? If not, then does the executable consist of a header or something that tells the OS how much heap space it needs for dynamic allocation?

I'd be grateful if someone provides the answer or shares any related content/links that explains this.

答:
Does the compiler generate a logical address for the variables? If yes, then how?

Yes, but they are related to the stack pointer at function entry time (which is normally saved as a constant base pointer, stored in a cpu register)  This is because the function can be recursive, and you can have two calls to the function with different instances for that variable (and related to different copies of the base pointer), the compiler assigns the offset to the base pointer for the variable, but the base pointer can be different, depending on the stack contents at function entry time.

Won't the compiler need OS permission to generate or assign such addresses?

Nope, the compiler just generates an executable in the format and form needed for the operating system to manage process' memory.  When the program starts, it is given normally three (or more) segments of memory:

text segment. A normally read-only (or execute only) segment that gives no write access to the program.  This is normally because the text segment is shared between all programs that are using the same executable at the same time.  A program can demand exclusive read-write acces to the text (to allow programs that modify their own executable code) but this happens only rarely.  This is normally specified to the compiler and the compiler writes an special flag in the text segment to inform the kernel of this requirement.

Data segment.  A read-write segment, that can be grown by means of a system cal (sbrk(2)) This is used for global variables and the heap (while in modern systems, the heap is allocated into a new segment acquired by calling the mmap(2) system call.  Sometimes this segment is divided in two.  A data segment read-only for constants (so the program receives a signal in case you try to change the value of a constant) and a read-write segment, freely usable by the program.  This is where global variables are stored.

Stack segment.  A read-write segment, that is allocated for the process to use as the stack segment.  It has the capability of growing in one direction as the process starts using it.  When the process accesses the data one memory page below the start of the segment, it generates a page fault trap that results in a new page being appended to the segment, so its workings are transparent to the process.  This is the memory we are talking about.

the process can ask the kernel explicitly to get a new segment if it wants to (let's say it needs to map some file on memory, or if it has to load a shared executable/library) and on some systems, the read only variables (declared as const) are explititly stored in the text segment or in a specific section called .rodata that demands from the system a special data segment that is read-only.  The compiler doesn't normally code this kind of resource itself, it is normally encoded in the program being compiled.

The complete memory is limited by system imposed limits, so if you try to overpass them (around 8Mb of stack space, by default, and depending on the operating system) you will get signalled by the system and your program aborted.

As you see, the process memory is owned by the process, and it can make whatever use it is permitted to.  The stack memory is read/write, and allocated on demand, you can use up to 8Mb, but there's no provision to check  on the use you do about it.

If no, then is there some sort of indication or instruction that the compiler puts in the code segment asking the OS to allocate memory when running the executable?

The system will know the size of the text segment of the process by the size it has on the executable.  The data segment is divided into two parts, normally based on the assumption of what are the global initialized variables and what are the ones defaulting to zero (the memory allocated by the kernel to a process is initialized to zeros for security reasons) so the sum of both the initialized/data and the non initialized data sections are added to know how much memory to assign to the data segment.  And the stack segment is assigned initialy just one page of memory, but as the process starts running and filling the stack, it grows as the process generates page faults on the so called next page of the stack segment.  As you see, there's no nedd for the compiler to embed in the code any instruction to ask for more memory.  Everything is read from the executable file.

The compiler runs as a normal program... it only generates all this information and writes it in a file (the executable file) for the kernel to know the resources needed to run the program.  But the compiler's communication with the kernel is just to ask it to open files, write on them, read from source code and struggle it's head to achieve its task. :)

In most POSIX systems, the kernel loads a program in memory by means of the exec*(2) system calls.  The kernel reads the executable file pointed to in a parameter of the call and creates the segments above mentioned, based on the parameters passed in the file, checks if another instance of the same program is running in the system to avoid loading the instructions from the file and referencing in this process the segment already open by the other.  The data segment contents is initialized to zeros, and the contents of the initialization data are read into the segment (so the first part has the .data section of initialized global variables and the .bss section, which has only a size, is used to calculate the total size of the data segment).  Then the stack is normally allocated one or more pages, depending on the initial contents that the exec() calls put in the initial stack.  The initial stack is filled with:

a structure of data containing references to the program parameter list that was used on legacy systems to provide the kernel about the command line parameters to show in the ps(1) command output (this is still being generated for legacy purposes, but not used by the kernel for obvious security reasons)  Today, a special system call is used to indicate the kernel the command line parameters to be output in the ps(1) output.

a snippet of machine code to use in the return from a system call to allow the execution (in user mode) of any signal handler that should be executed (this is the reason for the requirement that all signal handlers are called when the kernel returns from kernel mode and switches back again to user mode, and not otherwise)

the environment of the process.

the array of pointers to environment strings.

the command line parameters.

the array of char pointers that point to the command line parameters.

the envp array referenct to main().

the argv array reference to the command line parameters.

the argc counter of the number of command line parameters.

Once all these data is pushed to the stack, the program jumps to the start address (fixed by the linker, or by the user by a linker option) and is let to start running.

Before the program jumps to main() the executed code is part of the C runtime, that loads a special shared executable (called /lib/ld.so or similar) that is responsible of searching and loading of all the shared libraries that are linked to the program.  Not all the programs have this feature (but almost all of them today are dynamically linked) but IMHO this is out of the scope to this question, as the program has already started and is running.


问:
Ingress to redirect to service from LB ip
I'm trying to create an Ingress rule to redirect requests from LoadBalancer to Service.

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: hostlessendpoint
spec:
  rules:
  - http:
      paths:
      - path: /hostless
        backend:
          serviceName: node-red
          servicePort: 1880
</code>```

The above yaml script is supposed to redirect all requests from https://LOAD_BALANCER_IP/hostless to node-red on port 1880

If I try to request the above URL, I got an error Cannot GET /hostless. Requesting the root gives 404 page not found.

I can access my services with the direct URL (eg. http://LOAD_BALANCER_IP:1880 will redirect to Node-red service).

Service yaml looks like that:

```<code>apiVersion: v1
kind: Service
metadata:
  labels:
    app: node-red
  name: node-red
spec:
  ports:
    - name: "1880"
      port: 1880
      protocol: TCP
      targetPort: 1880
  selector:
    app: node-red
  sessionAffinity: None
  type: LoadBalancer
</code>```

How to use ingress to reach a service whereas a custom port ?

答:
I've found a way to make it works !

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod
    traefik.ingress.kubernetes.io/redirect-entry-point: https
    kubernetes.io/ingress.class: "traefik"
    traefik.ingress.kubernetes.io/router.middlewares: "kube-system-traefik-stripprefix@kubernetescrd"
  name: traefik-all
  namespace: partner
spec:
  rules:
  - http:
      paths:
      - path: /
        backend:
          serviceName: nginx-demo
          servicePort: 2222
      - path: /node
        backend:
          serviceName: node-red
          servicePort: 1880
---
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: traefik-stripprefix
  namespace: kube-system
spec:
  stripPrefixRegex:
    regex:
      - "/[^/]+"
</code>```

I use a middleware to remove the prefix as K3S Traefik does not support the traefik.ingress.kubernetes.io/rewrite-target annotation.

With the above code, all trafic from LOAD_BALANCER_IP/* will be redirected to nginx-demo:2222 service. All trafic from LOAD_BALANCER_IP/node/* will be redicted to node-red:1880 service.

I hope this could help someone !

Body:
I'm trying to create an Ingress rule to redirect requests from LoadBalancer to Service.

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: hostlessendpoint
spec:
  rules:
  - http:
      paths:
      - path: /hostless
        backend:
          serviceName: node-red
          servicePort: 1880

The above yaml script is supposed to redirect all requests from https://LOAD_BALANCER_IP/hostless to node-red on port 1880

If I try to request the above URL, I got an error Cannot GET /hostless. Requesting the root gives 404 page not found.

I can access my services with the direct URL (eg. http://LOAD_BALANCER_IP:1880 will redirect to Node-red service).

Service yaml looks like that:

apiVersion: v1
kind: Service
metadata:
  labels:
    app: node-red
  name: node-red
spec:
  ports:
    - name: "1880"
      port: 1880
      protocol: TCP
      targetPort: 1880
  selector:
    app: node-red
  sessionAffinity: None
  type: LoadBalancer

How to use ingress to reach a service whereas a custom port ?

Body:
I've found a way to make it works !

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod
    traefik.ingress.kubernetes.io/redirect-entry-point: https
    kubernetes.io/ingress.class: "traefik"
    traefik.ingress.kubernetes.io/router.middlewares: "kube-system-traefik-stripprefix@kubernetescrd"
  name: traefik-all
  namespace: partner
spec:
  rules:
  - http:
      paths:
      - path: /
        backend:
          serviceName: nginx-demo
          servicePort: 2222
      - path: /node
        backend:
          serviceName: node-red
          servicePort: 1880
---
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: traefik-stripprefix
  namespace: kube-system
spec:
  stripPrefixRegex:
    regex:
      - "/[^/]+"

I use a middleware to remove the prefix as K3S Traefik does not support the traefik.ingress.kubernetes.io/rewrite-target annotation.

With the above code, all trafic from LOAD_BALANCER_IP/* will be redirected to nginx-demo:2222 service. All trafic from LOAD_BALANCER_IP/node/* will be redicted to node-red:1880 service.

I hope this could help someone !


问:
Which model/technique to use for specific sentence extraction?
I have a dataset of tens of thousands of dialogues / conversations between a customer and customer support. These dialogues, which could be forum posts, or long-winded email conversations, have been hand-annotated to highlight the sentence containing the customers problem. For example:

Dear agent, I am writing to you because I have a very annoying problem with my washing machine. I bought it three weeks ago and was very happy with it. However, this morning the door does not lock properly. Please help

Dear customer.... etc

The highlighted sentence would be:

However, this morning the door does not lock properly.

What approaches can I take to model this, so that in future I can automatically extract the customers problem? The domain of the datasets are broad, but within the hardware space, so it could be appliances, gadgets, machinery etc.

What is this type of problem called?
I thought this might be called "intent recognition", but most guides seem to refer to multiclass classification. The sentence either is or isn't the customers problem. I considered analysing each sentence and performing binary classification, but I'd like to explore options that take into account the context of the rest of the conversation if possible.

What resources are available to research how to implement this in Python (using tensorflow or pytorch)

I found a model on HuggingFace which has been pre-trained with customer dialogues, and have read the research paper, so I was considering fine-tuning this as a starting point, but I only have experience with text (multiclass/multilabel) classification when it comes to transformers.

答:
This type of problem where you want to extract the customer problem from the original text is called Extractive Summarization and this type of task is solved by Sequence2Sequence models.

The main reason for this type of model being called Sequence2Sequence is because the input and the output of this model would both be text.

I recommend you to use a transformers model called Pegasus which has been pre-trained to predict a masked text, but its main application is to be fine-tuned for text summarization (extractive or abstractive).

This Pegasus model is listed on Transformers library, which provides you with a simple but powerful way of fine-tuning transformers with custom datasets. I think this notebook will be extremely useful as guidance and for understanding how to fine-tune this Pegasus model.


问:
Why is Uint8List compatible with list<int> in dart?
I am a dart newbie.

Something strange I noticed while learning dart is that Uint8List seems to be compatible with List<int>.

For example, the IOSink.read() method accepts data of type List<int> as an argument. But it also seems to accept data of type Uint8List as argument directly.

What kind of mechanism is this? It doesn't really convert every byte in the Uint8List to int, does it? That would be very wasteful in terms of efficiency and memory usage.

答:
The Uint8List interface implements List<int>.

That means that it has an implementation of every member of List<int> with a signature that is compatible with List<int>.
It also means that Uint8List is a subtype of List<int> and a Uint8List instance can be used anywhere a List<int> instance is allowed or required.

Making Uint8List implement List<int> was easy, since a Uint8List is a list of (limited) integers, and because Dart only has one integer type, int, there is no problem distinguishing between a "byte" and an integer.

Any integer you read out of a Uint8List will be in the range 0..255.
Any integer you write into a Uint8List will be truncated to its first 8 bits before being stored. Storing the integer 257 into a Uint8List means actually storing the byte with value 1.

The read method will likely just use plain List methods for storing integers into the buffer. If that buffer happens to be a Uint8List, those integers are truncated and take up only a single byte. If not, it just stores integers (which happen to be in the range 0..255) into a List<int> as normal.