问:
Google APi + Passport + React : Authentication flow
I'm using passport to authenticate using Google API, I'm sending a token by URL to the client (React app) which saves it in the localStorage.

I want to use that token : With every API call (get, post, put) I want to send that token to the server , but I didn't know how to verify that token on the server side.

Passport Startegy :

```<code>app.use(passport.initialize()); // Used to initialize passport
app.use(passport.session()); // Used to persist login sessions

passport.use(new GoogleStrategy({
    clientID: 'IDxxxxx',
    clientSecret: 'SecreXXX',
    callbackURL: 'http://localhost:3000/callback'
},
(accessToken, refreshToken, profile, done) => {

    // Directory API here

    var userData = {
        name: profile.displayName,
        token: accessToken
       };

    done(null, userData);
</code>```

Authentication :

```<code>app.get('/auth/google', passport.authenticate('google', {
    scope: ['profile'] // Used to specify the required data
}));

// The middleware receives the data from Google and runs the function on Strategy config
app.get('/callback', passport.authenticate('google'), (req, res) => {
    var token = req.user.token;
    res.redirect("http://localhost:8000?token=" + token);
});
</code>```

API in express (which contains CRUD methods) :

```<code>app.use('/api', movieRouter)
</code>```

In react side : Getting the token

```<code>  componentWillMount() {
    var query = queryString.parse(this.props.location.search);
    if (query.token) {
      window.localStorage.setItem("jwt", query.token);
      // appel a directory api (avec token) puis sauvergarder dans redux puis redirection vers liste demandes
      this.props.history.push("/");
    }
  }
</code>```

Doing API calls :

```<code>import axios from 'axios'

const api = axios.create({
    baseURL: 'http://localhost:3000/api',
})

export const insertMovie = payload => api.post(`/movie`, payload)
</code>```

I just need to send the token in every call and check it in the server side.

Thanks

答:
If the token is correctly set in the header, session, or cookie by the client as noted by Bill Metcalf, then express is able to authenticate a route/endpoint by adding the passport.authenticate middleware function to the route, like so

```<code>app.use('/api', passport.authenticate('google', {failureRedirect:'/login'}), movieRouter)
</code>```

Refer to http://www.passportjs.org/docs/google/ for more information

Body:
I'm using passport to authenticate using Google API, I'm sending a token by URL to the client (React app) which saves it in the localStorage.

I want to use that token : With every API call (get, post, put) I want to send that token to the server , but I didn't know how to verify that token on the server side.

Passport Startegy :

app.use(passport.initialize()); // Used to initialize passport
app.use(passport.session()); // Used to persist login sessions

passport.use(new GoogleStrategy({
    clientID: 'IDxxxxx',
    clientSecret: 'SecreXXX',
    callbackURL: 'http://localhost:3000/callback'
},
(accessToken, refreshToken, profile, done) => {

    // Directory API here

    var userData = {
        name: profile.displayName,
        token: accessToken
       };

    done(null, userData);

Authentication :

app.get('/auth/google', passport.authenticate('google', {
    scope: ['profile'] // Used to specify the required data
}));

// The middleware receives the data from Google and runs the function on Strategy config
app.get('/callback', passport.authenticate('google'), (req, res) => {
    var token = req.user.token;
    res.redirect("http://localhost:8000?token=" + token);
});

API in express (which contains CRUD methods) :

app.use('/api', movieRouter)

In react side : Getting the token

  componentWillMount() {
    var query = queryString.parse(this.props.location.search);
    if (query.token) {
      window.localStorage.setItem("jwt", query.token);
      // appel a directory api (avec token) puis sauvergarder dans redux puis redirection vers liste demandes
      this.props.history.push("/");
    }
  }

Doing API calls :

import axios from 'axios'

const api = axios.create({
    baseURL: 'http://localhost:3000/api',
})

export const insertMovie = payload => api.post(`/movie`, payload)

I just need to send the token in every call and check it in the server side.

Thanks

Body:
If the token is correctly set in the header, session, or cookie by the client as noted by Bill Metcalf, then express is able to authenticate a route/endpoint by adding the passport.authenticate middleware function to the route, like so

app.use('/api', passport.authenticate('google', {failureRedirect:'/login'}), movieRouter)

Refer to http://www.passportjs.org/docs/google/ for more information


来源: stackexchange

问:
Python typehint for os.getenv causes downstream incompatible type errors
When using os.getenv to retrieve environment variables, the default behavior returns a type of Optional[str]. This is problematic as any downstream methods/functions that utilize these variables will likely be defined to accept a str type explicitly. Is there an accepted usage to get around this issue or enforce the str return type?

In the stub file definition for getenv in typeshed you can find that getenv can have a return type of Optional[str] or Union[str, T_] depending on the usage of the default kwarg.

The four options I can see as yet are:

Define any downstream operations to accept Optional[str] types as arguments. This doesn't feel particularly right as a function/method may not be structured in a way that the Optional type makes sense. i.e. the operation has no reason for a particular argument to be None.

Use the default kwarg for getenv and provide a str default value. This seems more correct, but requires that one set a default value for every usage of getenv. The only problem I can see with this is that doing so may be confounding for testing or usage in different environments.

Define some kind of variable checking function. This could be a function that accepts the name of an environment variable to load, explicitly returns a string, and raises an error if the environment variable doesn't exist.

Explicitly set the type of the value returned by getenv to be a str. I really don't like this as it expects the environment to always be properly configured which, in my experience, is not a good assumption.

Find below an example that raises a mypy error.

import os

SOME_VAR = os.getenv("SOME_VAR")

def some_func(val: str) -> None:
    print(f"Loaded env var: {val}")

some_func(SOME_VAR)
```

The above raises the mypy error:

error: Argument 1 to "some_func" has incompatible type "Optional[str]"; expected "str"

答:
SOME_VAR is an optional because it can be None

Return the value of the environment variable varname if it exists, or value if it doesn’t. value defaults to None.

Docs

You could set a fallback if the environment variable doesn't exist:

import os

SOME_VAR = os.getenv("SOME_VAR", "my fallback value")

def some_func(val: str) -> None:
    print(f"Loaded env var: {val}")

some_func(SOME_VAR)
```

This schould make SOME_VAR "not optional"

ContentLicense: CC BY-SA 4.0

Body:
When using os.getenv to retrieve environment variables, the default behavior returns a type of Optional[str]. This is problematic as any downstream methods/functions that utilize these variables will likely be defined to accept a str type explicitly. Is there an accepted usage to get around this issue or enforce the str return type?

In the stub file definition for getenv in typeshed you can find that getenv can have a return type of Optional[str] or Union[str, T_] depending on the usage of the default kwarg.

The four options I can see as yet are:

Define any downstream operations to accept Optional[str] types as arguments. This doesn't feel particularly right as a function/method may not be structured in a way that the Optional type makes sense. i.e. the operation has no reason for a particular argument to be None.

Use the default kwarg for getenv and provide a str default value. This seems more correct, but requires that one set a default value for every usage of getenv. The only problem I can see with this is that doing so may be confounding for testing or usage in different environments.

Define some kind of variable checking function. This could be a function that accepts the name of an environment variable to load, explicitly returns a string, and raises an error if the environment variable doesn't exist.

Explicitly set the type of the value returned by getenv to be a str. I really don't like this as it expects the environment to always be properly configured which, in my experience, is not a good assumption.

Find below an example that raises a mypy error.

import os

SOME_VAR = os.getenv("SOME_VAR")

def some_func(val: str) -> None:
    print(f"Loaded env var: {val}")

some_func(SOME_VAR)

The above raises the mypy error:

error: Argument 1 to "some_func" has incompatible type "Optional[str]"; expected "str"

Body:
SOME_VAR is an optional because it can be None

Return the value of the environment variable varname if it exists, or value if it doesn’t. value defaults to None.

Docs

You could set a fallback if the environment variable doesn't exist:

import os

SOME_VAR = os.getenv("SOME_VAR", "my fallback value")

def some_func(val: str) -> None:
    print(f"Loaded env var: {val}")

some_func(SOME_VAR)

This schould make SOME_VAR "not optional"


问:
Spring Kafka AckOnError
I have configured SeekToErrorHandler with DeadLetterPublisheingRecoverer

```<code> ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(primaryConsumerFactory());
    factory.setConcurrency(this.kafkaConfigProperties.getConsumerConcurrency());
    factory.setAutoStartup(true);
    factory.getContainerProperties().setAckOnError(false);
    factory.getContainerProperties().setAckMode(AckMode.RECORD);
    factory.setErrorHandler(new SeekToErrorHandler(new DeadLetterPublisheingRecoverer(kafkaTemplate()),3));
</code>```

When an exception is thrown from listener (or validator), after three retries, the message gets published to the dead letter.

The issue here is next time when restart my spring boot application (or listener container), same message gets again delivered to the listener and goes through the entire sequence and finally lands on dead letter. Is there any way to avoid this?

I have disabled auto commit and have set AckOnError(false) and AckMode(AckMode.RECORD);

In SeekToErrorHandler, I could find that the logic around SeekToUtil which throws exception until configured number of iterations gets completed and finally calling the accept method of the BiConsumer (deadletter publishing). So the container should commit the record on the final step (on publishing to dead letter) right? I have also gone through the comment on ackOnError(boolean) method in org.springframework.kafka.listener.ContainerProperties

When setAckOnError(true), I could find correct behavior with three retries and finally invoking dead letter publisher. The message not getting re-delivered when listener container restarted

Spring kafka version is 2.2.6

答:
In 2.3 we added ackAfterHandle; with the default being true for the SeekToCurrentErrorHandler.

```<code>@Override
public boolean isAckAfterHandle() {
    return this.ackAfterHandle;
}

/**
 * Set to false to tell the container to NOT commit the offset for a recovered record.
 * @param ackAfterHandle false to suppress committing the offset.
 * @since 2.3.2
 */
public void setAckAfterHandle(boolean ackAfterHandle) {
    this.ackAfterHandle = ackAfterHandle;
}
</code>```

In 2.4 it defaults to true for all error handlers.

https://github.com/spring-projects/spring-kafka/issues/1273

Title: Spring Kafka AckOnError

Body:
I have configured SeekToErrorHandler with DeadLetterPublisheingRecoverer

 ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(primaryConsumerFactory());
    factory.setConcurrency(this.kafkaConfigProperties.getConsumerConcurrency());
    factory.setAutoStartup(true);
    factory.getContainerProperties().setAckOnError(false);
    factory.getContainerProperties().setAckMode(AckMode.RECORD);
    factory.setErrorHandler(new SeekToErrorHandler(new DeadLetterPublisheingRecoverer(kafkaTemplate()),3));

When an exception is thrown from listener (or validator), after three retries, the message gets published to the dead letter.

The issue here is next time when restart my spring boot application (or listener container), same message gets again delivered to the listener and goes through the entire sequence and finally lands on dead letter. Is there any way to avoid this?

I have disabled auto commit and have set AckOnError(false) and AckMode(AckMode.RECORD);

In SeekToErrorHandler, I could find that the logic around SeekToUtil which throws exception until configured number of iterations gets completed and finally calling the accept method of the BiConsumer (deadletter publishing). So the container should commit the record on the final step (on publishing to dead letter) right? I have also gone through the comment on ackOnError(boolean) method in org.springframework.kafka.listener.ContainerProperties

When setAckOnError(true), I could find correct behavior with three retries and finally invoking dead letter publisher. The message not getting re-delivered when listener container restarted

Spring kafka version is 2.2.6

Body:
In 2.3 we added ackAfterHandle; with the default being true for the SeekToCurrentErrorHandler.

@Override
public boolean isAckAfterHandle() {
    return this.ackAfterHandle;
}

/**
 * Set to false to tell the container to NOT commit the offset for a recovered record.
 * @param ackAfterHandle false to suppress committing the offset.
 * @since 2.3.2
 */
public void setAckAfterHandle(boolean ackAfterHandle) {
    this.ackAfterHandle = ackAfterHandle;
}

In 2.4 it defaults to true for all error handlers.

https://github.com/spring-projects/spring-kafka/issues/1273


问:
Windows service build includes DLL's not referenced
Using Visual Studio 2017 I have created a Windows service using VB.net.  I have the root service class and a project installer class.  The Service builds, installs, and runs as expected.  With the following exception - the output to the BIN folder is enormous.
The references listed are as follows:

```<code>    System
    System.Configuration
    System.Configuration.Install
    System.Deployment
    System.Net.Http
    System.Runtime.CompilerServices.Unsafe
    System.ServiceProcess
    System.Threading.Tasks.Extensions
    TSLogger (internall DLL that logs to Event log)
</code>```

When I build the service the output to the bin folder includes over 100 .NET DLLs.  At different points during development, using NuGet package manager, I have installed and uninstalled CsvHelper and Newtonsoft.Json.

Any idea what would set the compiler to include all these DLLs as part of the output?  Or how I can control it?

I have attached a screenshot of the bin folder.

Bin folder screenshot:

答:
So it turns out it was CsvHelper v15.0.0. I created a new solution, didn't add any code but just added references and as soon as I added CsvHelper with NuGet Package manager, the bin folder would fill up with all these framework DLLs.

UPDATE

I have confirmed I get the same result from CsvHelper version 14.0.0; versions 13.0.0 and 12.3.2 do not produce these results.  I didn't test any other versions.  The only difference I can see is that the latest 2 versions include a reference to System.Runtime.CompilerServices.Unsafe - could this be what brings in so much of the .NET Framework libraries??

Body:
Using Visual Studio 2017 I have created a Windows service using VB.net.  I have the root service class and a project installer class.  The Service builds, installs, and runs as expected.  With the following exception - the output to the BIN folder is enormous.
The references listed are as follows:

    System
    System.Configuration
    System.Configuration.Install
    System.Deployment
    System.Net.Http
    System.Runtime.CompilerServices.Unsafe
    System.ServiceProcess
    System.Threading.Tasks.Extensions
    TSLogger (internall DLL that logs to Event log)

When I build the service the output to the bin folder includes over 100 .NET DLLs.  At different points during development, using NuGet package manager, I have installed and uninstalled CsvHelper and Newtonsoft.Json.

Any idea what would set the compiler to include all these DLLs as part of the output?  Or how I can control it?

I have attached a screenshot of the bin folder.

Bin folder screenshot:


问:
Want to create a bar after Action bar in codename1
trying to make an action bar with three buttons after the toolbar and keep it in all my app pages

答:
I have an idea...

```<code>Form hi = new Form("MyToolbar", BoxLayout.y());
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
Button btn3 = new Button("Button 3");
hi.getToolbar().add(BorderLayout.SOUTH, GridLayout.encloseIn(3, btn1, btn2, btn3));
hi.add(new Label("My Content Pane"));
hi.show();
</code>```

I'm not sure if this is a proper solution or a workaround, because there isn't a specific API. This relies on the fact that Toolbar uses a BorderLayout.

Body:
I have an idea...

Form hi = new Form("MyToolbar", BoxLayout.y());
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
Button btn3 = new Button("Button 3");
hi.getToolbar().add(BorderLayout.SOUTH, GridLayout.encloseIn(3, btn1, btn2, btn3));
hi.add(new Label("My Content Pane"));
hi.show();

I'm not sure if this is a proper solution or a workaround, because there isn't a specific API. This relies on the fact that Toolbar uses a BorderLayout.


问:
Template or abstract base class?
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?

I see mainly two possibilities:

Use an abstract base class and pass concrete object in

Use a template

Here is a little example, implemented in the various versions:

Version 1: Abstract base class

```<code>class Brake {
public: virtual void stopCar() = 0;
};

class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};

class Car {
  Brake* _brake;
public:
  Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};
</code>```

Version 2a: Template

```<code>template<class Brake>
class Car {
  Brake brake;
public:
  Car(){ brake.stopCar(); }
};
</code>```

Version 2b: Template and private inheritance

```<code>template<class Brake>
class Car : private Brake {
  using Brake::stopCar;
public:
  Car(){ stopCar(); }
};
</code>```

Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?

I realize there is not a big difference between version 2a and 2b, see C++ FAQ.

Can you comment on these possibilities?

答:
Most of your question has already been answered, but I wanted to elaborate on this bit:

Coming from Java, I am naturally
  inclined to always use version 1, but
  the templates versions seem to be
  preferred often, e.g. in STL code? If
  that's true, is it just because of
  memory efficiency etc (no inheritance,
  no virtual function calls)?

That's part of it. But another factor is the added type safety. When you treat a BrakeWithABS as a Brake, you lose type information. You no longer know that the object is actually a BrakeWithABS. If it is a template parameter, you have the exact type available, which in some cases may enable the compiler to perform better typechecking. Or it may be useful in ensuring that the correct overload of a function gets called. (if stopCar() passes the Brake object to a second function, which may have a separate overload for BrakeWithABS, that won't be called if you'd used inheritance, and your BrakeWithABS had been cast to a Brake.

Another factor is that it allows more flexibility. Why do all Brake implementations have to inherit from the same base class? Does the base class actually have anything to bring to the table? If I write a class which exposes the expected member functions, isn't that good enough to act as a brake? Often, explicitly using interfaces or abstract base classes constrain your code more than necessary.

(Note, I'm not saying templates should always be the preferred solution. There are other concerns that might affect this, ranging from compilation speed to "what programmers on my team are familiar with" or just "what I prefer". And sometimes, you need runtime polymorphism, in which case the template solution simply isn't possible)

ContentLicense: CC BY-SA 2.5

Title: Template or abstract base class?

Body:
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?

I see mainly two possibilities:

Use an abstract base class and pass concrete object in

Use a template

Here is a little example, implemented in the various versions:

Version 1: Abstract base class

class Brake {
public: virtual void stopCar() = 0;
};

class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};

class Car {
  Brake* _brake;
public:
  Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};

Version 2a: Template

template<class Brake>
class Car {
  Brake brake;
public:
  Car(){ brake.stopCar(); }
};

Version 2b: Template and private inheritance

template<class Brake>
class Car : private Brake {
  using Brake::stopCar;
public:
  Car(){ stopCar(); }
};

Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?

I realize there is not a big difference between version 2a and 2b, see C++ FAQ.

Can you comment on these possibilities?

OwnerDisplayName: jalf


问:
Check the Keys of an external JSON File in Java
as the Title states i would like to check the Keys of an external Json File in Java.

What i tried:

```<code>JSONObject json = new JSONObject("src/com/json/inventory.json");
System.out.println(json.keys());
</code>```

Issue: Doesn't do anything.

What are other posibilities?

Thank you in advance!

EDIT
Error

答:
If you're using this library, first you should read the file content like:

```<code>String unparsedJson = Files.readAllLines(Paths.get("src/com/json/inventory.json"))
                .stream()
                .reduce((a,b) -> a + b)
                .get();
</code>```

Then you can parse json with the code you provided:

```<code>JSONObject json = new JSONObject(unparsedJson);
</code>```

And iterate over the keys with something like this:

```<code>json.keys().forEachRemaining(key -> {
            System.out.println(key);
        });
</code>```

You could also use other libraries such as Jackson and Gson.

Body:
as the Title states i would like to check the Keys of an external Json File in Java.

What i tried:

JSONObject json = new JSONObject("src/com/json/inventory.json");
System.out.println(json.keys());

Issue: Doesn't do anything.

What are other posibilities?

Thank you in advance!

EDIT
Error

Body:
If you're using this library, first you should read the file content like:

String unparsedJson = Files.readAllLines(Paths.get("src/com/json/inventory.json"))
                .stream()
                .reduce((a,b) -> a + b)
                .get();

Then you can parse json with the code you provided:

JSONObject json = new JSONObject(unparsedJson);

And iterate over the keys with something like this:

json.keys().forEachRemaining(key -> {
            System.out.println(key);
        });

You could also use other libraries such as Jackson and Gson.


问:
Fill JS DataTable with conditions - Entity Framework MVC5
I have an MV5 project with C#, EF and SQL Server, and I'm filling a data table (from datatables.net references) using the following code:

```<code>public ActionResult GetData()
{
   using (Entity db = new Entity())
   {
      List<tableName> htmlTable = db.tableName.ToList<tableName>();
      return Json(new { data = htmltable }, JsonRequestBehavior.AllowGet);
   }
}
</code>```

That brings the entire table, but I'm looking to filter these based on user session (so userX "selects" only the rows that he manages or where the columnY has any filter) so it runs a query like:

```<code>SELECT * FROM tableName WHERE idUser = 'userX' AND columnY = 1;
</code>```

Can I bind data to the DataTable with filters adapting the method above or I have to change the data-bind approach?

答:
You can add filter on tableName with the help of linq and lambda expression

Ex:

```<code>var htmlTable = db.tableName.Where(d=>d.idUser=="userX" &&
columnY==1).ToList<tableName>();
</code>```

Body:
I have an MV5 project with C#, EF and SQL Server, and I'm filling a data table (from datatables.net references) using the following code:

public ActionResult GetData()
{
   using (Entity db = new Entity())
   {
      List<tableName> htmlTable = db.tableName.ToList<tableName>();
      return Json(new { data = htmltable }, JsonRequestBehavior.AllowGet);
   }
}

That brings the entire table, but I'm looking to filter these based on user session (so userX "selects" only the rows that he manages or where the columnY has any filter) so it runs a query like:

SELECT * FROM tableName WHERE idUser = 'userX' AND columnY = 1;

Can I bind data to the DataTable with filters adapting the method above or I have to change the data-bind approach?

Body:
You can add filter on tableName with the help of linq and lambda expression

Ex:

var htmlTable = db.tableName.Where(d=>d.idUser=="userX" &&
columnY==1).ToList<tableName>();


问:
Byte Buddy installOn API giving error: adding retransformable transformers is not supported?
Why installOn API is giving an error in my code. I want to call instrumentation.retransformClasses API from another thread.
or can we call instrumentation.retransformClasses API in bytebuddy.
I want to insert a static field after class is loaded. If that's possible, a short example would be great!

```<code>public static void premain(String arguments, Instrumentation instrumentation) {

    System.out.println("Agent for add fields ");
    final ByteBuddy byteBuddy = new ByteBuddy().with(Implementation.Context.Disabled.Factory.INSTANCE);
    new AgentBuilder.Default()
              .with(byteBuddy).with(RedefinitionStrategy.RETRANSFORMATION)
              .with(new AgentBuilder.InitializationStrategy.SelfInjection.Eager())
              .with(TypeStrategy.Default.REDEFINE)
              .type((ElementMatchers.nameContains("Method")))
              .transform(new Transformer() {
                   public Builder<?> transform(Builder<?> arg0, TypeDescription arg1, ClassLoader arg2,
                            JavaModule arg3) {
                        // TODO Auto-generated method stub
                        return null;
                    }
                })
              .installOn(instrumentation);

    Thread thread = new Thread() {
        public void run() {
            System.out.println("Thread Running");
            try {
                Thread.currentThread().sleep(10000);

                Class c[] = instrumentation.getAllLoadedClasses();
                for (int i = 0; i < c.length; i++) {
                    String clsName = c[i].getName();

                    System.out.println(clsName);
                    if (clsName.equals("com.github.shehanperera.example.Method")) {

                            instrumentation.retransformClasses(c[i]);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e);
            }

        }
    };

    thread.start();
}
</code>```

Giving exception:

```<code>Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:386)
    at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:401)
Caused by: java.lang.IllegalStateException: Could not install class file transformer
    at net.bytebuddy.agent.builder.AgentBuilder$Default.installOn(AgentBuilder.java:8538)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$Delegator.installOn(AgentBuilder.java:10179)
    at com.github.shehanperera.addfield.Agent.premain(Agent.java:39)
    ... 6 more
Caused by: java.lang.UnsupportedOperationException: adding retransformable transformers is not supported in this environment
    at sun.instrument.InstrumentationImpl.addTransformer(InstrumentationImpl.java:88)
    at net.bytebuddy.agent.builder.AgentBuilder$Default.installOn(AgentBuilder.java:8514)
    ... 8 more
FATAL ERROR in native method: processing of -javaagent failed
</code>```

答:
Javassist does not allow anything like that by default, javassist just does simple clever trick and allows you to edit class before it's actually loaded, as classes are loaded on first use. Otherwise typical agent with retransform must be used too.

And to create instrumentation that can retransform classes you must add proper flag to manifest:

    Can-Retransform-Classes: true

https://docs.oracle.com/javase/7/docs/api/java/lang/instrument/Instrumentation.html

Body:
Why installOn API is giving an error in my code. I want to call instrumentation.retransformClasses API from another thread.
or can we call instrumentation.retransformClasses API in bytebuddy.
I want to insert a static field after class is loaded. If that's possible, a short example would be great!

public static void premain(String arguments, Instrumentation instrumentation) {

    System.out.println("Agent for add fields ");
    final ByteBuddy byteBuddy = new ByteBuddy().with(Implementation.Context.Disabled.Factory.INSTANCE);
    new AgentBuilder.Default()
              .with(byteBuddy).with(RedefinitionStrategy.RETRANSFORMATION)
              .with(new AgentBuilder.InitializationStrategy.SelfInjection.Eager())
              .with(TypeStrategy.Default.REDEFINE)
              .type((ElementMatchers.nameContains("Method")))
              .transform(new Transformer() {
                   public Builder<?> transform(Builder<?> arg0, TypeDescription arg1, ClassLoader arg2,
                            JavaModule arg3) {
                        // TODO Auto-generated method stub
                        return null;
                    }
                })
              .installOn(instrumentation);

    Thread thread = new Thread() {
        public void run() {
            System.out.println("Thread Running");
            try {
                Thread.currentThread().sleep(10000);

                Class c[] = instrumentation.getAllLoadedClasses();
                for (int i = 0; i < c.length; i++) {
                    String clsName = c[i].getName();

                    System.out.println(clsName);
                    if (clsName.equals("com.github.shehanperera.example.Method")) {

                            instrumentation.retransformClasses(c[i]);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e);
            }

        }
    };

    thread.start();
}

Giving exception:

Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:386)
    at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:401)
Caused by: java.lang.IllegalStateException: Could not install class file transformer
    at net.bytebuddy.agent.builder.AgentBuilder$Default.installOn(AgentBuilder.java:8538)
    at net.bytebuddy.agent.builder.AgentBuilder$Default$Delegator.installOn(AgentBuilder.java:10179)
    at com.github.shehanperera.addfield.Agent.premain(Agent.java:39)
    ... 6 more
Caused by: java.lang.UnsupportedOperationException: adding retransformable transformers is not supported in this environment
    at sun.instrument.InstrumentationImpl.addTransformer(InstrumentationImpl.java:88)
    at net.bytebuddy.agent.builder.AgentBuilder$Default.installOn(AgentBuilder.java:8514)
    ... 8 more
FATAL ERROR in native method: processing of -javaagent failed


问:
How would I write an algorithm to find the greatest jump from number to number in a sequence?
If your sequence is 4 2 1, the largest jump is from 4 to 2. If your sequence is 3 10 5 16 8 4 2 1, the largest jump is from 5 to 16.

I've made an algorithm however I'm not completely sure what I have done wrong (whever I haven't made the loop properly, set my variables correctly, or something else). I'm not sure what I need to set my index, BiggestDiff, or CurrentDiff too. I tried using a while loop to compare each number in my vector but I get zero (I'm assuming because I set BiggestDiff to zero)

If anyone can point me in the right direction, show me an example, or something else, that will be greatly appreciated.

Here is my code below

```<code>int findBiggestDiff(std::vector<int> sequence)
{
  int index = 0;
  int BiggestDiff = 0 ;
  int CurrentDiff = BiggestDiff;
  CurrentDiff = std::abs(sequence[index] - sequence[index + 1]);
  while (index < sequence.size())
  {
    if (CurrentDiff > BiggestDiff)
    {
      BiggestDiff = CurrentDiff;
    }

    return index;
  }
}
</code>```

答:
Try this:

```<code>{
    int indexOfBiggestJump = 0;
    int BiggestDiff = 0 ;
    int CurrentDiff = BiggestDiff;

    for(int i = 0; i < sequence.size() - 1; i++) {
        CurrentDiff = std::abs(sequence[i] - sequence[i + 1]);
        if (CurrentDiff > BiggestDiff)
        {
            BiggestDiff = CurrentDiff;
            indexOfBiggestJump = i;
        }
    }
    return indexOfBiggestJump;
}
</code>```

There are several errors in your code.

your return index literally does nothing, only returns index (which will be 0) always.

you are not saving the index of the biggest jump anywhere.

if you are looking positions i and i + 1, you must go until sequence.size() - 1, otherwise you will look out of the bounds of sequence.

Body:
If your sequence is 4 2 1, the largest jump is from 4 to 2. If your sequence is 3 10 5 16 8 4 2 1, the largest jump is from 5 to 16.

I've made an algorithm however I'm not completely sure what I have done wrong (whever I haven't made the loop properly, set my variables correctly, or something else). I'm not sure what I need to set my index, BiggestDiff, or CurrentDiff too. I tried using a while loop to compare each number in my vector but I get zero (I'm assuming because I set BiggestDiff to zero)

If anyone can point me in the right direction, show me an example, or something else, that will be greatly appreciated.

Here is my code below

int findBiggestDiff(std::vector<int> sequence)
{
  int index = 0;
  int BiggestDiff = 0 ;
  int CurrentDiff = BiggestDiff;
  CurrentDiff = std::abs(sequence[index] - sequence[index + 1]);
  while (index < sequence.size())
  {
    if (CurrentDiff > BiggestDiff)
    {
      BiggestDiff = CurrentDiff;
    }

    return index;
  }
}

Body:
Try this:

{
    int indexOfBiggestJump = 0;
    int BiggestDiff = 0 ;
    int CurrentDiff = BiggestDiff;

    for(int i = 0; i < sequence.size() - 1; i++) {
        CurrentDiff = std::abs(sequence[i] - sequence[i + 1]);
        if (CurrentDiff > BiggestDiff)
        {
            BiggestDiff = CurrentDiff;
            indexOfBiggestJump = i;
        }
    }
    return indexOfBiggestJump;
}

There are several errors in your code.

your return index literally does nothing, only returns index (which will be 0) always.

you are not saving the index of the biggest jump anywhere.

if you are looking positions i and i + 1, you must go until sequence.size() - 1, otherwise you will look out of the bounds of sequence.


问:
Changing data point shape of second y-axis with ggplot
In my example I created a second y-axis in ggplot.
Instead of changing the colour for the data points of the second y-axis I want to change the shape.
But, of course, I get the error Scale for 'shape' is already present. Adding another scale for 'shape', which will replace the existing scale.
In the end I want to have a circle for "Large" and a filled circle for "Small" for "Visits" of the second y-axis.

This is my code:

```<code>Treatment <- c(rep(c("T/T"), times = 6),rep(c("R/R"), times = 6))
Size <- c(rep(c("Large", "Large", "Large", "Small", "Small", "Small"), times = 2))
Areatime <- c(240, 220, 120, 60, 55, 75, 90, 45, 70, 115, 40, 30)
Visits <- c(30, 45, 45, 65, 55, 55, 25, 35, 45, 75, 65, 55)
Counts <- data.frame(Treatment, Size, Areatime, Visits)

Counts$Treatment <- factor(Counts$Treatment, levels=c("T/T","R/R"))
Counts$inter <- interaction(Counts$Treatment, Counts$Size)
str(Counts)

ggplot(Count, aes(x = Treatment, y = Areatime)) +
  geom_jitter(aes(y = Areatime, shape = Size, width = 0.3)) +
  scale_shape_manual(values = c(0, 15), name = "Areatime", breaks = c("Large", "Small"),
    labels = c("Large", "Small")) +
  geom_jitter(aes(y = Counts*3, colour = Size, width = 0.3)) +
  scale_y_continuous(sec.axis = sec_axis(~./3, name = "Relative Visits [%]"))+
  scale_colour_manual(values =c(1, 2), name="Visits", breaks=c("Large", "Small"),
                     labels=c("Large", "Small")) +
  theme(axis.text.x=element_blank(),
                 panel.grid.major = element_blank(),
                 panel.grid.minor = element_blank(),
                 axis.ticks.x = element_blank(),
                 axis.line.x = element_blank(),
                 axis.line.y = element_line("black")) +
  facet_grid(.~Treatment, scales="free", switch = "x") +
  labs(y = "Average Areatime [sec]")
</code>```

Plot of Example

答:
Great, thanks! I just changed the colour for both to black instead of red and made the background the same gray colour and added the *3 in the second geom_jitter after "Visits" again (you just forgot because of my typo). So, the solution is:

```<code>ggplot(data = Counts, aes(x = Treatment, y = Areatime)) +
  geom_jitter(aes(y = Areatime, colour = Size, shape = Size), size = 3, width = 0.3) +
  scale_shape_manual(values = c(0, 15), name = "Areatime",
                     breaks = c("Large", "Small"), labels = c("Large", "Small")) +
  scale_colour_manual(values = c(1, 1)) +
  geom_jitter(aes(y = Visits*3, fill = Size), shape = 21, size = 3, width = 0.3) +
  scale_y_continuous(sec.axis = sec_axis(~./3, name = "Relative Visits [%]")) +
  scale_fill_manual(values = c("gray95", "black"),name = "Visits",
                    breaks = c("Large", "Small"), labels = c("Large", "Small")) +
  guides(colour = guide_legend(title = "Areatime")) +
  theme(axis.text.x=element_blank(),
                panel.background = element_rect(fill = "gray95"),
                panel.grid.major = element_blank(),
                panel.grid.minor = element_blank(),
                axis.ticks.x = element_blank(),
                axis.line.x = element_blank(),
                axis.line.y = element_line("black")) +
  facet_grid(. ~Treatment, scales="free", switch = "x") +
  labs(y = "Average Areatime [sec]")
</code>```

Solution

Body:
In my example I created a second y-axis in ggplot.
Instead of changing the colour for the data points of the second y-axis I want to change the shape.
But, of course, I get the error Scale for 'shape' is already present. Adding another scale for 'shape', which will replace the existing scale.
In the end I want to have a circle for "Large" and a filled circle for "Small" for "Visits" of the second y-axis.

This is my code:

Treatment <- c(rep(c("T/T"), times = 6),rep(c("R/R"), times = 6))
Size <- c(rep(c("Large", "Large", "Large", "Small", "Small", "Small"), times = 2))
Areatime <- c(240, 220, 120, 60, 55, 75, 90, 45, 70, 115, 40, 30)
Visits <- c(30, 45, 45, 65, 55, 55, 25, 35, 45, 75, 65, 55)
Counts <- data.frame(Treatment, Size, Areatime, Visits)

Counts$Treatment <- factor(Counts$Treatment, levels=c("T/T","R/R"))
Counts$inter <- interaction(Counts$Treatment, Counts$Size)
str(Counts)

ggplot(Count, aes(x = Treatment, y = Areatime)) +
  geom_jitter(aes(y = Areatime, shape = Size, width = 0.3)) +
  scale_shape_manual(values = c(0, 15), name = "Areatime", breaks = c("Large", "Small"),
    labels = c("Large", "Small")) +
  geom_jitter(aes(y = Counts*3, colour = Size, width = 0.3)) +
  scale_y_continuous(sec.axis = sec_axis(~./3, name = "Relative Visits [%]"))+
  scale_colour_manual(values =c(1, 2), name="Visits", breaks=c("Large", "Small"),
                     labels=c("Large", "Small")) +
  theme(axis.text.x=element_blank(),
                 panel.grid.major = element_blank(),
                 panel.grid.minor = element_blank(),
                 axis.ticks.x = element_blank(),
                 axis.line.x = element_blank(),
                 axis.line.y = element_line("black")) +
  facet_grid(.~Treatment, scales="free", switch = "x") +
  labs(y = "Average Areatime [sec]")

Plot of Example

Body:
Great, thanks! I just changed the colour for both to black instead of red and made the background the same gray colour and added the *3 in the second geom_jitter after "Visits" again (you just forgot because of my typo). So, the solution is:

ggplot(data = Counts, aes(x = Treatment, y = Areatime)) +
  geom_jitter(aes(y = Areatime, colour = Size, shape = Size), size = 3, width = 0.3) +
  scale_shape_manual(values = c(0, 15), name = "Areatime",
                     breaks = c("Large", "Small"), labels = c("Large", "Small")) +
  scale_colour_manual(values = c(1, 1)) +
  geom_jitter(aes(y = Visits*3, fill = Size), shape = 21, size = 3, width = 0.3) +
  scale_y_continuous(sec.axis = sec_axis(~./3, name = "Relative Visits [%]")) +
  scale_fill_manual(values = c("gray95", "black"),name = "Visits",
                    breaks = c("Large", "Small"), labels = c("Large", "Small")) +
  guides(colour = guide_legend(title = "Areatime")) +
  theme(axis.text.x=element_blank(),
                panel.background = element_rect(fill = "gray95"),
                panel.grid.major = element_blank(),
                panel.grid.minor = element_blank(),
                axis.ticks.x = element_blank(),
                axis.line.x = element_blank(),
                axis.line.y = element_line("black")) +
  facet_grid(. ~Treatment, scales="free", switch = "x") +
  labs(y = "Average Areatime [sec]")

Solution


问:
(AttributeError: __enter__) when using __new__ magic method
I'm trying to use __new__ method to check for argument validity (str) before processing it, so i am doing as following:

```<code>class foo:

    def __new__(cls, argument):
        if not isinstance(argument, str):
            raise TypeError('argument must be str')
        print("passed __new__")

    def __init__(self, argument):
        self.argument = argument
        print("passed __init__")

    def __enter__(self):
        print("passed __enter__")

    def __exit__(self, *args):
        print("passed __exit__")
</code>```

then, when I call this using with keyword which calls __enter__ and __exit__

```<code>with foo('test'):
    print("i am between __enter__ and __exit__, damn!")
</code>```

I am getting this output:

```<code>passed __new__
AttributeError: __enter__
</code>```

I expected this output:

```<code>passed __new__
passed __init__
passed __enter__
i am between __enter__ and __exit__, damn!
passed __exit__
</code>```

I noticed when dropping __new__ method entirely; it will work. Why does using __new__ break that? and how can I get it to work even with __new__ existing?

答:
__new__ has to actually create and return an instance of your class.

```<code>class foo:

    def __new__(cls, argument):
        if not isinstance(argument, str):
            raise TypeError('argument must be str')
        print("passed __new__")
        <b>return super().__new__(cls)</b>

    def __init__(self, argument):
        self.argument = argument
        print("passed __init__")

    def __enter__(self):
        print("passed __enter__")

    def __exit__(self, *args):
        print("passed __exit__")</code>```

In your original code, foo.__new__ returned None, and indeed None has no attribute __enter__. Also, since None is not an instance of foo, the implicit call to foo.__init__ was suppressed.

Since foo is an instance of type, the call foo('test') is short for

```<code>type.__call__(foo, 'test')
</code>```

You can imagine __call__ is defined something like

```<code>def __call__(cls, *args, **kwargs):
    obj = cls.__new__(*args, **kwargs)
    if isinstance(obj, cls):
        obj.__init__(*args, **kwargs)
    return obj
</code>```

Overriding __new__ means you want to change how the instance gets created, while overriding __init__ means you want to change how an already-created instance gets initialized. In this case, you avoid creating a new instance altogether if the argument is of the wrong type.

Body:
I'm trying to use __new__ method to check for argument validity (str) before processing it, so i am doing as following:

class foo:

    def __new__(cls, argument):
        if not isinstance(argument, str):
            raise TypeError('argument must be str')
        print("passed __new__")

    def __init__(self, argument):
        self.argument = argument
        print("passed __init__")

    def __enter__(self):
        print("passed __enter__")

    def __exit__(self, *args):
        print("passed __exit__")

then, when I call this using with keyword which calls __enter__ and __exit__

with foo('test'):
    print("i am between __enter__ and __exit__, damn!")

I am getting this output:

passed __new__
AttributeError: __enter__

I expected this output:

passed __new__
passed __init__
passed __enter__
i am between __enter__ and __exit__, damn!
passed __exit__

I noticed when dropping __new__ method entirely; it will work. Why does using __new__ break that? and how can I get it to work even with __new__ existing?

Body:
__new__ has to actually create and return an instance of your class.

class foo:

    def __new__(cls, argument):
        if not isinstance(argument, str):
            raise TypeError('argument must be str')
        print("passed __new__")
        return super().__new__(cls)

    def __init__(self, argument):
        self.argument = argument
        print("passed __init__")

    def __enter__(self):
        print("passed __enter__")

    def __exit__(self, *args):
        print("passed __exit__")

In your original code, foo.__new__ returned None, and indeed None has no attribute __enter__. Also, since None is not an instance of foo, the implicit call to foo.__init__ was suppressed.

Since foo is an instance of type, the call foo('test') is short for

type.__call__(foo, 'test')

You can imagine __call__ is defined something like

def __call__(cls, *args, **kwargs):
    obj = cls.__new__(*args, **kwargs)
    if isinstance(obj, cls):
        obj.__init__(*args, **kwargs)
    return obj

Overriding __new__ means you want to change how the instance gets created, while overriding __init__ means you want to change how an already-created instance gets initialized. In this case, you avoid creating a new instance altogether if the argument is of the wrong type.


问:
SwiftUI customized text field in OSX
I am creating a edit view in SwiftUI for Mac OSX. A user can change his profile. At the moment I am using default Text() elements to view his current values/settings.

Now I want to create a edit mode. I already created a button, which toggles the edit mode. If the edit mode is activated, I replaced every Text with a TextField.

When I took a look at Apple's contact book for Mac OSX, I found out that they are using a different kind of Text Field (see image)

Is it possible to use this kind of element in SwiftUI and in OSX? What are they called or are they just customized TextFields with Border? I couldn't find any official documentation about them. If somebody finds it, I would be very happy.

答:
Well, in general all you need is PlainTextFieldStyle, but as currently SwiftUI does not allow to turn off focus ring there is some workaround below to disable it globally for all text fields.

Anyway... I think worth posting, so here it is (tested with Xcode 11.3)

```<code>extension NSTextField { // << workaround !!!
    open override var focusRingType: NSFocusRingType {
        get { .none }
        set { }
    }
}

struct ContentView: View {
    @State private var text = ""
    var body: some View {
        HStack {
            Text("Mobil")
            TextField("", text: $text)
                .textFieldStyle(PlainTextFieldStyle())
                .padding(1)
                .background(RoundedRectangle(cornerRadius: 2).stroke(Color.white))
                .frame(width: 100)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.black)
    }
}
</code>```

Title: SwiftUI customized text field in OSX

Body:
Well, in general all you need is PlainTextFieldStyle, but as currently SwiftUI does not allow to turn off focus ring there is some workaround below to disable it globally for all text fields.

Anyway... I think worth posting, so here it is (tested with Xcode 11.3)

extension NSTextField { // << workaround !!!
    open override var focusRingType: NSFocusRingType {
        get { .none }
        set { }
    }
}

struct ContentView: View {
    @State private var text = ""
    var body: some View {
        HStack {
            Text("Mobil")
            TextField("", text: $text)
                .textFieldStyle(PlainTextFieldStyle())
                .padding(1)
                .background(RoundedRectangle(cornerRadius: 2).stroke(Color.white))
                .frame(width: 100)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.black)
    }
}


问:
Power Query remove repetitive substrings
I have a column in Power Query (standalone power query with Excel), with text like this

"Hazelnut Berries Nuts Raspberry"

I need to be able to identify if there are more than 1 instance of "nut" ("berry") in it and remove generic word, to have result as

"Hazelnut Raspberry"

I have seen this post, but it works off whole words repeated.

答:
List.Distinct: https://learn.microsoft.com/en-ie/powerquery-m/list-distinct should do it; something like: List.Distinct(Text.Split("Hazelnut Berries Nuts Raspberry", " "))

You might need a bit more if your list could contain multiple spaces or other "stuff"


问:
Log4Net Log to specific Appender .NET Core
Using .NET Core, C#, Log4Net 2.0.8

I am trying to log to different Appenders but for some reason there is no log4net.LogManager.GetLogger(string), there is only log4net.LogManager.GetLogger(type).

I have taken an example from:
Log4net - Logging to wrong appender

I wish to log from one class:

```<code>private static readonly ILog logA = LogManager.GetLogger("LogA");
log.Debug("This should log to LogA");
</code>```

And in another other class:

```<code>private static readonly ILog logB = LogManager.GetLogger("LogB");
log.Debug("This should log to LogB");
</code>```

I have tried understanding Log4Net following https://logging.apache.org/log4net/release/manual/introduction.html

But the example also refers to:

```<code>ILog x = LogManager.GetLogger("wombat");
ILog y = LogManager.GetLogger("wombat");
</code>```

How do I log to specific Appenders? Thank you

答:
You'll need to use the GetLogger(Assembly repositoryAssembly, string name) overload, see spec.

An assembly argument must be passed in, which can be e.g. Assembly.GetExecutingAssembly().

(Note that this logs to a specific logger, not an appender, which is what you are trying to do.)

Example:

```<code>ILog logger = LogManager .GetLogger(Assembly.GetExecutingAssembly(), "LogB");
</code>```

Body:
Using .NET Core, C#, Log4Net 2.0.8

I am trying to log to different Appenders but for some reason there is no log4net.LogManager.GetLogger(string), there is only log4net.LogManager.GetLogger(type).

I have taken an example from:
Log4net - Logging to wrong appender

I wish to log from one class:

private static readonly ILog logA = LogManager.GetLogger("LogA");
log.Debug("This should log to LogA");

And in another other class:

private static readonly ILog logB = LogManager.GetLogger("LogB");
log.Debug("This should log to LogB");

I have tried understanding Log4Net following https://logging.apache.org/log4net/release/manual/introduction.html

But the example also refers to:

ILog x = LogManager.GetLogger("wombat");
ILog y = LogManager.GetLogger("wombat");

How do I log to specific Appenders? Thank you

Body:
You'll need to use the GetLogger(Assembly repositoryAssembly, string name) overload, see spec.

An assembly argument must be passed in, which can be e.g. Assembly.GetExecutingAssembly().

(Note that this logs to a specific logger, not an appender, which is what you are trying to do.)

Example:

ILog logger = LogManager .GetLogger(Assembly.GetExecutingAssembly(), "LogB");


问:
Uncaught Error: Call to undefined function stats_cdf_t()
I have to calculate an Excel formula(F.DIST.RT) in PHP. but receiving an error.
e.g,

```<code>F.DIST.RT(4, 2, 1)
</code>```

As defined here:
https://www.php.net/manual/en/function.stats-cdf-t.php

答:
I installed PECL and Stat library in PHP to fix this problem.

```<code>sudo apt-get install php-pear
sudo apt-get install php7.4-dev
sudo pecl install stats-2.0.3
</code>```

then added extension=stats.so to my php.ini
restart apache.

Body:
I have to calculate an Excel formula(F.DIST.RT) in PHP. but receiving an error.
e.g,

F.DIST.RT(4, 2, 1)

As defined here:
https://www.php.net/manual/en/function.stats-cdf-t.php

Body:
I installed PECL and Stat library in PHP to fix this problem.

sudo apt-get install php-pear
sudo apt-get install php7.4-dev
sudo pecl install stats-2.0.3

then added extension=stats.so to my php.ini
restart apache.


答:
You can try as shown in the below query. Here is a Basic LINQ Query Operations (C#)
 reference learning to you.</p>

```<code>public ActionResult GetData()
{
  using (Entity db = new Entity())
  {
     var htmltable = (from r in db.tableName WHERE r.idUser == "userX" &&
     r.columnY = 1
     select r).ToList();
     return Json(new { data = htmltable }, JsonRequestBehavior.AllowGet);
  }
}
</code>```

Title: Fill JS DataTable with conditions - Entity Framework MVC5

Body:
You can try as shown in the below query. Here is a Basic LINQ Query Operations (C#)
 reference learning to you.

public ActionResult GetData()
{
  using (Entity db = new Entity())
  {
     var htmltable = (from r in db.tableName WHERE r.idUser == "userX" &&
     r.columnY = 1
     select r).ToList();
     return Json(new { data = htmltable }, JsonRequestBehavior.AllowGet);
  }
}


问:
Psuedo-Element Triangle During JQuery Slide
I'm making a login box which slides out via JQuery, I'm using a pseudo-element to position a triangle on top. I've also tried placing the triangle there the normal way (with a traditional divider), so I assume the issue is with the border and not the pseudo-element.

The triangle does not appear until the slide is complete.

```<code>.mobiles-login {
    z-index: 10;
    display: none;
    position: absolute;
    right: 89px;
    top: 112px;
    width: 300px;
    margin: 16px auto;
    font-size: 16px;
    box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
}

.mobiles-login:after {
    content: " ";
    position: absolute;
    right: 30px;
    top: -15px;
    border-top: none;
    border-right: 15px solid transparent;
    border-left: 15px solid transparent;
    border-bottom: 15px solid #656565;
}
</code>```

https://codepen.io/cohen-coombe/pen/MWweEVB

CSS arrow hides during jQuery slideUp or slideDown animation suggests setting overflow to visible !important, with an inner element with the overflow to invisible. This half worked, however the inner element's hidden overflow has no effect https://codepen.io/cohen-coombe/pen/OJVXOvw

Any pointers would be much appreciated.

答:
Check my option, maybe it will be useful:

https://codepen.io/roman-seredenko/pen/poJbpKR

I have added padding and put the arrow in that space. The shadow I have put in an additional div.

```<code>.mobiles-login {
    z-index: 10;
    display: none;
    position: absolute;
    right: 89px;
    top: 112px;
    width: 300px;
    margin: 0px auto;
  padding: 15px;
    font-size: 16px;

}
.mobiles-login-inner { box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24); }
.mobiles-login:after {
    content: " ";
    position: absolute;
    right: 30px;
    top: 0px;
    border-top: none;
    border-right: 15px solid transparent;
    border-left: 15px solid transparent;
    border-bottom: 15px solid #656565;
}
</code>```

Body:
I'm making a login box which slides out via JQuery, I'm using a pseudo-element to position a triangle on top. I've also tried placing the triangle there the normal way (with a traditional divider), so I assume the issue is with the border and not the pseudo-element.

The triangle does not appear until the slide is complete.

.mobiles-login {
    z-index: 10;
    display: none;
    position: absolute;
    right: 89px;
    top: 112px;
    width: 300px;
    margin: 16px auto;
    font-size: 16px;
    box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
}

.mobiles-login:after {
    content: " ";
    position: absolute;
    right: 30px;
    top: -15px;
    border-top: none;
    border-right: 15px solid transparent;
    border-left: 15px solid transparent;
    border-bottom: 15px solid #656565;
}

https://codepen.io/cohen-coombe/pen/MWweEVB

CSS arrow hides during jQuery slideUp or slideDown animation suggests setting overflow to visible !important, with an inner element with the overflow to invisible. This half worked, however the inner element's hidden overflow has no effect https://codepen.io/cohen-coombe/pen/OJVXOvw

Any pointers would be much appreciated.

Body:
Check my option, maybe it will be useful:

https://codepen.io/roman-seredenko/pen/poJbpKR

I have added padding and put the arrow in that space. The shadow I have put in an additional div.

.mobiles-login {
    z-index: 10;
    display: none;
    position: absolute;
    right: 89px;
    top: 112px;
    width: 300px;
    margin: 0px auto;
  padding: 15px;
    font-size: 16px;

}
.mobiles-login-inner { box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24); }
.mobiles-login:after {
    content: " ";
    position: absolute;
    right: 30px;
    top: 0px;
    border-top: none;
    border-right: 15px solid transparent;
    border-left: 15px solid transparent;
    border-bottom: 15px solid #656565;
}


问:
Regex allowing spaces (for a Phone number regex)
I have this regex:

```<code>preg_match("#^([0-9]+)$#", $post['telephone'])
</code>```

who allow only numbers (for a phone number in the French type so 0123456789) but I would like to allow spaces. For example allow this type of string: "01 23 45 67 89".

Can you please help me?

答:
This one strips out anything but digits, spaces and a dash.

```<code>$input = '0123?> Abc -_#';
$output = preg_replace('#[^0-9- ]#', '', strtolower($input));
echo($output);
</code>```

Do you want to just validate (matches and abort) or cleanse, try and clean up and carry on?

ContentLicense: CC BY-SA 3.0

Body:
I have this regex:

preg_match("#^([0-9]+)$#", $post['telephone'])

who allow only numbers (for a phone number in the French type so 0123456789) but I would like to allow spaces. For example allow this type of string: "01 23 45 67 89".

Can you please help me?

Body:
This one strips out anything but digits, spaces and a dash.

$input = '0123?> Abc -_#';
$output = preg_replace('#[^0-9- ]#', '', strtolower($input));
echo($output);

Do you want to just validate (matches and abort) or cleanse, try and clean up and carry on?


问:
How to assign allow all action `*/` to a specific role using code in Yii2?
I am creating new role using the below code.

```<code>use yii\rbac\PhpManager;
$r=new PhpManager;
$r->init();
$r->createRole("admin","Администратор");
$r->save();
</code>```

I am assigning the above role to specific user.

```<code>$r->assign('1','admin');   //1 is user id
</code>```

So how can i assign allow all action to the above role admin using php code.
Basically after run the migration i want to create a user as admin role and allow all the action's for this role.

答:
If you are using the behavior yii\filters\AccessControl in your controllers, you could replace it with your own one in your bootstrap.php:

```<code>Yii::$classMap['yii\filters\AccessControl'] = @common/components/filters/AccessControl.php
</code>```

Add the appropriate role in your AccessControl class, by copying the original AccessControl.php in your AccessControl.php and by extending the init function. At the end of init function just add your role:

```<code>public function init()
{
...
...
    $this->rules[] = [
        'allow' => true,
        'roles' => ['admin'],
    ];
}
</code>```

Body:
I am creating new role using the below code.

use yii\rbac\PhpManager;
$r=new PhpManager;
$r->init();
$r->createRole("admin","Администратор");
$r->save();

I am assigning the above role to specific user.

$r->assign('1','admin');   //1 is user id

So how can i assign allow all action to the above role admin using php code.
Basically after run the migration i want to create a user as admin role and allow all the action's for this role.

Body:
If you are using the behavior yii\filters\AccessControl in your controllers, you could replace it with your own one in your bootstrap.php:

Yii::$classMap['yii\filters\AccessControl'] = @common/components/filters/AccessControl.php

Add the appropriate role in your AccessControl class, by copying the original AccessControl.php in your AccessControl.php and by extending the init function. At the end of init function just add your role:

public function init()
{
...
...
    $this->rules[] = [
        'allow' => true,
        'roles' => ['admin'],
    ];
}


问:
Is it possible to build a generic function for the fetches?
I build an app in react.js with a lot of 'crud' operations. I am a beginner in React. For all these fetches there are always the same header (content-type, token...). And for each requests I have to resolve promises, test the code status, parse the answer, manage the errors , etc.... It is very long to write.

So I wonder if is possible to build a generic function. Something like that:

```<code>myBooks = callApi('endpoint', 'myparams');
</code>```

And that's all ! The function callApi would do all the necessary (add the headers, the token, etc....).

I tried on my side, but I have not enough skills to do that in React.

Do you make your fetches with a special package ? or do you write, like me, your fetches and too bad it's long to write.

Do you have some packages to suggest?

答:
Yes totally. You can create a callApi function like this:

```<code>const callApi = (url, params) => {
  let token = localStorage.getItem('token');
  let heads = {};
  let body = params;

  if (token !== null && token !== undefined && token !== ''){
    heads['token'] = token;
  }

  heads["Content-Type"] = "application/json";
  body = params && JSON.stringify(params);

  let options = {
    mode: "cors",
    method: "POST",
    headers: heads
  };

  if (body) options['body'] = body;

  try {
    const response = await fetch(url, options);
    const res = await response.json();
    return res;
  } catch (error) {
    console.log(error);
  }
}
</code>```

Hope this helps!!

Body:
I build an app in react.js with a lot of 'crud' operations. I am a beginner in React. For all these fetches there are always the same header (content-type, token...). And for each requests I have to resolve promises, test the code status, parse the answer, manage the errors , etc.... It is very long to write.

So I wonder if is possible to build a generic function. Something like that:

myBooks = callApi('endpoint', 'myparams');

And that's all ! The function callApi would do all the necessary (add the headers, the token, etc....).

I tried on my side, but I have not enough skills to do that in React.

Do you make your fetches with a special package ? or do you write, like me, your fetches and too bad it's long to write.

Do you have some packages to suggest?

Body:
Yes totally. You can create a callApi function like this:

const callApi = (url, params) => {
  let token = localStorage.getItem('token');
  let heads = {};
  let body = params;

  if (token !== null && token !== undefined && token !== ''){
    heads['token'] = token;
  }

  heads["Content-Type"] = "application/json";
  body = params && JSON.stringify(params);

  let options = {
    mode: "cors",
    method: "POST",
    headers: heads
  };

  if (body) options['body'] = body;

  try {
    const response = await fetch(url, options);
    const res = await response.json();
    return res;
  } catch (error) {
    console.log(error);
  }
}

Hope this helps!!


问:
Reading data from MySQL to create HTML table (with filter)
I am trying to create an HTML page that will display data as a table from MySql table.  I am able to get the data from Mysql into JSON but not able to get it to display on the HTML page.  It can either read from the database directly or a JSON page, whichever is better practice.  I am stuck getting it to display as a table, once it is displayed I would like to be able to add more data such as age and have a sort/filter function.  The code I have is very basic and from a tutorial I saw so thank you for any assistance!

table_routes.js

```<code>module.exports = function(app, passport) {
    app.get('/', function(req, res){
     res.render('index.ejs');
    });

    //-SQL QUERY
    var express = require('express')
     , http = require('http')
     , mysql = require('mysql'); // <---- HERE

    var app = express();

    app.use(function(req, res, next) {
       res.header("Access-Control-Allow-Origin", "http://localhost:8080");
       res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
       next();
     });

    var connection = mysql.createConnection({
       host: 'localhost',
       user: 'root',
       password: "password",
       database: 'db'
    });

    connection.connect(); // <---- AND HERE

    // all environments
    app.set('port', process.env.PORT || 7003);

   connection.query('SELECT * FROM testtable', function(err, rows, fields){
      if(err) {
            console.log(err);
            res.json({"error":true});
      }
      else {
           //    console.log(result);
          console.log(JSON.stringify(rows));
        //   response.writeHead(200, {'Content-Type': 'application/json'});
          res.json(rows);
        //   response.end(JSON.stringify(rows));

      }

      });

   http.createServer(app).listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));
   });

    };

</code>```

admintable.ejs

```<code><!DOCTYPE html>
<head>
<title>Home | Table</title>
<link type="text/css" rel="stylesheet" href="css/styles.css" />
</head>
<body>
  <h1>Dashboard</h1>
  <table id="servers">
    <thead>
      <tr>
        <th width="150">ID</th>
        <th width="150">Name</th>
        <th width="150">Last Name</th>
        <th width="150">Row</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>

  <div class="log"></div>
  <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
        // Code here
          $.get('/getTable', function(result,fields) {
          var rows = JSON.parse(result);
          var row = rows[i];
          console.log(rows);
            for (i=0 ; i < rows.length ; i++){
                $('#servers tbody').append('<tr><td>'+row.id+'</td><td>'+row.name+'</td><td>'+row.lastname+'</td><td>'+row.testtablecol+'</td></tr>');
            }
          });
    });
    </script>
  <script type="text/javascript" src="js/script.js" />
</body>

</code>```

答:
I was able to get the data to display with the help of this example.  Now I just need assistance with filtering.

https://github.com/sam-suresh/JSON-URL-to-HTML-Table

JSON to HTML from url

```<code><html>
<table id="personDataTable">
    <tr>
        <th>id</th>
        <th>name</th>
        <th>lastname</th>
    </tr>

</table>

<style>
table {
  border: 2px solid #666;
    width: 100%;
}
th {
  background: #f8f8f8;
  font-weight: bold;
    padding: 2px;
}
</style>
     <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<script>
$.ajax({
    url: 'ENTER YOUR URL',
    type: "get",
    dataType: "json",

    success: function(data) {
        drawTable(data);
    }
});

function drawTable(data) {
    for (var i = 0; i < data.length; i++) {
        drawRow(data[i]);
    }
}

function drawRow(rowData) {
    var row = $("<tr />")
    $("#personDataTable").append(row);
        row.append($("<td>" + rowData.id + "</td>"));
        row.append($("<td>" + rowData.name + "</td>"));
        row.append($("<td>" + rowData.lastname + "</td>"));
    }

</script>
</html>
</code>```

Body:
I am trying to create an HTML page that will display data as a table from MySql table.  I am able to get the data from Mysql into JSON but not able to get it to display on the HTML page.  It can either read from the database directly or a JSON page, whichever is better practice.  I am stuck getting it to display as a table, once it is displayed I would like to be able to add more data such as age and have a sort/filter function.  The code I have is very basic and from a tutorial I saw so thank you for any assistance!

table_routes.js

module.exports = function(app, passport) {
    app.get('/', function(req, res){
     res.render('index.ejs');
    });

    //-SQL QUERY
    var express = require('express')
     , http = require('http')
     , mysql = require('mysql'); // <---- HERE

    var app = express();

    app.use(function(req, res, next) {
       res.header("Access-Control-Allow-Origin", "http://localhost:8080");
       res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
       next();
     });

    var connection = mysql.createConnection({
       host: 'localhost',
       user: 'root',
       password: "password",
       database: 'db'
    });

    connection.connect(); // <---- AND HERE

    // all environments
    app.set('port', process.env.PORT || 7003);

   connection.query('SELECT * FROM testtable', function(err, rows, fields){
      if(err) {
            console.log(err);
            res.json({"error":true});
      }
      else {
           //    console.log(result);
          console.log(JSON.stringify(rows));
        //   response.writeHead(200, {'Content-Type': 'application/json'});
          res.json(rows);
        //   response.end(JSON.stringify(rows));

      }

      });

   http.createServer(app).listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));
   });

    };

admintable.ejs

<!DOCTYPE html>

<title>Home | Table</title>
<link type="text/css" rel="stylesheet" href="css/styles.css" />

Dashboard

        ID
        Name
        Last Name
        Row

Body:
I was able to get the data to display with the help of this example.  Now I just need assistance with filtering.

https://github.com/sam-suresh/JSON-URL-to-HTML-Table

JSON to HTML from url

<html>
<table id="personDataTable">
    <tr>
        <th>id</th>
        <th>name</th>
        <th>lastname</th>
    </tr>

</table>

<style>
table {
  border: 2px solid #666;
    width: 100%;
}
th {
  background: #f8f8f8;
  font-weight: bold;
    padding: 2px;
}
</style>
     <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<script>
$.ajax({
    url: 'ENTER YOUR URL',
    type: "get",
    dataType: "json",

    success: function(data) {
        drawTable(data);
    }
});

function drawTable(data) {
    for (var i = 0; i < data.length; i++) {
        drawRow(data[i]);
    }
}

function drawRow(rowData) {
    var row = $("<tr />")
    $("#personDataTable").append(row);
        row.append($("<td>" + rowData.id + "</td>"));
        row.append($("<td>" + rowData.name + "</td>"));
        row.append($("<td>" + rowData.lastname + "</td>"));
    }

</script>
</html>


问:
Apache Camel route to pojo
I have an Account Instance that is not in the format I need. I am trying Camel
but just not getting
the basic understanding. I have the un-formatted Instance successfully coming in and I display it in the log.
I have tried to extract the data from the body using a processor and directly to a POJO.
The POJO uses fixed length definitions. Which is needed do to passing data to a Mainframe DB. Please point me in a direction.

Got message:12          xZZ200ZZZZZZZ

```<code>public class AccountAddRoute extends RouteBuilder{
    public void configure() throws Exception {
        DataFormat bindy = new BindyFixedLengthDataFormat(AccountAddData.class);
        from("direct:input")
        .log("   In AccountAddRoute   ")
        .marshal(bindy)
        .log("Got message:${body}");
        .to(???????_)

My Apologies. Not a good explanation of what I am trying to do.
I have An Account POJO that is being built thru FORM. I need to save
it in 2 different formats. Incoming just the way it is and in a
fixed format to be sent to Mainframe. This is what I get from the form

Code1=12          x , Code2=200

I initiate rout by sending body of form in accountAddData Instance

producerTemplate.sendBody("direct:input", accountAddData);

public class AccountAddRoute extends RouteBuilder{
    public void configure() throws Exception {
        DataFormat bindy = new BindyFixedLengthDataFormat(AccountAddData.class);
        from("direct:input")
        .log("   In AccountAddRoute   ")
        .marshal(bindy)
        .log("Got message:${body}");
        .to(???????_)

Just for Testing purposes my Account Bindy Pojo is below
    @DataField(pos =1, length=15, paddingChar='Z', trim=true, align="L")
    private String Code1;

    @DataField(pos =2, length=10, paddingChar='Z',  align="L")
    private String Code2;

When I log Body, I get >>

Got message:12          xZZ200ZZZZZZZ

However, my question is how do I create the new Instance in the
BINDY Format SO I can use it

==========
I did add processor and when I do display of body in processor >>

log.info("   In MyProcessor           =    " + exchange.getIn().getBody());
In MyProcessor           =    [B@3338b2b9
I was expecting to have the getter/setters available after getBody for the
accoountAddData instance. But obviously I don’t have a good understanding
of camel
exchange.getIn().getBody().????

</code>```

答:
Are you trying to unmarshal the incoming data? If thats the case, then you would need to use the following code.</p>

```<code>  from("direct:input")
   .log("   In AccountAddRoute   ")
   .unmarshal(new BindyFixedLengthDataFormat(AccountAddData.class))
   .log("Got message:${body}");
   .to(???????_)
</code>```

Title: Apache Camel route to pojo

Body:
I have an Account Instance that is not in the format I need. I am trying Camel
but just not getting
the basic understanding. I have the un-formatted Instance successfully coming in and I display it in the log.
I have tried to extract the data from the body using a processor and directly to a POJO.
The POJO uses fixed length definitions. Which is needed do to passing data to a Mainframe DB. Please point me in a direction.

Got message:12          xZZ200ZZZZZZZ

public class AccountAddRoute extends RouteBuilder{
    public void configure() throws Exception {
        DataFormat bindy = new BindyFixedLengthDataFormat(AccountAddData.class);
        from("direct:input")
        .log("   In AccountAddRoute   ")
        .marshal(bindy)
        .log("Got message:${body}");
        .to(???????_)

My Apologies. Not a good explanation of what I am trying to do.
I have An Account POJO that is being built thru FORM. I need to save
it in 2 different formats. Incoming just the way it is and in a
fixed format to be sent to Mainframe. This is what I get from the form

Code1=12          x , Code2=200

I initiate rout by sending body of form in accountAddData Instance

producerTemplate.sendBody("direct:input", accountAddData);

public class AccountAddRoute extends RouteBuilder{
    public void configure() throws Exception {
        DataFormat bindy = new BindyFixedLengthDataFormat(AccountAddData.class);
        from("direct:input")
        .log("   In AccountAddRoute   ")
        .marshal(bindy)
        .log("Got message:${body}");
        .to(???????_)

Just for Testing purposes my Account Bindy Pojo is below
    @DataField(pos =1, length=15, paddingChar='Z', trim=true, align="L")
    private String Code1;

    @DataField(pos =2, length=10, paddingChar='Z',  align="L")
    private String Code2;

When I log Body, I get >>

Got message:12          xZZ200ZZZZZZZ

However, my question is how do I create the new Instance in the
BINDY Format SO I can use it

==========
I did add processor and when I do display of body in processor >>

log.info("   In MyProcessor           =    " + exchange.getIn().getBody());
In MyProcessor           =    [B@3338b2b9
I was expecting to have the getter/setters available after getBody for the
accoountAddData instance. But obviously I don’t have a good understanding
of camel
exchange.getIn().getBody().????

Body:
Are you trying to unmarshal the incoming data? If thats the case, then you would need to use the following code.

  from("direct:input")
   .log("   In AccountAddRoute   ")
   .unmarshal(new BindyFixedLengthDataFormat(AccountAddData.class))
   .log("Got message:${body}");
   .to(???????_)


问:
How compare elements of lists when lists are stored as strings
I have two arrays:

```<code>arr1 = [ "B,C,D"
         "W,F,G"
         "M,S,E"
       ]
arr2 = [E]
</code>```

and want to compare the 3rd elements of the comma-separated strings (so "D" or "G" or "E") against doesn't have the contents of arr2. If that 3rd element is not equal to the element in arr2, I want to output the entire string from arr1.

I wrote this code but didn't give me the response that I need:

```<code> for(var k=0 ; k<A.length ; k++){
    if(A[k].split(",")[2] !== E) {
       finalSuccessServices = A;
       console.log(finalSuccessServices );
     }
</code>```

How can I fix my code to output lines that fit my goal above?

答:
If what you want is to just check the third value of your comma separated string of arrays against the 0th element in your second array, the below snippet would suffice.

const arr1 = ["B,C,D", "W,F,G", "M,S,E", "X,Y,Z"];
const arr2 = ["E"];

for( let ele of arr1 ) {
  if (arr2[0] !== ele.split(',')[2] ) {
    console.log('match', ele);
  }
}```

Adding your code in question as snippet would make it easier to understand what you're trying to accomplish.

Body:
I have two arrays:

arr1 = [ "B,C,D"
         "W,F,G"
         "M,S,E"
       ]
arr2 = [E]

and want to compare the 3rd elements of the comma-separated strings (so "D" or "G" or "E") against doesn't have the contents of arr2. If that 3rd element is not equal to the element in arr2, I want to output the entire string from arr1.

I wrote this code but didn't give me the response that I need:

 for(var k=0 ; k<A.length ; k++){
    if(A[k].split(",")[2] !== E) {
       finalSuccessServices = A;
       console.log(finalSuccessServices );
     }

How can I fix my code to output lines that fit my goal above?

Body:
If what you want is to just check the third value of your comma separated string of arrays against the 0th element in your second array, the below snippet would suffice.

const arr1 = ["B,C,D", "W,F,G", "M,S,E", "X,Y,Z"];
const arr2 = ["E"];

for( let ele of arr1 ) {
  if (arr2[0] !== ele.split(',')[2] ) {
    console.log('match', ele);
  }
}

Adding your code in question as snippet would make it easier to understand what you're trying to accomplish.


问:
CustomObject as Datasource doesn't update Control
If I bind an BindingList(Of FooBar) to the datasource of my datagrid the controls gets updated whenever I add an item to this BindingList. For example:

```<code>Public Class FooBar
    Public Property Name As String
    Public Property Value As String
End Class

Private obj As BindingList(Of FooBar)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    DataGridFooBars.DataSource = obj
End Sub

Private Sub btnNewFooBar(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewFooBar.Click
    obj.Add(New FooBar() With { .Name = "Name", .Value = "Value"})
End Sub
</code>```

When doing this the grid gets added a new row every time I press the New FooBar button.

Now When I create a Class FoobarList that inherits BindingList(Of FooBar) and bind an object of FoobarList to the datagrid this works exactly the same.

Now when I have a Class that inherits BindingList(Of T). When I bind an object from this Class to the datasource of a grid and add new items to it the grid doesn't get updated.

My class:

```<code>Public Class ProfelList(Of T)
    Inherits System.ComponentModel.BindingList(Of T)
    Implements IBindingList

    Private originalList As List(Of T)
    Private sortDirection As ListSortDirection
    Private sortProperty As PropertyDescriptor

    Private populateBaseList As Action(Of ProfelList(Of T), List(Of T)) = Sub(a, b) a.ResetItems(b)
    Shared cachedOrderByExpressions As New Dictionary(Of String, Func(Of List(Of T), IEnumerable(Of T)))()

    Public SortMapping As New ProfelSortMapper

    Protected Overrides ReadOnly Property SupportsSortingCore() As Boolean
        Get
            Return True
        End Get
    End Property

    Protected Overrides ReadOnly Property SortDirectionCore() As ListSortDirection
        Get
            Return sortDirection
        End Get
    End Property

    Protected Overrides ReadOnly Property SortPropertyCore() As PropertyDescriptor
        Get
            Return sortProperty
        End Get
    End Property

    Public Sub New()
        originalList = New List(Of T)()
    End Sub

    Public Sub New(ByVal enumerable As IEnumerable(Of T))
        originalList = enumerable.ToList()
        populateBaseList(Me, originalList)
    End Sub

    Public Sub New(ByVal list As List(Of T))
        originalList = list
        populateBaseList(Me, originalList)
    End Sub

    Protected Overrides Sub ApplySortCore(ByVal prop As PropertyDescriptor, ByVal direction As ListSortDirection)
        sortProperty = prop

        Dim orderByMethodName = If(sortDirection = ListSortDirection.Ascending, "OrderBy", "OrderByDescending")
        Dim cacheKey As String

        If SortMapping.ContainsKey(prop.Name.ToLower) Then
            cacheKey = Convert.ToString(GetType(T).GUID.ToString & SortMapping(prop.Name.ToLower)) & orderByMethodName
        Else
            cacheKey = Convert.ToString(GetType(T).GUID.ToString & prop.Name) & orderByMethodName
        End If

        If Not cachedOrderByExpressions.ContainsKey(cacheKey) Then
            CreateOrderByMethod(prop, orderByMethodName, cacheKey)
        End If

        ResetItems(cachedOrderByExpressions(cacheKey)(originalList).ToList())
        ResetBindings()
        sortDirection = If(sortDirection = ListSortDirection.Ascending, ListSortDirection.Descending, ListSortDirection.Ascending)
    End Sub

    Private Sub CreateOrderByMethod(ByVal prop As PropertyDescriptor, ByVal orderByMethodName As String, ByVal cacheKey As String)
        Dim sourceParameter = Expression.Parameter(GetType(List(Of T)), "source")
        Dim lambdaParameter = Expression.Parameter(GetType(T), "lambdaParameter")
        Dim accesedMember As Reflection.PropertyInfo

        If SortMapping.ContainsKey(prop.Name.ToLower) Then
            accesedMember = GetType(T).GetProperty(SortMapping(prop.Name.ToLower))
        Else
            accesedMember = GetType(T).GetProperty(prop.Name)
        End If

        Dim propertySelectorLambda = Expression.Lambda(Expression.MakeMemberAccess(lambdaParameter, accesedMember), lambdaParameter)
        Dim orderByMethod = GetType(Enumerable).GetMethods().Where(Function(a) a.Name = orderByMethodName AndAlso a.GetParameters().Length = 2).[Single]().MakeGenericMethod(GetType(T), accesedMember.PropertyType)

        Dim orderByExpression = Expression.Lambda(Of Func(Of List(Of T), IEnumerable(Of T)))(Expression.[Call](orderByMethod, New Expression() {sourceParameter, propertySelectorLambda}), sourceParameter)

        cachedOrderByExpressions.Add(cacheKey, orderByExpression.Compile())
    End Sub

    Protected Overrides Sub RemoveSortCore()
        ResetItems(originalList)
    End Sub

    Private Sub ResetItems(ByVal items As List(Of T))
        MyBase.ClearItems()

        For i As Integer = 0 To items.Count - 1
            MyBase.InsertItem(i, items(i))
        Next
    End Sub

    Protected Overrides Sub OnListChanged(ByVal e As ListChangedEventArgs)
        originalList = MyBase.Items.ToList()
    End Sub

    Public Function Find(ByVal match As System.Predicate(Of T)) As T
        Return Me.ToList.Find(match)
    End Function

    Public Function FindAll(ByVal match As System.Predicate(Of T)) As ProfelList(Of T)
        Return New ProfelList(Of T)(DirectCast(Me.ToList.FindAll(match), List(Of T)))
    End Function

End Class
</code>```

So when I Do:

```<code>Private obj As ProfelList(Of FooBar)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    DataGridFooBars.DataSource = obj
End Sub

Private Sub btnNewFooBar(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewFooBar.Click
    obj.Add(New FooBar() With { .Name = "Name", .Value = "Value"})
End Sub
</code>```

The datagrid doesn't update it rows. The datasource obj does increase in items.

Whats the difference between this ProfelList(Of FooBar) and BindingList(Of FooBar) or FooBarList? I have no clue why this isn't working.

答: I think you have to implement IObservable to achieve this.</p>

Body:
If I bind an BindingList(Of FooBar) to the datasource of my datagrid the controls gets updated whenever I add an item to this BindingList. For example:

Public Class FooBar
    Public Property Name As String
    Public Property Value As String
End Class

Private obj As BindingList(Of FooBar)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    DataGridFooBars.DataSource = obj
End Sub

Private Sub btnNewFooBar(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewFooBar.Click
    obj.Add(New FooBar() With { .Name = "Name", .Value = "Value"})
End Sub

When doing this the grid gets added a new row every time I press the New FooBar button.

Now When I create a Class FoobarList that inherits BindingList(Of FooBar) and bind an object of FoobarList to the datagrid this works exactly the same.

Now when I have a Class that inherits BindingList(Of T). When I bind an object from this Class to the datasource of a grid and add new items to it the grid doesn't get updated.

My class:

Public Class ProfelList(Of T)
    Inherits System.ComponentModel.BindingList(Of T)
    Implements IBindingList

    Private originalList As List(Of T)
    Private sortDirection As ListSortDirection
    Private sortProperty As PropertyDescriptor

    Private populateBaseList As Action(Of ProfelList(Of T), List(Of T)) = Sub(a, b) a.ResetItems(b)
    Shared cachedOrderByExpressions As New Dictionary(Of String, Func(Of List(Of T), IEnumerable(Of T)))()

    Public SortMapping As New ProfelSortMapper

    Protected Overrides ReadOnly Property SupportsSortingCore() As Boolean
        Get
            Return True
        End Get
    End Property

    Protected Overrides ReadOnly Property SortDirectionCore() As ListSortDirection
        Get
            Return sortDirection
        End Get
    End Property

    Protected Overrides ReadOnly Property SortPropertyCore() As PropertyDescriptor
        Get
            Return sortProperty
        End Get
    End Property

    Public Sub New()
        originalList = New List(Of T)()
    End Sub

    Public Sub New(ByVal enumerable As IEnumerable(Of T))
        originalList = enumerable.ToList()
        populateBaseList(Me, originalList)
    End Sub

    Public Sub New(ByVal list As List(Of T))
        originalList = list
        populateBaseList(Me, originalList)
    End Sub

    Protected Overrides Sub ApplySortCore(ByVal prop As PropertyDescriptor, ByVal direction As ListSortDirection)
        sortProperty = prop

        Dim orderByMethodName = If(sortDirection = ListSortDirection.Ascending, "OrderBy", "OrderByDescending")
        Dim cacheKey As String

        If SortMapping.ContainsKey(prop.Name.ToLower) Then
            cacheKey = Convert.ToString(GetType(T).GUID.ToString & SortMapping(prop.Name.ToLower)) & orderByMethodName
        Else
            cacheKey = Convert.ToString(GetType(T).GUID.ToString & prop.Name) & orderByMethodName
        End If

        If Not cachedOrderByExpressions.ContainsKey(cacheKey) Then
            CreateOrderByMethod(prop, orderByMethodName, cacheKey)
        End If

        ResetItems(cachedOrderByExpressions(cacheKey)(originalList).ToList())
        ResetBindings()
        sortDirection = If(sortDirection = ListSortDirection.Ascending, ListSortDirection.Descending, ListSortDirection.Ascending)
    End Sub

    Private Sub CreateOrderByMethod(ByVal prop As PropertyDescriptor, ByVal orderByMethodName As String, ByVal cacheKey As String)
        Dim sourceParameter = Expression.Parameter(GetType(List(Of T)), "source")
        Dim lambdaParameter = Expression.Parameter(GetType(T), "lambdaParameter")
        Dim accesedMember As Reflection.PropertyInfo

        If SortMapping.ContainsKey(prop.Name.ToLower) Then
            accesedMember = GetType(T).GetProperty(SortMapping(prop.Name.ToLower))
        Else
            accesedMember = GetType(T).GetProperty(prop.Name)
        End If

        Dim propertySelectorLambda = Expression.Lambda(Expression.MakeMemberAccess(lambdaParameter, accesedMember), lambdaParameter)
        Dim orderByMethod = GetType(Enumerable).GetMethods().Where(Function(a) a.Name = orderByMethodName AndAlso a.GetParameters().Length = 2).[Single]().MakeGenericMethod(GetType(T), accesedMember.PropertyType)

        Dim orderByExpression = Expression.Lambda(Of Func(Of List(Of T), IEnumerable(Of T)))(Expression.[Call](orderByMethod, New Expression() {sourceParameter, propertySelectorLambda}), sourceParameter)

        cachedOrderByExpressions.Add(cacheKey, orderByExpression.Compile())
    End Sub

    Protected Overrides Sub RemoveSortCore()
        ResetItems(originalList)
    End Sub

    Private Sub ResetItems(ByVal items As List(Of T))
        MyBase.ClearItems()

        For i As Integer = 0 To items.Count - 1
            MyBase.InsertItem(i, items(i))
        Next
    End Sub

    Protected Overrides Sub OnListChanged(ByVal e As ListChangedEventArgs)
        originalList = MyBase.Items.ToList()
    End Sub

    Public Function Find(ByVal match As System.Predicate(Of T)) As T
        Return Me.ToList.Find(match)
    End Function

    Public Function FindAll(ByVal match As System.Predicate(Of T)) As ProfelList(Of T)
        Return New ProfelList(Of T)(DirectCast(Me.ToList.FindAll(match), List(Of T)))
    End Function

End Class

So when I Do:

Private obj As ProfelList(Of FooBar)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    DataGridFooBars.DataSource = obj
End Sub

Private Sub btnNewFooBar(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewFooBar.Click
    obj.Add(New FooBar() With { .Name = "Name", .Value = "Value"})
End Sub

The datagrid doesn't update it rows. The datasource obj does increase in items.

Whats the difference between this ProfelList(Of FooBar) and BindingList(Of FooBar) or FooBarList? I have no clue why this isn't working.


问:
Git : git status don't show new files and git add return fatal file is outside repository
I created new files in my project and git status return
Your branch is up to date with 'origin/dev/master'.
nothing to commit, working tree clean

When i try to add new files with git add , i have
fatal: file is outside repository.

But when a make change in other old files , git status track change and i can commit it.

答:
First, you can check if your file is ignored with:

```<code>git check-ignore -v -- afile
</code>```

Second, that error message ("is outside repository") will be clarified with Git 2.26 (Q1 2020).

See commit e0020b2 (15 Feb 2020) by Emily Shaffer (nasamuffin).

(Merged by Junio C Hamano -- gitster -- in commit f97741f, 17 Feb 2020)

prefix_path: show gitdir when arg is outside repo

Signed-off-by: Emily Shaffer

  Acked-by: brian m. carlson

When developing a script, it can be painful to understand why Git thinks something is outside the current repo, if the current repo isn't what the user thinks it is.

Since this can be tricky to diagnose, especially in cases like submodules or nested worktrees, let's give the user a hint about which repository is offended about that path.

The error message will then be:

```<code>aFile is outside repository at 'full/path/of/repo'
                            ^^^^^^^^^^^^^^^^^^^^^^
                                   (new!)
</code>```

And, still with Git 2.25.2 (March 2020), the update above, to show the location of working tree in the error message, did not consider the possibility that a git command may be run in a bare repository, which has been corrected.

See commit 5c20398 (03 Mar 2020) by Emily Shaffer (nasamuffin).

(Merged by Junio C Hamano -- gitster -- in commit e96327c, 16 Mar 2020)

prefix_path: show gitdir if worktree unavailable

Signed-off-by: Emily Shaffer

  [jc: added minimum tests, with help from Szeder Gábor]

  Signed-off-by: Junio C Hamano

If there is no worktree at present, we can still hint the user about Git's current directory by showing them the absolute path to the Git directory. Even though the Git directory doesn't make it as easy to locate the worktree in question, it can still help a user figure out what's going on while developing a script.

This fixes a segmentation fault introduced in e0020b2f ("prefix_path: show gitdir when arg is outside repo", 2020-02-14).

Body:
First, you can check if your file is ignored with:

git check-ignore -v -- afile

Second, that error message ("is outside repository") will be clarified with Git 2.26 (Q1 2020).

See commit e0020b2 (15 Feb 2020) by Emily Shaffer (nasamuffin).

(Merged by Junio C Hamano -- gitster -- in commit f97741f, 17 Feb 2020)

prefix_path: show gitdir when arg is outside repo

Signed-off-by: Emily Shaffer

  Acked-by: brian m. carlson

When developing a script, it can be painful to understand why Git thinks something is outside the current repo, if the current repo isn't what the user thinks it is.

Since this can be tricky to diagnose, especially in cases like submodules or nested worktrees, let's give the user a hint about which repository is offended about that path.

The error message will then be:

aFile is outside repository at 'full/path/of/repo'
                            ^^^^^^^^^^^^^^^^^^^^^^
                                   (new!)

And, still with Git 2.25.2 (March 2020), the update above, to show the location of working tree in the error message, did not consider the possibility that a git command may be run in a bare repository, which has been corrected.

See commit 5c20398 (03 Mar 2020) by Emily Shaffer (nasamuffin).

(Merged by Junio C Hamano -- gitster -- in commit e96327c, 16 Mar 2020)

prefix_path: show gitdir if worktree unavailable

Signed-off-by: Emily Shaffer

  [jc: added minimum tests, with help from Szeder Gábor]

  Signed-off-by: Junio C Hamano

If there is no worktree at present, we can still hint the user about Git's current directory by showing them the absolute path to the Git directory. Even though the Git directory doesn't make it as easy to locate the worktree in question, it can still help a user figure out what's going on while developing a script.

This fixes a segmentation fault introduced in e0020b2f ("prefix_path: show gitdir when arg is outside repo", 2020-02-14).