问:
Unable to send emails from Godaddy Plesk Hosting for ASP .NET project
I am having a hard time wrapping my head around this issue. I followed this link- https://ca.godaddy.com/help/send-email-using-systemnetmail-in-windows-hosting-19291. Basically, they want us to use their network host it seems.

Can someone help me figure out what I need to fix this?

This is the code I am using in web.config-

```<code>    <mailSettings>
    <smtp from="tefgh@gmail.com">
    <network host="relay-hosting.secureserver.net" port="25" />
    </smtp>
    </mailSettings>
</code>```

In controller-

```<code>    MailMessage mail = new MailMessage();
    mail.From = new MailAddress("tefgh@gmail.com");
    mail.To.Add("abcd@gmail.com");
    mail.Subject = "Hello";
    mail.Body = "body";
    SmtpClient smtp = new SmtpClient();
    smtp.UseDefaultCredentials = false;
    smtp.Send(mail);
</code>```

I want to receive the email successfully. It does not even throw any errors. When I use real Gmail SMTP settings, then it throws error

Body:
I am having a hard time wrapping my head around this issue. I followed this link- https://ca.godaddy.com/help/send-email-using-systemnetmail-in-windows-hosting-19291. Basically, they want us to use their network host it seems.

Can someone help me figure out what I need to fix this?

This is the code I am using in web.config-

    <mailSettings>
    <smtp from="tefgh@gmail.com">
    <network host="relay-hosting.secureserver.net" port="25" />
    </smtp>
    </mailSettings>

In controller-

    MailMessage mail = new MailMessage();
    mail.From = new MailAddress("tefgh@gmail.com");
    mail.To.Add("abcd@gmail.com");
    mail.Subject = "Hello";
    mail.Body = "body";
    SmtpClient smtp = new SmtpClient();
    smtp.UseDefaultCredentials = false;
    smtp.Send(mail);

I want to receive the email successfully. It does not even throw any errors. When I use real Gmail SMTP settings, then it throws error


来源: stackexchange

问:
In singleton test container, how can we use the value inside the application.yml to do the configuration?
In singleton test container, i have

```<code>@ActiveProfiles("Testing")
@SpringBootTest
abstract class AbstractContainerBaseTest {

static final MySQLContainer MY_SQL_CONTAINER;

private static String userName;

@Value("spring.datasource.username")
public void setPrivateName(String userName) {
    AbstractContainerBaseTest.userName = userName;
}

static {
    System.out.println(userName);
    MY_SQL_CONTAINER = new MySQLContainer();
    MY_SQL_CONTAINER.start();
    }

@DynamicPropertySource
static void overrideTestProperties(DynamicPropertyRegistry registry){
    registry.add("spring.datasource.url", mySQLContainer::getJdbcUrl);
    registry.add("spring.datasource.username", mySQLContainer::getUsername);
    registry.add("spring.datasource.password", mySQLContainer::getPassword);
   }
}
</code>```

I tried to print out the username but it is always print as null, did i do anything wrong?

in application.yml, i have

```<code> spring:
  profiles: Testing
  datasource:
    url: jdbc:tc:mysql:5.1.0:///test
    username: aa
    password: aa
    hikari:
      maximum-pool-size: 20
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL8Dialect
</code>```

Many thanks.

ContentLicense: CC BY-SA 4.0

Body:
In singleton test container, i have

@ActiveProfiles("Testing")
@SpringBootTest
abstract class AbstractContainerBaseTest {

static final MySQLContainer MY_SQL_CONTAINER;

private static String userName;

@Value("spring.datasource.username")
public void setPrivateName(String userName) {
    AbstractContainerBaseTest.userName = userName;
}

static {
    System.out.println(userName);
    MY_SQL_CONTAINER = new MySQLContainer();
    MY_SQL_CONTAINER.start();
    }

@DynamicPropertySource
static void overrideTestProperties(DynamicPropertyRegistry registry){
    registry.add("spring.datasource.url", mySQLContainer::getJdbcUrl);
    registry.add("spring.datasource.username", mySQLContainer::getUsername);
    registry.add("spring.datasource.password", mySQLContainer::getPassword);
   }
}

I tried to print out the username but it is always print as null, did i do anything wrong?

in application.yml, i have

 spring:
  profiles: Testing
  datasource:
    url: jdbc:tc:mysql:5.1.0:///test
    username: aa
    password: aa
    hikari:
      maximum-pool-size: 20
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL8Dialect

Many thanks.


问:
Fixing: JsonNode not of type ObjectNode (but com.fasterxml.jackson.databind.node.ArrayNode), cannot call withArray() on it?
While an array with-in an array is legal in json -

This is valid json - { "id": [1, 2, { "a": [4, 5] }] }

But when I try to create an array within an array using jackson library - I am facing below error -

java.lang.UnsupportedOperationException: JsonNode not of type
ObjectNode (but com.fasterxml.jackson.databind.node.ArrayNode), cannot
call withArray() on it    at
com.fasterxml.jackson.databind.JsonNode.withArray(JsonNode.java:1107)

My code snippet is as below -

```<code>if (root.getNodeType().equals(JsonNodeType.ARRAY)) {
    if (currentElem.endsWith("[]")) {
        root = ((ArrayNode) root).withArray(currentElem.substring(0, currentElem.length() - 2)); //error line
        if (!((ArrayNode) root).has(value))
            ((ArrayNode) root).add(value);
    } else {
        ((ObjectNode) ((ArrayNode) root).addObject()).put(currentElem, value);
    }
}
</code>```

Is this as expected or are there any work arounds for this(like get/create an array obj first and then add edit the retrieved array and add it back... etc and ).

I am using jackson 2.13.4.

Body:
While an array with-in an array is legal in json -

This is valid json - { "id": [1, 2, { "a": [4, 5] }] }

But when I try to create an array within an array using jackson library - I am facing below error -

java.lang.UnsupportedOperationException: JsonNode not of type
ObjectNode (but com.fasterxml.jackson.databind.node.ArrayNode), cannot
call withArray() on it    at
com.fasterxml.jackson.databind.JsonNode.withArray(JsonNode.java:1107)

My code snippet is as below -

if (root.getNodeType().equals(JsonNodeType.ARRAY)) {
    if (currentElem.endsWith("[]")) {
        root = ((ArrayNode) root).withArray(currentElem.substring(0, currentElem.length() - 2)); //error line
        if (!((ArrayNode) root).has(value))
            ((ArrayNode) root).add(value);
    } else {
        ((ObjectNode) ((ArrayNode) root).addObject()).put(currentElem, value);
    }
}

Is this as expected or are there any work arounds for this(like get/create an array obj first and then add edit the retrieved array and add it back... etc and ).

I am using jackson 2.13.4.


问:
Handlebars populate data according to selected item on drop down
I want to populate data acording to selected value on "Select" on handlebars.

My code(form) :

```<code><div class="row">
                            <div class="col-lg-6">
                                <label class="form-control-label" for="form-select">User</label>
                                <select class="form-select" aria-label="Default select example">
                                    {{#each users}}
                                        <option value="{{_id}}">{{_id}} - {{name}}</option>
                                    {{/each}}
                                </select>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group">
                                    <label class="form-control-label" for="input-email">{{selectedUser _id}}</label>
                                    <input type="email" id="input-email" class="form-control"
                                        placeholder="jesse@example.com" value="">
                                </div>
                            </div>
                        </div>
</code>```

I want to load the user's email after selecting the ID from the top select menu.

I created handlebar helper :

```<code>selectedUser: (option) => {
    return User.findOne({ _id: option });
  },
</code>```

I want to send the selected ID to that helper.

Body:
I want to populate data acording to selected value on "Select" on handlebars.

My code(form) :

                                User
                                <select class="form-select" aria-label="Default select example">
                                    {{#each users}}
                                        <option value="{{_id}}">{{_id}} - {{name}}</option>
                                    {{/each}}
                                </select>

                                    {{selectedUser _id}}
                                    <input type="email" id="input-email" class="form-control"
                                        placeholder="jesse@example.com" value="">

I want to load the user's email after selecting the ID from the top select menu.

I created handlebar helper :

selectedUser: (option) => {
    return User.findOne({ _id: option });
  },

I want to send the selected ID to that helper.


问:
How to update KeyResult Actual Values Using Rally REST API
I want to update actual value for some Objective Key Result.

I am using following curl-

```<code>curl --location -g --request POST 'https://rally1.rallydev.com/slm/webservice/v2.0/keyresultactualvalue/{Key Result UUID}' \
--header 'zsessionid: xxxxxxxxxxxxxxxxxxxxxxxx' \
--header 'Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxx' \
--header 'Content-Type: application/json' \
--header 'Cookie: JSESSIONID=gc-app-xxxxxxxxxxxxxxxxxxx.gc-app-18; SERVERID=xxxxxxxxxxxxxxxxxxxxx; SUBBUCKETID=100; SUBSCRIPTIONID=100; __cflb=xxxxxxxxxxxxxxxxxxxxxx; _username=test@ktestlera.io' \
--data-raw '{

    "KeyResultActualValues":{

        "Date":"2023-10-10",
        "ActualValue":"100"
    }
}'
</code>```

But I am getting error:

```<code>{
    "OperationResult": {
        "_rallyAPIMajor": "2",
        "_rallyAPIMinor": "0",
        "Errors": [
            "Cannot parse number: For input string: \"ObjectReference[oid=null, type=null]\""
        ],
        "Warnings": []
    }
}
</code>```

I am sure that I am sending wrong request body.
Please help me in that.

Body:
I want to update actual value for some Objective Key Result.

I am using following curl-

curl --location -g --request POST 'https://rally1.rallydev.com/slm/webservice/v2.0/keyresultactualvalue/{Key Result UUID}' \
--header 'zsessionid: xxxxxxxxxxxxxxxxxxxxxxxx' \
--header 'Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxx' \
--header 'Content-Type: application/json' \
--header 'Cookie: JSESSIONID=gc-app-xxxxxxxxxxxxxxxxxxx.gc-app-18; SERVERID=xxxxxxxxxxxxxxxxxxxxx; SUBBUCKETID=100; SUBSCRIPTIONID=100; __cflb=xxxxxxxxxxxxxxxxxxxxxx; _username=test@ktestlera.io' \
--data-raw '{

    "KeyResultActualValues":{

        "Date":"2023-10-10",
        "ActualValue":"100"
    }
}'

But I am getting error:

{
    "OperationResult": {
        "_rallyAPIMajor": "2",
        "_rallyAPIMinor": "0",
        "Errors": [
            "Cannot parse number: For input string: \"ObjectReference[oid=null, type=null]\""
        ],
        "Warnings": []
    }
}

I am sure that I am sending wrong request body.
Please help me in that.


问:
How to get the same object from another process?
Is it possible to use the same object in two process?

Here are the steps in my case:
First, when I open the particular application, the DLL file will create a class and get the object that from the application.
Next, I open an EXE file.
The EXE file will use this object and do some procedure.

When I open the particular application, it will create a form application automatically.
Here is my code in DLL file:

First:

```<code>public class myClassSample
{
    public object module
    {
        get;
        set;
    }
}
</code>```

Second:

```<code>Form newForm;
static BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;

myClassSample classSample = new myClassSample();
classSample.module = module;
Assembly assembly = Assembly.LoadFrom("mySample.exe");
Type formType = assembly.GetType("mySample.Form1");
Form resultForm = assembly.CreateInstance(formType.FullName) as Form;
newForm = resultForm;
Type type = newForm.GetType();
PropertyInfo propertyInfo = type.GetProperty("serverModule", flags);
propertyInfo.SetValue(newForm, module);
newForm.Show();
</code>```

It seems to be ok, but I have to open a certain application first.
I wish I could open the EXE file individually.

Like, when I open the EXE file, the object is null.
The object will get after the specific application is opening.

Body:
Is it possible to use the same object in two process?

Here are the steps in my case:
First, when I open the particular application, the DLL file will create a class and get the object that from the application.
Next, I open an EXE file.
The EXE file will use this object and do some procedure.

When I open the particular application, it will create a form application automatically.
Here is my code in DLL file:

First:

public class myClassSample
{
    public object module
    {
        get;
        set;
    }
}

Second:

Form newForm;
static BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;

myClassSample classSample = new myClassSample();
classSample.module = module;
Assembly assembly = Assembly.LoadFrom("mySample.exe");
Type formType = assembly.GetType("mySample.Form1");
Form resultForm = assembly.CreateInstance(formType.FullName) as Form;
newForm = resultForm;
Type type = newForm.GetType();
PropertyInfo propertyInfo = type.GetProperty("serverModule", flags);
propertyInfo.SetValue(newForm, module);
newForm.Show();

It seems to be ok, but I have to open a certain application first.
I wish I could open the EXE file individually.

Like, when I open the EXE file, the object is null.
The object will get after the specific application is opening.


问:
Is there a Universal Modal Form?, VB .net framework windows forms
Using VB .NET Framework,  I’m trying to develop an educational windows forms application that will require a child to answer a challenge before allowing to continue normal use of the device (Desktop pc).

I looked for something like a “Universal modal form”, but couldn’t find anything like that. Actually, windows is specifically design to impede user interface blockage by rogue application.

I was able to pause some running processes such as the browsers and media players until the modal form containing the challenge is addressed, but because the device has multiple monitors, the paused applications remain visible and they crash when the child frustratingly clicks on them. Also, game applications from the Microsoft store run in their own sandboxes and I couldn’t find a way to pause them.
Any suggestions?


问:
Generic XUnit C# .NET Core API Tests with different models
I would like to write a generic XUnit test for my CRUD API methods. However, I am not sure how to implement this with different models.

I wanted to use the following code:

```<code>public class BaseControllerTests<TModel> : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;
    private List<string> _modelIds = new List<string> { };

    public BaseControllerTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task TestCreateModel()
    {
        // Arrange
        var client = _factory.CreateClient();
        var newModel = new TModel
        {
            // Here normally I would initialize the properties
        };

        // Act
        var response = await client.PostAsJsonAsync("api/[controller]", newModel);
        response.EnsureSuccessStatusCode();
        var model = await response.Content.ReadFromJsonAsync<TModel>();

        // Assert
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        // Here I would normally assert the properties of the model

        // Add model id to the list to delete later
        _modelIds.Add(model.Id);
    }
}
</code>```

If I have different models like this:

```<code>Copy code
public class BaseModel
{
    public string Id { get; set; }
    public string CreatedBy { get; set; }
    public DateTime CreatedDate { get; set; }
    public string UpdatedBy { get; set; }
    public DateTime UpdatedDate { get; set; }
}

public class ProductModel : BaseModel
{
    public string ProductName { get; set; }
    public double Price { get; set; }
}

public class UserModel : BaseModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
</code>```

Is there a way to implement a generic xUnit test? Or is it a stupid idea?

Body:
I would like to write a generic XUnit test for my CRUD API methods. However, I am not sure how to implement this with different models.

I wanted to use the following code:

public class BaseControllerTests<TModel> : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;
    private List<string> _modelIds = new List<string> { };

    public BaseControllerTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task TestCreateModel()
    {
        // Arrange
        var client = _factory.CreateClient();
        var newModel = new TModel
        {
            // Here normally I would initialize the properties
        };

        // Act
        var response = await client.PostAsJsonAsync("api/[controller]", newModel);
        response.EnsureSuccessStatusCode();
        var model = await response.Content.ReadFromJsonAsync<TModel>();

        // Assert
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        // Here I would normally assert the properties of the model

        // Add model id to the list to delete later
        _modelIds.Add(model.Id);
    }
}

If I have different models like this:

Copy code
public class BaseModel
{
    public string Id { get; set; }
    public string CreatedBy { get; set; }
    public DateTime CreatedDate { get; set; }
    public string UpdatedBy { get; set; }
    public DateTime UpdatedDate { get; set; }
}

public class ProductModel : BaseModel
{
    public string ProductName { get; set; }
    public double Price { get; set; }
}

public class UserModel : BaseModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Is there a way to implement a generic xUnit test? Or is it a stupid idea?


问:
How to train large ner dataset(400K) with Spacy in Google Colab. I want to override Allocated memory error
I want to train a Spacy Custom ner model with my own data using Spacy-transformers in Google Colab. I have already done this training before. But this time, I have a huge dataset of 500K entries. This is resulting in a warning -- > tcmalloc: large alloc 2147491840 bytes == 0x7f10d6f7c000 @  0x7f1315a882a4 0x5d6f4c 0x45fe31 0x5eccd1 0x5ed150 0x5aae14 0x4997c7 0x5d8868 0x4997a2 0x5d8868 0x4997a2 0x4f6097 0x55e146 0x4f6097 0x55e146 0x4f6097 0x5d1e94 0x5d8cdf 0x55dc1e 0x4f6097 0x4f6ee4 0x55e146 0x4f6097 0x55e146 0x55d078 0x5d8941 0x49abe4 0x55d078 0x5d8941 0x49abe4 0x55cd91

I understood that the Colab is not able to run all my data at once as the allocated memory has been breached. So the training is interupted.

So I want to train the model with less data(50K) and update the NER model with the rest of the data eventually. Therefore I am looking for ways to update spacy v3 model with new training data.

I would appreciate any help regarding this. Thank you!

I am training the model through the cli with the config file.
!python -m spacy train $config_file_name --output spacy_output --paths.train training_data.spacy --paths.dev valid_data.spacy --gpu-id 0

The configuration file for the training that I am using is below:

```<code>[paths]
train = null
dev = null
vectors = null
init_tok2vec = null

[system]
gpu_allocator = "pytorch"
seed = 0

[nlp]
lang = "en"
pipeline = ["transformer","ner"]
batch_size = 128
disabled = []
before_creation = null
after_creation = null
after_pipeline_creation = null
tokenizer = {"@tokenizers":"spacy.Tokenizer.v1"}

[components]

[components.ner]
factory = "ner"
moves = null
update_with_oracle_cut_size = 100

[components.ner.model]
@architectures = "spacy.TransitionBasedParser.v2"
state_type = "ner"
extra_state_tokens = false
hidden_width = 64
maxout_pieces = 2
use_upper = false
nO = null

[components.ner.model.tok2vec]
@architectures = "spacy-transformers.TransformerListener.v1"
grad_factor = 1.0
pooling = {"@layers":"reduce_mean.v1"}
upstream = "transformer"

[components.transformer]
factory = "transformer"
max_batch_items = 4096
set_extra_annotations = {"@annotation_setters":"spacy-transformers.null_annotation_setter.v1"}

[components.transformer.model]
@architectures = "spacy-transformers.TransformerModel.v3"
name = "roberta-base"
mixed_precision = false

[components.transformer.model.get_spans]
@span_getters = "spacy-transformers.strided_spans.v1"
window = 128
stride = 96

[components.transformer.model.grad_scaler_config]

[components.transformer.model.tokenizer_config]
use_fast = true

[components.transformer.model.transformer_config]

[corpora]

[corpora.dev]
@readers = "spacy.Corpus.v1"
path = ${paths.dev}
max_length = 0
gold_preproc = false
limit = 0
augmenter = null

[corpora.train]
@readers = "spacy.Corpus.v1"
path = ${paths.train}
max_length = 0
gold_preproc = false
limit = 0
augmenter = null

[training]
accumulate_gradient = 3
dev_corpus = "corpora.dev"
train_corpus = "corpora.train"
seed = ${system.seed}
gpu_allocator = ${system.gpu_allocator}
dropout = 0.0
patience = 1200
max_epochs = 0
max_steps = 20000
eval_frequency = 50
frozen_components = []
before_to_disk = null

[training.batcher]
@batchers = "spacy.batch_by_padded.v1"
discard_oversize = true
size = 2000
buffer = 256
get_length = null

[training.logger]
@loggers = "spacy.ConsoleLogger.v1"
progress_bar = false

[training.optimizer]
@optimizers = "Adam.v1"
beta1 = 0.9
beta2 = 0.999
L2_is_weight_decay = true
L2 = 0.01
grad_clip = 1.0
use_averages = false
eps = 0.00000001

[training.optimizer.learn_rate]
@schedules = "warmup_linear.v1"
warmup_steps = 250
total_steps = 20000
initial_rate = 0.001

[training.score_weights]
ents_per_type = null
ents_f = 1.0
ents_p = 0.0
ents_r = 0.0

[pretraining]

[initialize]
vectors = ${paths.vectors}
init_tok2vec = ${paths.init_tok2vec}
vocab_data = null
lookups = null
before_init = null
after_init = null

[initialize.components]

[initialize.tokenizer]

</code>```

Body:
I want to train a Spacy Custom ner model with my own data using Spacy-transformers in Google Colab. I have already done this training before. But this time, I have a huge dataset of 500K entries. This is resulting in a warning -- > tcmalloc: large alloc 2147491840 bytes == 0x7f10d6f7c000 @  0x7f1315a882a4 0x5d6f4c 0x45fe31 0x5eccd1 0x5ed150 0x5aae14 0x4997c7 0x5d8868 0x4997a2 0x5d8868 0x4997a2 0x4f6097 0x55e146 0x4f6097 0x55e146 0x4f6097 0x5d1e94 0x5d8cdf 0x55dc1e 0x4f6097 0x4f6ee4 0x55e146 0x4f6097 0x55e146 0x55d078 0x5d8941 0x49abe4 0x55d078 0x5d8941 0x49abe4 0x55cd91

I understood that the Colab is not able to run all my data at once as the allocated memory has been breached. So the training is interupted.

So I want to train the model with less data(50K) and update the NER model with the rest of the data eventually. Therefore I am looking for ways to update spacy v3 model with new training data.

I would appreciate any help regarding this. Thank you!

I am training the model through the cli with the config file.
!python -m spacy train $config_file_name --output spacy_output --paths.train training_data.spacy --paths.dev valid_data.spacy --gpu-id 0

The configuration file for the training that I am using is below:

[paths]
train = null
dev = null
vectors = null
init_tok2vec = null

[system]
gpu_allocator = "pytorch"
seed = 0

[nlp]
lang = "en"
pipeline = ["transformer","ner"]
batch_size = 128
disabled = []
before_creation = null
after_creation = null
after_pipeline_creation = null
tokenizer = {"@tokenizers":"spacy.Tokenizer.v1"}

[components]

[components.ner]
factory = "ner"
moves = null
update_with_oracle_cut_size = 100

[components.ner.model]
@architectures = "spacy.TransitionBasedParser.v2"
state_type = "ner"
extra_state_tokens = false
hidden_width = 64
maxout_pieces = 2
use_upper = false
nO = null

[components.ner.model.tok2vec]
@architectures = "spacy-transformers.TransformerListener.v1"
grad_factor = 1.0
pooling = {"@layers":"reduce_mean.v1"}
upstream = "transformer"

[components.transformer]
factory = "transformer"
max_batch_items = 4096
set_extra_annotations = {"@annotation_setters":"spacy-transformers.null_annotation_setter.v1"}

[components.transformer.model]
@architectures = "spacy-transformers.TransformerModel.v3"
name = "roberta-base"
mixed_precision = false

[components.transformer.model.get_spans]
@span_getters = "spacy-transformers.strided_spans.v1"
window = 128
stride = 96

[components.transformer.model.grad_scaler_config]

[components.transformer.model.tokenizer_config]
use_fast = true

[components.transformer.model.transformer_config]

[corpora]

[corpora.dev]
@readers = "spacy.Corpus.v1"
path = ${paths.dev}
max_length = 0
gold_preproc = false
limit = 0
augmenter = null

[corpora.train]
@readers = "spacy.Corpus.v1"
path = ${paths.train}
max_length = 0
gold_preproc = false
limit = 0
augmenter = null

[training]
accumulate_gradient = 3
dev_corpus = "corpora.dev"
train_corpus = "corpora.train"
seed = ${system.seed}
gpu_allocator = ${system.gpu_allocator}
dropout = 0.0
patience = 1200
max_epochs = 0
max_steps = 20000
eval_frequency = 50
frozen_components = []
before_to_disk = null

[training.batcher]
@batchers = "spacy.batch_by_padded.v1"
discard_oversize = true
size = 2000
buffer = 256
get_length = null

[training.logger]
@loggers = "spacy.ConsoleLogger.v1"
progress_bar = false

[training.optimizer]
@optimizers = "Adam.v1"
beta1 = 0.9
beta2 = 0.999
L2_is_weight_decay = true
L2 = 0.01
grad_clip = 1.0
use_averages = false
eps = 0.00000001

[training.optimizer.learn_rate]
@schedules = "warmup_linear.v1"
warmup_steps = 250
total_steps = 20000
initial_rate = 0.001

[training.score_weights]
ents_per_type = null
ents_f = 1.0
ents_p = 0.0
ents_r = 0.0

[pretraining]

[initialize]
vectors = ${paths.vectors}
init_tok2vec = ${paths.init_tok2vec}
vocab_data = null
lookups = null
before_init = null
after_init = null

[initialize.components]

[initialize.tokenizer]


问:
Deleted poetry cache folder and cannot put things back
How to recreate the poetry cache folder, since I deleted it creating it again not helping. Now I've set the venv inside the project folder.</p>


问:
How to implement a customized Security Support Provider to auth a user on a cloud?
I want to provide an authentication mechanism on Windows for a user on a cloud.
The credential provider mostly satisfies this requirement with the premise that the user is a local user, Microsoft account or a domain user of this PC.
But I also would like to get escalated privilege as the user, even the user is only on a cloud, not a domain user or Microsoft account.

As far as I know, Microsoft provide a mechanism, SSP(Security Support Provider), kerberos and NTLM implements it.
There are few documents describing about SSP, such as The Windows Negotiation Extension and Writing NegoEx SSPs
Futhermore, Spgetextendedinformationfn in my current implementation is called though.
But I cannot find any further information about what the data I should response to the LSA.

Is there any sample code about SSP, or I should try another way to achieve my goal?


问:
Python, how to assign boolean comparison operators to variables?
I'd like to asign these operators to variables.
I have a flag that if is set to True uses > or >= in certain conditions, but when I set the flag to False I want to use < or <= instead.

Example:

```<code>up_down: bool = True
if up_down:
   flag1 = data['foo'] > data['foo'].shift(x)
   flag2 = data['foo'] >= data['foo2']
else:
   flag1 = data['foo'] < data['foo'].shift(x)
   flag2 = data['foo'] <= data['foo2']
</code>```

I want to achieve the same without duplicating the code, so the code would look like&work this:

```<code>if up_down:
  var1 = ">"
  var2 = ">="
else:
  var1 = "<"
  var2 = "<="
flag1 = data['foo'] var1 data['foo'].shift(x)
flag2 = data['foo'] var2 data['foo2']
</code>```

Is it possible?

Body:
I'd like to asign these operators to variables.
I have a flag that if is set to True uses > or >= in certain conditions, but when I set the flag to False I want to use < or <= instead.

Example:

up_down: bool = True
if up_down:
   flag1 = data['foo'] > data['foo'].shift(x)
   flag2 = data['foo'] >= data['foo2']
else:
   flag1 = data['foo'] < data['foo'].shift(x)
   flag2 = data['foo'] <= data['foo2']

I want to achieve the same without duplicating the code, so the code would look like&work this:

if up_down:
  var1 = ">"
  var2 = ">="
else:
  var1 = "<"
  var2 = "<="
flag1 = data['foo'] var1 data['foo'].shift(x)
flag2 = data['foo'] var2 data['foo2']

Is it possible?


问:
The AdWidget is already in the Widget tree create a new instance in the builder function in flutter
I am showing native ad inside my listview but i am getting this error sometime instead of ad and then scroll down and again scroll up then the ad appear?</p>


问:
python replit XML conversion not working for larger files - invalid token
I am using python on replit to convert XML files from endnote into a different XML format that can be opened in Microsoft Word's reference manager. When I tested on files with up to 6 records, it worked perfectly. When I tried on larger files with 30-50 records, it returned the following error:

```<code>  File "main.py", line 12, in convert_endnote_to_word
    root = ET.fromstring(endnote_xml_str)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/xml/etree/ElementTree.py", line 1320, in XML
    parser.feed(text)
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 2248
</code>```

My code is below:

```<code>import xml.etree.ElementTree as ET
def convert_endnote_to_word(endnote_xml_str):
    word_xml_str = '<?xml version="1.0" encoding="utf-8"?>\n'
    word_xml_str += '<b:Sources xmlns:b="http://schemas.openxmlformats.org/officeDocument/2006/bibliography" '
    word_xml_str += 'xmlns="http://schemas.openxmlformats.org/officeDocument/2006/bibliography" SelectedStyle="">\n'
    root = ET.fromstring(endnote_xml_str)
    for record in root.findall('./records/record'):
        source = {}
        word_xml_str += '  <b:Source>\n'
        year = record.find('./pub-dates/date').text
        source['year'] = year
        word_xml_str += f'    <b:Year>{source["year"]}</b:Year>\n'
        source['ref_type'] = record.find('./ref-type').get('name').replace(" ", "")
        word_xml_str += f'    <b:SourceType>{source["ref_type"]}</b:SourceType>\n'
        title = record.find('./titles/title').text
        source['title'] = title
        word_xml_str += f'    <b:Title>{source["title"]}</b:Title>\n'        authors = []
        for author in record.findall('./contributors/authors/author'):
            authors.append(author.text)
        source['authors'] = authors
        convert_authors_and_year(source)
        word_xml_str += f'    <b:Tag>{source["tag"]}</b:Tag>\n'
        word_xml_str += f'    <b:Author>\n{source["authors_xml"]}    </b:Author>\n'
        source['url'] = record.find('./urls/related-urls/url').text
        word_xml_str += f'    <b:URL>{source["url"]}</b:URL>\n'
        word_xml_str += '  </b:Source>\n'
    word_xml_str += '</b:Sources>'
    return word_xml_str

def convert_authors_and_year(source):
    authors = source['authors']
    year = source['year']
    last_names = [author.split()[-1] for author in authors]
    tag = f'{", ".join(last_names)} ({year})'
    source['tag'] = tag
    source['authors_xml'] = ''
    source['authors_xml'] += f'      <b:Author>\n        <b:NameList>\n'
    for author in authors:
        source['authors_xml'] += f'          <b:Person>\n'
        source['authors_xml'] += f'            <b:Last>{author.split(" ")[-1]}</b:Last>\n'
        source['authors_xml'] += f'            <b:First>{author.split(" ")[0]}</b:First>\n'
        source['authors_xml'] += '          </b:Person>\n'
    source['authors_xml'] += '        </b:NameList>\n      </b:Author>\n'

def save_word_file(endnote_xml_str,word_filepath: str='word_xml_file.xml'):
    word_xml_str = convert_endnote_to_word(endnote_xml_str)
    with open(word_filepath, 'w') as f:
      f.write(word_xml_str)

def convert_file(endnote_filepath: str='endnote_xml_file.xml', word_filepath: str='word_xml_file.xml'):
  with open(endnote_filepath, 'r') as f:
    endnote_xml_str = f.read()
  save_word_file(endnote_xml_str, word_filepath)
</code>```

I was expecting that it would work the same way no matter the size of the file. I also tried to change the parsing to be in the following way to deal with the XML file directly using only one record at a time rather than using the whole thing at once:

```<code>**    root = ET.iterparse(endnote_xml_str)**
**    for event, record in root:**
**      if event == 'end' and record.tag == 'record':**
        source = {}
        ...
        word_xml_str += '  </b:Source>\n'
**      record.clear()**
    word_xml_str += '</b:Sources>'

</code>```

However, the changes above forced further changes that may be above my skill, as no matter how much I change there are always still errors. I am aware that I will have to change "endnote_xml_str" with the filename, but I would prefer to keep things simple and continue working on the original code handling the whole XML if possible.

Body:
I am using python on replit to convert XML files from endnote into a different XML format that can be opened in Microsoft Word's reference manager. When I tested on files with up to 6 records, it worked perfectly. When I tried on larger files with 30-50 records, it returned the following error:

  File "main.py", line 12, in convert_endnote_to_word
    root = ET.fromstring(endnote_xml_str)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/xml/etree/ElementTree.py", line 1320, in XML
    parser.feed(text)
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 2248

My code is below:

import xml.etree.ElementTree as ET
def convert_endnote_to_word(endnote_xml_str):
    word_xml_str = '<?xml version="1.0" encoding="utf-8"?>\n'
    word_xml_str += '\n'
    root = ET.fromstring(endnote_xml_str)
    for record in root.findall('./records/record'):
        source = {}
        word_xml_str += '  \n'
        year = record.find('./pub-dates/date').text
        source['year'] = year
        word_xml_str += f'    {source["year"]}\n'
        source['ref_type'] = record.find('./ref-type').get('name').replace(" ", "")
        word_xml_str += f'    {source["ref_type"]}\n'
        title = record.find('./titles/title').text
        source['title'] = title
        word_xml_str += f'    {source["title"]}\n'        authors = []
        for author in record.findall('./contributors/authors/author'):
            authors.append(author.text)
        source['authors'] = authors
        convert_authors_and_year(source)
        word_xml_str += f'    {source["tag"]}\n'
        word_xml_str += f'    \n{source["authors_xml"]}    \n'
        source['url'] = record.find('./urls/related-urls/url').text
        word_xml_str += f'    {source["url"]}\n'
        word_xml_str += '  \n'
    word_xml_str += ''
    return word_xml_str

def convert_authors_and_year(source):
    authors = source['authors']
    year = source['year']
    last_names = [author.split()[-1] for author in authors]
    tag = f'{", ".join(last_names)} ({year})'
    source['tag'] = tag
    source['authors_xml'] = ''
    source['authors_xml'] += f'      \n        \n'
    for author in authors:
        source['authors_xml'] += f'          \n'
        source['authors_xml'] += f'            {author.split(" ")[-1]}\n'
        source['authors_xml'] += f'            {author.split(" ")[0]}\n'
        source['authors_xml'] += '          \n'
    source['authors_xml'] += '        \n      \n'

def save_word_file(endnote_xml_str,word_filepath: str='word_xml_file.xml'):
    word_xml_str = convert_endnote_to_word(endnote_xml_str)
    with open(word_filepath, 'w') as f:
      f.write(word_xml_str)

def convert_file(endnote_filepath: str='endnote_xml_file.xml', word_filepath: str='word_xml_file.xml'):
  with open(endnote_filepath, 'r') as f:
    endnote_xml_str = f.read()
  save_word_file(endnote_xml_str, word_filepath)

I was expecting that it would work the same way no matter the size of the file. I also tried to change the parsing to be in the following way to deal with the XML file directly using only one record at a time rather than using the whole thing at once:

**    root = ET.iterparse(endnote_xml_str)**
**    for event, record in root:**
**      if event == 'end' and record.tag == 'record':**
        source = {}
        ...
        word_xml_str += '  \n'
**      record.clear()**
    word_xml_str += ''

However, the changes above forced further changes that may be above my skill, as no matter how much I change there are always still errors. I am aware that I will have to change "endnote_xml_str" with the filename, but I would prefer to keep things simple and continue working on the original code handling the whole XML if possible.


问:
ChartJSPlugins Issue
```<code>`<script>
Chart.pluginService.register({
    beforeDraw: function (chart) {
        var width = chart.chart.width,
            height = chart.chart.height,
            ctx = chart.chart.ctx;
        ctx.restore();
        var fontSize = (height / 114).toFixed(2);
        ctx.font = fontSize + "em sans-serif";
        ctx.textBaseline = "middle";
        var text = chart.config.options.elements.center.text,
            textX = Math.round((width - ctx.measureText(text).width) / 2),
            textY = height / 2;
        ctx.fillText(text, textX, textY);
        ctx.save();
    }
});

// chart1
var data = {
    labels: ["Red", "Blue"],
    datasets: [{
        data: [50],
        backgroundColor: ["#BEFF60", "#36A2EB"],
        hoverBackgroundColor: ["#BEFF60", "#36A2EB"]
    }]
};

var promisedDeliveryChart = new Chart(document.getElementById('myChart1'), {
    type: 'doughnut',
    data: data,

    options: {
        title: {
            display: true,
            text: 'OEE Chart'
        },

        elements: {
            center: {
                text: parseInt(<?php echo json_encode($OEE); ?>) + '%', //set as you wish

        }
    },
    cutout Percentage: 85,
    legend: {
        display: false
    }
}
});
</script>
`

</code>```

I have few questions here.

I have already created Plugins Service and doughnut chart code where I standardize everything including having a text in between the doughnut chart - how can I small changes  the Plugin Service so that where I can add picture send towards backwards and bring the text infront?? - Is it possible this same Plugin Service used after modification answers given by anyone where for other charts but dont want to add the picture and text as other charts will be either bar graph or line chart etc... can anyone guide me with these kind of things. I'm not sure how to do it.. any advice??

If lets say I want to do chartsJS for stepped line chart how is that?? I tried using the same Plugin Service but failed. if if each type of chart need to use different plugins I can do it... but the issue I will create their separate files and call them in PHP index folder (as the main file running the website but when I add the JavaScript link and add call the name from the JS file into the PHP index file failed. Hopefully someone can guide me or advice me on this

when i use the same PluginService(which is used for doughnut chart)  i cannot show the results for barchart , line chart etc using the same PluginService when i pass <php json() file  ?>  from the database file i created to pass the data into data[] in chartJS

-dscsccsss\\\\\\

Title: ChartJSPlugins Issue

Body:
`
`

I have few questions here.

I have already created Plugins Service and doughnut chart code where I standardize everything including having a text in between the doughnut chart - how can I small changes  the Plugin Service so that where I can add picture send towards backwards and bring the text infront?? - Is it possible this same Plugin Service used after modification answers given by anyone where for other charts but dont want to add the picture and text as other charts will be either bar graph or line chart etc... can anyone guide me with these kind of things. I'm not sure how to do it.. any advice??

If lets say I want to do chartsJS for stepped line chart how is that?? I tried using the same Plugin Service but failed. if if each type of chart need to use different plugins I can do it... but the issue I will create their separate files and call them in PHP index folder (as the main file running the website but when I add the JavaScript link and add call the name from the JS file into the PHP index file failed. Hopefully someone can guide me or advice me on this

when i use the same PluginService(which is used for doughnut chart)  i cannot show the results for barchart , line chart etc using the same PluginService when i pass <php json() file  ?>  from the database file i created to pass the data into data[] in chartJS

-dscsccsss\\\\\\


问:
Print some text before a function text in Python

Input code:

```<code>d="Good Dawn"
m="Good Morning"
a="Good Afternoon"
e="Good evenning"
n="Good Night"
nn="Good Noon"

print("What is time in only Hour?")
t=int(input("Hour: "))

def myFunc1():
    if t>4:
        print(d)
    elif t>6:
        print(m)
    elif t>11:
        print(nn)
    elif t>15:
        print(a)
    elif t>16:
        print(e)
    else:
        print(n)
print("1st Algorithm Result is: ")
myFunc1()

def myFunc2():
    if t<7:
        print(d)
    elif t<12:
        print(m)
    elif t<16:
        print(nn)
    elif t<18:
        print(a)
    elif t<20:
        print(e)
    else:
        print(n)

print("2nd Algorithm Result is: ")
myFunc2()
</code>```

The output result is:

What is time in only Hour?
Hour: 11
1st Algorithm Result is:
Good Dawn
2nd Algorithm Result is:
Good Morning

But I want The result will be like this:

What is time in only Hour?

Hour:  11

1st Algorithm Result is: Good Dawn

2nd Algorithm Result is: Good Morning

Body:
Input code:

d="Good Dawn"
m="Good Morning"
a="Good Afternoon"
e="Good evenning"
n="Good Night"
nn="Good Noon"

print("What is time in only Hour?")
t=int(input("Hour: "))

def myFunc1():
    if t>4:
        print(d)
    elif t>6:
        print(m)
    elif t>11:
        print(nn)
    elif t>15:
        print(a)
    elif t>16:
        print(e)
    else:
        print(n)
print("1st Algorithm Result is: ")
myFunc1()

def myFunc2():
    if t<7:
        print(d)
    elif t<12:
        print(m)
    elif t<16:
        print(nn)
    elif t<18:
        print(a)
    elif t<20:
        print(e)
    else:
        print(n)

print("2nd Algorithm Result is: ")
myFunc2()

The output result is:

What is time in only Hour?
Hour: 11
1st Algorithm Result is:
Good Dawn
2nd Algorithm Result is:
Good Morning

But I want The result will be like this:

What is time in only Hour?

Hour:  11

1st Algorithm Result is: Good Dawn

2nd Algorithm Result is: Good Morning


问:
What happens when you do array[-1]?
I wrote a function that copies an array in reverse order

Here:

void reverse(char to[], char from[], int size)
{
    int i;

    i = 0;
    // Copy all the characters before the null character into 'to'. i ends at size-1 for the null character
    while ((to[i] = from[(size-1)-i]))
        ++i;
}

```
<p>Looking at it again after sometime I noticed that at some point <code>from[-1]</code> in the condition is evaluated. But for some reason my code still works?</p>
<p>I know that there should be junk values here but I want to know why my code "just works" no matter the input. When looking at it through a debugger I still only get <code>'\0'</code> when <code>from[-1]</code> is evaluated. In the end my reverse string is always null terminated lol</p>
<p>I know I can just add <code>to[i] = '\0'</code> to the end to be certain that it's always null terminated but having it this way hasn't caused any issues</p>
<p>This is the code I use it in</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>

#define MAXLINE 1000

int megetline(char s[],int lim);
void reverse(char to[], char from[], int size);

/* This program reverses it's input a line at a time */
int main()
{
    int len;
    char line[MAXLINE], r_str[MAXLINE];

    while ((len = megetline(line, MAXLINE)) > 0) {
        reverse(r_str, line, len);
        printf("%s", r_str);
    }

    return 0;
}
/* Best time: 0.000070 secs */

int megetline(char s[],int lim)
{
    int c, i;

    for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
        s[i] = c;
    if (c == '\n') {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';

    return i;
}

void reverse(char to[], char from[], int size)
{
    int i;

    i = 0;
    // Copy all the characters before the null character into 'to'. i ends at size-1 for the null character
    while ((to[i] = from[(size-1)-i]))
        ++i;
}

</code>```

Your thoughts are greatly appreciated.

Title: What happens when you do array[-1]?

Body:
I wrote a function that copies an array in reverse order

Here:

void reverse(char to[], char from[], int size)
{
    int i;

    i = 0;
    // Copy all the characters before the null character into 'to'. i ends at size-1 for the null character
    while ((to[i] = from[(size-1)-i]))
        ++i;
}

Looking at it again after sometime I noticed that at some point from[-1] in the condition is evaluated. But for some reason my code still works?

I know that there should be junk values here but I want to know why my code "just works" no matter the input. When looking at it through a debugger I still only get '\0' when from[-1] is evaluated. In the end my reverse string is always null terminated lol

I know I can just add to[i] = '\0' to the end to be certain that it's always null terminated but having it this way hasn't caused any issues

This is the code I use it in

#include <stdio.h>

#define MAXLINE 1000

int megetline(char s[],int lim);
void reverse(char to[], char from[], int size);

/* This program reverses it's input a line at a time */
int main()
{
    int len;
    char line[MAXLINE], r_str[MAXLINE];

    while ((len = megetline(line, MAXLINE)) > 0) {
        reverse(r_str, line, len);
        printf("%s", r_str);
    }

    return 0;
}
/* Best time: 0.000070 secs */

int megetline(char s[],int lim)
{
    int c, i;

    for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
        s[i] = c;
    if (c == '\n') {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';

    return i;
}

void reverse(char to[], char from[], int size)
{
    int i;

    i = 0;
    // Copy all the characters before the null character into 'to'. i ends at size-1 for the null character
    while ((to[i] = from[(size-1)-i]))
        ++i;
}

Your thoughts are greatly appreciated.


问:
Laravel 9 - Failed to authenticate on SMTP server with username
The issue: Failed to authenticate on SMTP server with username "b926ad2c64b4a7" using the following authenticators: "CRAM-MD5", "LOGIN", "PLAIN". Authenticator "CRAM-MD5" returned "Expected response code "235" but got code "451", with message "451 4.3.2 Internal server error".". Authenticator "LOGIN" returned "Expected response code "334" but got empty code.". Authenticator "PLAIN" returned "Expected response code "235" but got empty code.".

My Laravel Project was all working perfectly fine a few days ago. (No Code Changes have been made). When I stumbled into the error I updated my SMPT setting within the .env file like so:

.env

```<code>    MAIL_MAILER=smtp
    MAIL_HOST=smtp.mailtrap.io
    MAIL_PORT=2525
    MAIL_USERNAME=b926ad2c64b4a7
    MAIL_PASSWORD=ba6651bbf8xxxx
    MAIL_ENCRYPTION=tls
</code>```

with the new setting's in place within the .env file, I'm still receiving the same error. I use npm run dev (Laravel Vite) and Docker Container.  Shut down the laravel vite and for docker I have used docker compose down and then docker compose up for complete refresh. same error still happens.

Ran following

```<code>    php artisan config:cache
    php artisan config:clear
    php artisan cache:clear
</code>```

Body:
The issue: Failed to authenticate on SMTP server with username "b926ad2c64b4a7" using the following authenticators: "CRAM-MD5", "LOGIN", "PLAIN". Authenticator "CRAM-MD5" returned "Expected response code "235" but got code "451", with message "451 4.3.2 Internal server error".". Authenticator "LOGIN" returned "Expected response code "334" but got empty code.". Authenticator "PLAIN" returned "Expected response code "235" but got empty code.".

My Laravel Project was all working perfectly fine a few days ago. (No Code Changes have been made). When I stumbled into the error I updated my SMPT setting within the .env file like so:

.env

    MAIL_MAILER=smtp
    MAIL_HOST=smtp.mailtrap.io
    MAIL_PORT=2525
    MAIL_USERNAME=b926ad2c64b4a7
    MAIL_PASSWORD=ba6651bbf8xxxx
    MAIL_ENCRYPTION=tls

with the new setting's in place within the .env file, I'm still receiving the same error. I use npm run dev (Laravel Vite) and Docker Container.  Shut down the laravel vite and for docker I have used docker compose down and then docker compose up for complete refresh. same error still happens.

Ran following

    php artisan config:cache
    php artisan config:clear
    php artisan cache:clear


问:
How to write data with geometries into same .csv file using R?
I have a geometry data that I want to write into an existing csv file which has the same format of data. I want to append the new geometry data into the old csv file. When I am using st_write to write the data it throws the below error. How do I append the data into a existing csv file using st_write?

code:-

```<code>iso <- st_as_sf(iso, crs = 4326)
st_write(iso, 'path/iso_test.csv',layer_options = "GEOMETRY=AS_WKT")
</code>```

error:-

```<code>  Error in CPL_write_ogr(obj, dsn, layer, driver, as.character(dataset_options), : Feature creation failed.
</code>```

Body:
I have a geometry data that I want to write into an existing csv file which has the same format of data. I want to append the new geometry data into the old csv file. When I am using st_write to write the data it throws the below error. How do I append the data into a existing csv file using st_write?

code:-

iso <- st_as_sf(iso, crs = 4326)
st_write(iso, 'path/iso_test.csv',layer_options = "GEOMETRY=AS_WKT")

error:-

  Error in CPL_write_ogr(obj, dsn, layer, driver, as.character(dataset_options), : Feature creation failed.


问:
plot a kagi chart using python not JavaScript or other code
how to plot a kagi chart using python?
i have used chat-gpt to get the following code and add some code to it, it is not finished yet,
could anyone to help to add more features(varying thickness,price reversal) to it?

```<code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def KagiChart(df):
    # Create a new dataframe to store the Kagi chart
    kagi_df = pd.DataFrame(columns=['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Kagi'])

    # Initialize the Kagi line
    kagi = df.iloc[0]['close']
    kagi_df.loc[0] = [df.iloc[0]['date'], df.iloc[0]['open'], df.iloc[0]['high'], df.iloc[0]['low'], df.iloc[0]['close'], df.iloc[0]['volume'], 'Line']

    # Loop through the rest of the data
    for i in range(1, df.shape[0]):
        # If the close is greater than the previous close, set the Kagi line to 'Rise'
        if df.iloc[i]['close'] > kagi:
            kagi_df.loc[i] = [df.iloc[i]['date'], df.iloc[i]['open'], df.iloc[i]['high'], df.iloc[i]['low'], df.iloc[i]['close'], df.iloc[i]['volume'], 'up']
            kagi = df.iloc[i]['close']
        # If the close is less than the previous close, set the Kagi line to 'Fall'
        elif df.iloc[i]['close'] < kagi:
            kagi_df.loc[i] = [df.iloc[i]['date'], df.iloc[i]['open'], df.iloc[i]['high'], df.iloc[i]['low'], df.iloc[i]['close'], df.iloc[i]['volume'], 'down']
            kagi = df.iloc[i]['close']
        # If the close is equal to the previous close, set the Kagi line to 'Line'
        else:
            kagi_df.loc[i] = [df.iloc[i]['date'], df.iloc[i]['open'], df.iloc[i]['high'], df.iloc[i]['low'], df.iloc[i]['close'], df.iloc[i]['volume'], 'Line']

    return kagi_df
# Load the data
df = pd.read_csv('data.csv')
print(KagiChart(df))
date = KagiChart(df)['Date']
close = KagiChart(df)['Close']
direction = KagiChart(df)['Kagi']
fig, ax = plt.subplots()

for i in range(1,len(date)):
    if direction[i] == 'up':
        ax.plot([date[i], date[i]], [close[i-1], close[i]], color='r')
        plt.hlines(close[i-1], xmin=date[i-1], xmax=date[i],color='r')
    else:
        ax.plot([date[i], date[i]], [close[i-1], close[i]], color='g')
        plt.hlines(close[i-1], xmin=date[i-1], xmax=date[i],color='g')
# Set the title and labels
ax.set_title('Kagi Chart')
ax.set_xlabel('Date')
ax.set_ylabel('Close')
plt.show()]
</code>```

]

Body:
how to plot a kagi chart using python?
i have used chat-gpt to get the following code and add some code to it, it is not finished yet,
could anyone to help to add more features(varying thickness,price reversal) to it?

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def KagiChart(df):
    # Create a new dataframe to store the Kagi chart
    kagi_df = pd.DataFrame(columns=['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Kagi'])

    # Initialize the Kagi line
    kagi = df.iloc[0]['close']
    kagi_df.loc[0] = [df.iloc[0]['date'], df.iloc[0]['open'], df.iloc[0]['high'], df.iloc[0]['low'], df.iloc[0]['close'], df.iloc[0]['volume'], 'Line']

    # Loop through the rest of the data
    for i in range(1, df.shape[0]):
        # If the close is greater than the previous close, set the Kagi line to 'Rise'
        if df.iloc[i]['close'] > kagi:
            kagi_df.loc[i] = [df.iloc[i]['date'], df.iloc[i]['open'], df.iloc[i]['high'], df.iloc[i]['low'], df.iloc[i]['close'], df.iloc[i]['volume'], 'up']
            kagi = df.iloc[i]['close']
        # If the close is less than the previous close, set the Kagi line to 'Fall'
        elif df.iloc[i]['close'] < kagi:
            kagi_df.loc[i] = [df.iloc[i]['date'], df.iloc[i]['open'], df.iloc[i]['high'], df.iloc[i]['low'], df.iloc[i]['close'], df.iloc[i]['volume'], 'down']
            kagi = df.iloc[i]['close']
        # If the close is equal to the previous close, set the Kagi line to 'Line'
        else:
            kagi_df.loc[i] = [df.iloc[i]['date'], df.iloc[i]['open'], df.iloc[i]['high'], df.iloc[i]['low'], df.iloc[i]['close'], df.iloc[i]['volume'], 'Line']

    return kagi_df
# Load the data
df = pd.read_csv('data.csv')
print(KagiChart(df))
date = KagiChart(df)['Date']
close = KagiChart(df)['Close']
direction = KagiChart(df)['Kagi']
fig, ax = plt.subplots()

for i in range(1,len(date)):
    if direction[i] == 'up':
        ax.plot([date[i], date[i]], [close[i-1], close[i]], color='r')
        plt.hlines(close[i-1], xmin=date[i-1], xmax=date[i],color='r')
    else:
        ax.plot([date[i], date[i]], [close[i-1], close[i]], color='g')
        plt.hlines(close[i-1], xmin=date[i-1], xmax=date[i],color='g')
# Set the title and labels
ax.set_title('Kagi Chart')
ax.set_xlabel('Date')
ax.set_ylabel('Close')
plt.show()]

]


问:
loss2 confused me, the face correlation model.Model failed to converge
I used two images to generate one image via a generator, then used the retinaface to get the face from the generated image. Then a discriminator is used to judge the authenticity of the face, and the loss of the real tag is obtained. I wanted to make the loss as large as possible(the loss function as small as possible), but found that the value of the loss varied.I've tried using two faces directly to generate a face, and the deception works very well. But generating an image and extracting a face failed.This is my code.

```<code>criterion = nn.CrossEntropyLoss()
mseloss = nn.MSELoss(reduction='mean')
for step, (img, label, img_real) in enumerate(tqdm(train_loader)):
    face =[]
    img = img.to(device, non_blocking=True).float()
    target = label.to(device, non_blocking=True).long()
    img_real = img_real.to(device, non_blocking=True).float()
    output_g = generator(img, img_real)
    loss1 = mseloss(output_g, img)
    for i in range(batch_size):
        # input_tensor = output_g[i].clone().detach()
        input_tensor = output_g[i]
        input_tensor = input_tensor.squeeze().to(torch.device('cpu'))
        input_tensor = input_tensor.mul_(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).type(torch.uint8).numpy()
        face_list = extract_face(input_tensor,face_detector,image_size=(380, 380))
        face.append(face_list[0])
    if (len(face) != 8):
        continue
    faceList = torch.tensor(np.array(face)).to(device).float() / 255
    output_d = detector(faceList)
    criloss = criterion(output_d, target)
    loss2 = torch.exp(-criloss)
    loss = loss1 + loss2
</code>```

I think it's a code problem. But as a beginner of faces, I couldn't solve it.

Body:
I used two images to generate one image via a generator, then used the retinaface to get the face from the generated image. Then a discriminator is used to judge the authenticity of the face, and the loss of the real tag is obtained. I wanted to make the loss as large as possible(the loss function as small as possible), but found that the value of the loss varied.I've tried using two faces directly to generate a face, and the deception works very well. But generating an image and extracting a face failed.This is my code.

criterion = nn.CrossEntropyLoss()
mseloss = nn.MSELoss(reduction='mean')
for step, (img, label, img_real) in enumerate(tqdm(train_loader)):
    face =[]
    img = img.to(device, non_blocking=True).float()
    target = label.to(device, non_blocking=True).long()
    img_real = img_real.to(device, non_blocking=True).float()
    output_g = generator(img, img_real)
    loss1 = mseloss(output_g, img)
    for i in range(batch_size):
        # input_tensor = output_g[i].clone().detach()
        input_tensor = output_g[i]
        input_tensor = input_tensor.squeeze().to(torch.device('cpu'))
        input_tensor = input_tensor.mul_(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).type(torch.uint8).numpy()
        face_list = extract_face(input_tensor,face_detector,image_size=(380, 380))
        face.append(face_list[0])
    if (len(face) != 8):
        continue
    faceList = torch.tensor(np.array(face)).to(device).float() / 255
    output_d = detector(faceList)
    criloss = criterion(output_d, target)
    loss2 = torch.exp(-criloss)
    loss = loss1 + loss2

I think it's a code problem. But as a beginner of faces, I couldn't solve it.


问:
Apache .htaccess URL rewrite [profile?u=]==>[@] (Just like YouTube)
Trying to figure out what to add to my .htaccess file to enable

mywebsite.com/@username

Right now it works as follows... mywebsite.com/profile?u=username

So I want to show "@" in the URL instead of "profile?u="... Exactly what YouTube just enabled. It's much cleaner and gives the userbase easy links to share their profile pages with friends.

Here's my current htaccess file:

```<code>#Header set Cache-Control "max-age=0, private, no-cache, no-store, must-revalidate"
DirectoryIndex index.php
# Turn mod_rewrite on
RewriteEngine On
#RewriteBase /cloud/
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]
# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
# Caching the Cloud image
ExpiresActive On ExpiresByType image/gif "access plus 1 year"
</code>```

Are there extra backend steps in terms of configuring Apache for encoded URLs or anything?  I'd appreciate the full answer to this question. Thanks!!

Body:
Trying to figure out what to add to my .htaccess file to enable

mywebsite.com/@username

Right now it works as follows... mywebsite.com/profile?u=username

So I want to show "@" in the URL instead of "profile?u="... Exactly what YouTube just enabled. It's much cleaner and gives the userbase easy links to share their profile pages with friends.

Here's my current htaccess file:

#Header set Cache-Control "max-age=0, private, no-cache, no-store, must-revalidate"
DirectoryIndex index.php
# Turn mod_rewrite on
RewriteEngine On
#RewriteBase /cloud/
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]
# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
# Caching the Cloud image
ExpiresActive On ExpiresByType image/gif "access plus 1 year"

Are there extra backend steps in terms of configuring Apache for encoded URLs or anything?  I'd appreciate the full answer to this question. Thanks!!


问:
How to know a android device is a cloud phone?
How to know a device is a cloud phone or real device?</p>


问:
Android publishing flavour based artifact on Artifactory
I am trying publish flavour based artifact on my Artifactory server. Gradle code looks like this

```<code>def GroupId = 'com.example.directory'
def ArtifactId = 'demo
def Version = '0.0.1-IB1''

productFlavors {
    extended {
        ArtifactId = "extended"
    }
    mini {
        ArtifactId = "mini"
    }
}

publishing {
    publications {
        aar(MavenPublication) {
            android.libraryVariants.all { variant ->

                groupId GroupId
                version Version
                artifactId ArtifactId

                def filename = "${archivesBaseName}-${variant.baseName}.aar"
                artifact("$buildDir/outputs/aar/${filename}")
            }
                pom.withXml {
                    def dependenciesNode = asNode().appendNode('dependencies')
                    def deps = configurations.implementation.allDependencies + configurations.api.allDependencies
                    deps.each {
                        if (it.group != null && (it.name != null || "unspecified" == it.name) && it.version != null && "unspecified" != it.version) {
                            def dependencyNode = dependenciesNode.appendNode('dependency')
                            dependencyNode.appendNode('groupId', it.group)
                            dependencyNode.appendNode('artifactId', it.name)
                            dependencyNode.appendNode('version', it.version)
                        }
                    }
                }

        }
    }
}

artifactory {
    contextUrl = 'http://artifactoryUrl/artifactory'
    publish {
        repository {
            repoKey = GroupId
            username = "${userName}"
            password = "${pass}"

        }
        defaults {
            publications('aar')
            publishArtifacts = true
            properties = ['qa.level': 'basic', 'dev.team': 'core']
            publishPom = true
        }
    }
}
</code>```

But when I run gradle command it generates the specific flavour + build type artifact. But while publishing it tries to publish all varient of the library and throws an error for other aar file names.

```<code>./gradlew clean && ./gradlew :demo:assembleextendedrelease && ./gradlew :demo:artifactoryPublish
</code>```

Body:
I am trying publish flavour based artifact on my Artifactory server. Gradle code looks like this

def GroupId = 'com.example.directory'
def ArtifactId = 'demo
def Version = '0.0.1-IB1''

productFlavors {
    extended {
        ArtifactId = "extended"
    }
    mini {
        ArtifactId = "mini"
    }
}

publishing {
    publications {
        aar(MavenPublication) {
            android.libraryVariants.all { variant ->

                groupId GroupId
                version Version
                artifactId ArtifactId

                def filename = "${archivesBaseName}-${variant.baseName}.aar"
                artifact("$buildDir/outputs/aar/${filename}")
            }
                pom.withXml {
                    def dependenciesNode = asNode().appendNode('dependencies')
                    def deps = configurations.implementation.allDependencies + configurations.api.allDependencies
                    deps.each {
                        if (it.group != null && (it.name != null || "unspecified" == it.name) && it.version != null && "unspecified" != it.version) {
                            def dependencyNode = dependenciesNode.appendNode('dependency')
                            dependencyNode.appendNode('groupId', it.group)
                            dependencyNode.appendNode('artifactId', it.name)
                            dependencyNode.appendNode('version', it.version)
                        }
                    }
                }

        }
    }
}

artifactory {
    contextUrl = 'http://artifactoryUrl/artifactory'
    publish {
        repository {
            repoKey = GroupId
            username = "${userName}"
            password = "${pass}"

        }
        defaults {
            publications('aar')
            publishArtifacts = true
            properties = ['qa.level': 'basic', 'dev.team': 'core']
            publishPom = true
        }
    }
}

But when I run gradle command it generates the specific flavour + build type artifact. But while publishing it tries to publish all varient of the library and throws an error for other aar file names.

./gradlew clean && ./gradlew :demo:assembleextendedrelease && ./gradlew :demo:artifactoryPublish


问:
Why color bar in matplotlib showing inconsistent value for 2 my figures
When I plot fig. A with only 1 map the highest value at colorbar is 140, but adding 2 other plots (different its time variable) it become 64. It means that value 140 is gone from the map1, why?? it is a bug?

A colorbar of multi-plot should exactly cover all range of values of all the plots.

Any suggestions?
thanks

A.

B.


问:
View pager 2 render issue with full screen mode android
View pager 2 render issue with full screen mode android . When I scroll in full screen mode the UI cuts and when its not in full screen with gesture mode off its work fine. I am using view pager 2 with media view and recyclyer view adapter issue image   and orignal one and orignal one

any one know the solution

tried adding full sreen mode to application but it now make it worst


问:
Qt - What exactly does the dependency_type custom compiler option do? What are the differences between TYPE_C, TYPE_UI, TYPE_QRC?
I am looking into how to manage custom compilers and generated files in qmake, and many of the github projects i'm looking at, have something like this in the .pro/.pri file:

```<code>CustomCompilerName.dependency_type = TYPE_C
</code>```

What does this do?

It's always TYPE_C btw, in all these projects.

The official qt docs have this to say about this:

Specifies the type of file the output is. If it is a known type (such as TYPE_C, TYPE_UI, TYPE_QRC), it is handled as one of those type of files

There's this qt wiki page that says this:

.dependency_type — use one of the default dependency-walking algorithms built into qmake. As of version 4.3.3, legal options are TYPE_C and TYPE_UI.

But none of these pages describe what exactly these options do and what the differences between them are.

I looked at the qmake source code thinking there will be some comments or something explaning these (there aren't). These options are part of an enum called enum SourceFileType, defined in a class called QMakeSourceFileInfo, in the makefiledeps.h file:

```<code>enum SourceFileType { TYPE_UNKNOWN, TYPE_C, TYPE_UI, TYPE_QRC };
</code>```

What are these options, what's the difference between them?

Body:
I am looking into how to manage custom compilers and generated files in qmake, and many of the github projects i'm looking at, have something like this in the .pro/.pri file:

CustomCompilerName.dependency_type = TYPE_C

What does this do?

It's always TYPE_C btw, in all these projects.

The official qt docs have this to say about this:

Specifies the type of file the output is. If it is a known type (such as TYPE_C, TYPE_UI, TYPE_QRC), it is handled as one of those type of files

There's this qt wiki page that says this:

.dependency_type — use one of the default dependency-walking algorithms built into qmake. As of version 4.3.3, legal options are TYPE_C and TYPE_UI.

But none of these pages describe what exactly these options do and what the differences between them are.

I looked at the qmake source code thinking there will be some comments or something explaning these (there aren't). These options are part of an enum called enum SourceFileType, defined in a class called QMakeSourceFileInfo, in the makefiledeps.h file:

enum SourceFileType { TYPE_UNKNOWN, TYPE_C, TYPE_UI, TYPE_QRC };

What are these options, what's the difference between them?


问:
Flutter RefreshIndicator, Async operation & setState
I want to implement Refresh Indicator on my list view. On pulling the list down I'm calling an API to sync the list with server.

Now when I sync the list while I'm on the same page it refreshes the list.
But If I pop the screen by going back and again navigating to the same screen it doesn't refresh the list.

The sync is taking some time and the code for syncing is written in ChangeNotifier.

```<code>class ListScreen extends StatefulWidget {
  const ListScreen({super.key});

  @override
  State<ListScreen> createState() => _ListScreenState();
}

class _ListScreenState extends State<ListScreen> {
  int itemCount = 1;
  SyncViewModel? _syncViewModel;

  @override
  Widget build(BuildContext context) {
    _syncViewModel = context.watch<SyncViewModel>();

    return Builder(builder: (context) {
      return RefreshIndicator(
        displacement: 250,
        backgroundColor: Colors.yellow,
        color: Colors.red,
        strokeWidth: 3,
        triggerMode: RefreshIndicatorTriggerMode.onEdge,
        onRefresh: () async {
          await _syncViewModel!.callSyncAPIs();
          setState(() {
            itemCount = itemCount + 1;
          });
        },
        child: Scaffold(
          backgroundColor: const Color(0xff246df8),
          appBar: AppBar(
            title: const Text('Refresh Indicator'),
            backgroundColor: const Color(0xff246df8),
          ),
          body: _buildCardDesign(),
        ),
      );
    });
  }

</code>```
```<code>import 'package:flutter/material.dart';

class SyncViewModel extends ChangeNotifier {
  bool _loading = false;
  bool get loading => _loading;

  Future<void> callSyncAPIs() async {
    _loading = true;
    notifyListeners();

    await Future.delayed(const Duration(seconds: 5));

    _loading = false;
    notifyListeners();
  }
}

</code>```

Earlier I was getting following exception, then I also checked for mounted before setState. But now in my use case the mounted is always false.

```<code>Exception has occurred.
FlutterError (setState() called after dispose(): _ListScreenState#5934b(lifecycle state: defunct, not mounted)
This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().)
</code>```

How can I refresh the list when the sync completes If user navigates to the list page?

How can I show refreshing indicator if user navigates to the list page when sync is in progress?

Body:
I want to implement Refresh Indicator on my list view. On pulling the list down I'm calling an API to sync the list with server.

Now when I sync the list while I'm on the same page it refreshes the list.
But If I pop the screen by going back and again navigating to the same screen it doesn't refresh the list.

The sync is taking some time and the code for syncing is written in ChangeNotifier.

class ListScreen extends StatefulWidget {
  const ListScreen({super.key});

  @override
  State<ListScreen> createState() => _ListScreenState();
}

class _ListScreenState extends State<ListScreen> {
  int itemCount = 1;
  SyncViewModel? _syncViewModel;

  @override
  Widget build(BuildContext context) {
    _syncViewModel = context.watch<SyncViewModel>();

    return Builder(builder: (context) {
      return RefreshIndicator(
        displacement: 250,
        backgroundColor: Colors.yellow,
        color: Colors.red,
        strokeWidth: 3,
        triggerMode: RefreshIndicatorTriggerMode.onEdge,
        onRefresh: () async {
          await _syncViewModel!.callSyncAPIs();
          setState(() {
            itemCount = itemCount + 1;
          });
        },
        child: Scaffold(
          backgroundColor: const Color(0xff246df8),
          appBar: AppBar(
            title: const Text('Refresh Indicator'),
            backgroundColor: const Color(0xff246df8),
          ),
          body: _buildCardDesign(),
        ),
      );
    });
  }

import 'package:flutter/material.dart';

class SyncViewModel extends ChangeNotifier {
  bool _loading = false;
  bool get loading => _loading;

  Future<void> callSyncAPIs() async {
    _loading = true;
    notifyListeners();

    await Future.delayed(const Duration(seconds: 5));

    _loading = false;
    notifyListeners();
  }
}

Earlier I was getting following exception, then I also checked for mounted before setState. But now in my use case the mounted is always false.

Exception has occurred.
FlutterError (setState() called after dispose(): _ListScreenState#5934b(lifecycle state: defunct, not mounted)
This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().)

How can I refresh the list when the sync completes If user navigates to the list page?

How can I show refreshing indicator if user navigates to the list page when sync is in progress?


问:
Using NowJS for Node.js with jQuery UI Draggable
I started with the code found at this post: http://www.bennadel.com/blog/2171-Realtime-Messaging-And-Synchronization-With-NowJS-And-Node-js.htm.

I tried refactoring the html so that the example would use jQuery UI Draggable.  The code is pasted below; server side is unchanged.  It works fine, but there is an issue with flickering when dragging.  I assume this is a jQuery question, although I was thinking there might be a problem with the filtering on the server side?

Also, I was wondering about how I might create an "initialPosition" function so that opening a new page would put the draggable div in the proper position.  I assume this is something that needs to be done on the server side, and ideally it would come from a database value that gets written after a drag ends.

Also, beyond that I was wondering what the code would look like if I had multiple draggable items on a page.

HTML

```<code><!DOCTYPE html>
<html>
<head>
    <title>NowJS Draggable using jQuery UI</title>
    <style type="text/css">
        html, body { height: 100%; width: 100%; overflow: hidden; }
        #draggable { width: 150px; height: 150px; border: 1px solid black; }
    </style>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"/></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"/></script>
    <script type="text/javascript" src="/nowjs/now.js"></script>
    <script>
        $(function() {
            $( "#draggable" ).draggable();
            $( "#draggable" ).bind( "drag", function( event ) {
                var newPosition = {
                    left: ( event.pageX ),
                    top: ( event.pageY ),
                };
                now.syncPosition( newPosition );
            });
            now.updatePosition = function( newPosition ){
                $( "#draggable" ).css( newPosition );
            };
        });
    </script>
</head>
<body>
    <div id="draggable"></div>
</body>
</html>
</code>```

NODE.JS (comments stripped out)

```<code>var sys = require( "sys" );
var http = require( "http" );
var url = require( "url" );
var path = require( "path" );
var fileSystem = require( "fs" );

var server = http.createServer(
    function( request, response ){
        fileSystem.readFile(
            __dirname+'/index.html',
            "binary",
            function( error, fileBinary ){
                if (error){
                    response.writeHead( 404 );
                    response.end();
                    return;
                }
                response.writeHead( 200 );
                response.write( fileBinary, "binary" );
                response.end();
            }
        );
    }
);

server.listen( 8080 );

(function(){
    var nowjs = require( "now" );
    var everyone = nowjs.initialize( server );
    var primaryKey = 0;
    everyone.connected(
        function(){
            this.now.uuid = ++primaryKey;
        }
    );
    everyone.now.syncPosition = function( position ){
        everyone.now.filterUpdateBroadcast( this.now.uuid, position );
    };
    everyone.now.filterUpdateBroadcast = function( masterUUID, position ){
        if (this.now.uuid == masterUUID){
            return;
        }
        everyone.now.updatePosition( position );
    };
})();

sys.puts( "Server is running on 8080" );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I started with the code found at this post: http://www.bennadel.com/blog/2171-Realtime-Messaging-And-Synchronization-With-NowJS-And-Node-js.htm.

I tried refactoring the html so that the example would use jQuery UI Draggable.  The code is pasted below; server side is unchanged.  It works fine, but there is an issue with flickering when dragging.  I assume this is a jQuery question, although I was thinking there might be a problem with the filtering on the server side?

Also, I was wondering about how I might create an "initialPosition" function so that opening a new page would put the draggable div in the proper position.  I assume this is something that needs to be done on the server side, and ideally it would come from a database value that gets written after a drag ends.

Also, beyond that I was wondering what the code would look like if I had multiple draggable items on a page.

HTML

<!DOCTYPE html>

    <title>NowJS Draggable using jQuery UI</title>

NODE.JS (comments stripped out)

var sys = require( "sys" );
var http = require( "http" );
var url = require( "url" );
var path = require( "path" );
var fileSystem = require( "fs" );

var server = http.createServer(
    function( request, response ){
        fileSystem.readFile(
            __dirname+'/index.html',
            "binary",
            function( error, fileBinary ){
                if (error){
                    response.writeHead( 404 );
                    response.end();
                    return;
                }
                response.writeHead( 200 );
                response.write( fileBinary, "binary" );
                response.end();
            }
        );
    }
);

server.listen( 8080 );

(function(){
    var nowjs = require( "now" );
    var everyone = nowjs.initialize( server );
    var primaryKey = 0;
    everyone.connected(
        function(){
            this.now.uuid = ++primaryKey;
        }
    );
    everyone.now.syncPosition = function( position ){
        everyone.now.filterUpdateBroadcast( this.now.uuid, position );
    };
    everyone.now.filterUpdateBroadcast = function( masterUUID, position ){
        if (this.now.uuid == masterUUID){
            return;
        }
        everyone.now.updatePosition( position );
    };
})();

sys.puts( "Server is running on 8080" );


问:
Powershell: Call function during Start-Process
I have a function called RemoveSoftware:

```<code>function RemoveSoftware {
        foreach ($utility in $toRemove) {
            Try {
                winget uninstall -e $utility
                $wingetResult.Add("$node`n")
                Start-Sleep -s 6
                Wait-Process winget -Timeout 90 -ErrorAction SilentlyContinue
            }
            Catch {
                Write-Host "Paket $utility konnte nicht deinstalliert werden. " -ForegroundColor red
            }
        }
    }
</code>```

This function is in a ps1 file. In the same file I want to start another powershell window which should start this function.

I tried this here:

```<code>Start-Process powershell.exe -Verb RunAs -ArgumentList "-command Start-Transcript C:\temp\winget-start.log -Append; & {$RemoveSoftware} | Out-Host" -WindowStyle Normal
</code>```

But this don't work.
Also I tried several other things like Invoke-Expression and so on. Neither of it worked:(
Has someone a tipp for solving this problem?

Body:
I have a function called RemoveSoftware:

function RemoveSoftware {
        foreach ($utility in $toRemove) {
            Try {
                winget uninstall -e $utility
                $wingetResult.Add("$node`n")
                Start-Sleep -s 6
                Wait-Process winget -Timeout 90 -ErrorAction SilentlyContinue
            }
            Catch {
                Write-Host "Paket $utility konnte nicht deinstalliert werden. " -ForegroundColor red
            }
        }
    }

This function is in a ps1 file. In the same file I want to start another powershell window which should start this function.

I tried this here:

Start-Process powershell.exe -Verb RunAs -ArgumentList "-command Start-Transcript C:\temp\winget-start.log -Append; & {$RemoveSoftware} | Out-Host" -WindowStyle Normal

But this don't work.
Also I tried several other things like Invoke-Expression and so on. Neither of it worked:(
Has someone a tipp for solving this problem?


问:
How to use customize assert marco
tmp2.c

```<code>/*
gcc -Wall -Werror -g assert.c tmp2.c && ./a.out
*/

#include "tmp2.h"
#include <assert.h>

int main(void)
{
    // assert(1 == 2);
    Assert(1 == 2);
    return 0;
}
</code>```

tmp2.h

```<code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <math.h>
#include<stdint.h>
#include<stdalign.h>
#include<stdbool.h>

/*
 * BoolIsValid
 *      True iff bool is valid.
 */
#define BoolIsValid(boolean) ((boolean) == false || (boolean) == true)

/*
 * PointerIsValid
 *      True iff pointer is valid.
 */
#define PointerIsValid(pointer) ((const void*)(pointer) != NULL)

extern void
ExceptionalCondition(const char *conditionName,
                     const char *fileName,
                     int lineNumber);
/*
 * USE_ASSERT_CHECKING, if defined, turns on all the assertions.
 * - plai  9/5/90
 *
 * It should _NOT_ be defined in releases or in benchmark copies
 */

/*
 * Assert() can be used in both frontend and backend code. In frontend code it
 * just calls the standard assert, if it's available. If use of assertions is
 * not configured, it does nothing.
 */
#define USE_ASSERT_CHECKING 0
#ifndef USE_ASSERT_CHECKING

#define Assert(condition) ((void)true)
#define AssertMarcod(condition) ((void)true)

#elif defined(FRONTEND)

#include<assert.h>
#define Assert(p) assert(p)
#define AssertMarco(p) ((void) assert(p))

#else
/*
 * Assert
 *      Generates a fatal exception if the given condition is false.
 */

#define Assert(condition) \
    do { \
        if (!(condition)) \
            ExceptionalCondition(#condition,__FILE__,__LINE__); \
    } while (0)

/*
 * AssertMacro is the same as Assert but it's suitable for use in
 * expression-like macros, for example:
 *
 *      #define foo(x) (AssertMacro(x != 0), bar(x))
 */
#define  AssertMacro(condition) \
    ((void) ((condition) || \
            (ExceptionalCondition(#condition,__FILE__,__LINE__),0)))
#endif

</code>```

assert.c

```<code>#include "tmp2.h"
#include <unistd.h>
#ifdef HAVE_EXECINFO_H
#include <execinfo.h>
#endif

/*
 * ExceptionalCondition - Handles the failure of an Assert()
 *
 * We intentionally do not go through elog() here, on the grounds of
 * wanting to minimize the amount of infrastructure that has to be
 * working to report an assertion failure.
 */
void
ExceptionalCondition(const char *conditionName,
                     const char *fileName,
                     int lineNumber)
{
    /* Report the failure on stderr (or local equivalent) */
    if (!PointerIsValid(conditionName)
        || !PointerIsValid(fileName))
        fprintf(stderr,"TRAP: ExceptionalCondition: bad arguments in PID %d\n",
                     (int) getpid());
    else
        fprintf(stderr,"TRAP: failed Assert(\"%s\"), File: \"%s\", Line: %d, PID: %d\n",
                     conditionName, fileName, lineNumber, (int) getpid());

    /* Usually this shouldn't be needed, but make sure the msg went out */
    fflush(stderr);

//  /* If we have support for it, dump a simple backtrace */
// #ifdef HAVE_BACKTRACE_SYMBOLS
//  {
//      void       *buf[100];
//      int         nframes;

//      nframes = backtrace(buf, lengthof(buf));
//      backtrace_symbols_fd(buf, nframes, fileno(stderr));
//  }
// #endif

    /*
     * If configured to do so, sleep indefinitely to allow user to attach a
     * debugger.  It would be nice to use pg_usleep() here, but that can sleep
     * at most 2G usec or ~33 minutes, which seems too short.
     */
#ifdef SLEEP_ON_ASSERT
    sleep(1000000);
#endif

    abort();
}
</code>```

In this context, I'm trying a way to use the AssertMacro; that is, find a way to invoke assert.c ExceptionalCondition function. Assume FRONTEND is not defined. USE_ASSERT_CHECKING can be 1 or 0.

update: to use ExceptionalCondition function I need to declare it on  tmp2.h via

```<code>extern void
ExceptionalCondition(const char *conditionName,
                     const char *fileName,
                     int lineNumber);
</code>```

I also need to define USE_ASSERT_CHECKING in tmp2.h or before tmp2.h.
If  I don't define USE_ASSERT_CHECKING seems all  the assert will be true always?

Title: How to use customize assert marco

Body:
tmp2.c

/*
gcc -Wall -Werror -g assert.c tmp2.c && ./a.out
*/

#include "tmp2.h"
#include <assert.h>

int main(void)
{
    // assert(1 == 2);
    Assert(1 == 2);
    return 0;
}

tmp2.h

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <math.h>
#include<stdint.h>
#include<stdalign.h>
#include<stdbool.h>

/*
 * BoolIsValid
 *      True iff bool is valid.
 */
#define BoolIsValid(boolean) ((boolean) == false || (boolean) == true)

/*
 * PointerIsValid
 *      True iff pointer is valid.
 */
#define PointerIsValid(pointer) ((const void*)(pointer) != NULL)

extern void
ExceptionalCondition(const char *conditionName,
                     const char *fileName,
                     int lineNumber);
/*
 * USE_ASSERT_CHECKING, if defined, turns on all the assertions.
 * - plai  9/5/90
 *
 * It should _NOT_ be defined in releases or in benchmark copies
 */

/*
 * Assert() can be used in both frontend and backend code. In frontend code it
 * just calls the standard assert, if it's available. If use of assertions is
 * not configured, it does nothing.
 */
#define USE_ASSERT_CHECKING 0
#ifndef USE_ASSERT_CHECKING

#define Assert(condition) ((void)true)
#define AssertMarcod(condition) ((void)true)

#elif defined(FRONTEND)

#include<assert.h>
#define Assert(p) assert(p)
#define AssertMarco(p) ((void) assert(p))

#else
/*
 * Assert
 *      Generates a fatal exception if the given condition is false.
 */

#define Assert(condition) \
    do { \
        if (!(condition)) \
            ExceptionalCondition(#condition,__FILE__,__LINE__); \
    } while (0)

/*
 * AssertMacro is the same as Assert but it's suitable for use in
 * expression-like macros, for example:
 *
 *      #define foo(x) (AssertMacro(x != 0), bar(x))
 */
#define  AssertMacro(condition) \
    ((void) ((condition) || \
            (ExceptionalCondition(#condition,__FILE__,__LINE__),0)))
#endif

assert.c

#include "tmp2.h"
#include <unistd.h>
#ifdef HAVE_EXECINFO_H
#include <execinfo.h>
#endif

/*
 * ExceptionalCondition - Handles the failure of an Assert()
 *
 * We intentionally do not go through elog() here, on the grounds of
 * wanting to minimize the amount of infrastructure that has to be
 * working to report an assertion failure.
 */
void
ExceptionalCondition(const char *conditionName,
                     const char *fileName,
                     int lineNumber)
{
    /* Report the failure on stderr (or local equivalent) */
    if (!PointerIsValid(conditionName)
        || !PointerIsValid(fileName))
        fprintf(stderr,"TRAP: ExceptionalCondition: bad arguments in PID %d\n",
                     (int) getpid());
    else
        fprintf(stderr,"TRAP: failed Assert(\"%s\"), File: \"%s\", Line: %d, PID: %d\n",
                     conditionName, fileName, lineNumber, (int) getpid());

    /* Usually this shouldn't be needed, but make sure the msg went out */
    fflush(stderr);

//  /* If we have support for it, dump a simple backtrace */
// #ifdef HAVE_BACKTRACE_SYMBOLS
//  {
//      void       *buf[100];
//      int         nframes;

//      nframes = backtrace(buf, lengthof(buf));
//      backtrace_symbols_fd(buf, nframes, fileno(stderr));
//  }
// #endif

    /*
     * If configured to do so, sleep indefinitely to allow user to attach a
     * debugger.  It would be nice to use pg_usleep() here, but that can sleep
     * at most 2G usec or ~33 minutes, which seems too short.
     */
#ifdef SLEEP_ON_ASSERT
    sleep(1000000);
#endif

    abort();
}

In this context, I'm trying a way to use the AssertMacro; that is, find a way to invoke assert.c ExceptionalCondition function. Assume FRONTEND is not defined. USE_ASSERT_CHECKING can be 1 or 0.

update: to use ExceptionalCondition function I need to declare it on  tmp2.h via

extern void
ExceptionalCondition(const char *conditionName,
                     const char *fileName,
                     int lineNumber);

I also need to define USE_ASSERT_CHECKING in tmp2.h or before tmp2.h.
If  I don't define USE_ASSERT_CHECKING seems all  the assert will be true always?


问:
I am making testcase for multi hyn tenancy but m not being able to rollback the data inserted from testcase
I have used a static website id for inserting into a specific database but the test case is not rolling back after the test case run.
class order extends TestCase</p>
```<code>{
    use ApiTestTrait;
    protected $connectionsToTransact = ["new_company"];
    // to which business
    protected $organization = 1;
    protected $restaurant = "1";
    protected $terminal = 1;
    protected $screen = "1";
    protected $userId = "1";

 public function testcase()
    {
//code here;
    }
}
</code>```

Body:
I have used a static website id for inserting into a specific database but the test case is not rolling back after the test case run.
class order extends TestCase

{
    use ApiTestTrait;
    protected $connectionsToTransact = ["new_company"];
    // to which business
    protected $organization = 1;
    protected $restaurant = "1";
    protected $terminal = 1;
    protected $screen = "1";
    protected $userId = "1";

 public function testcase()
    {
//code here;
    }
}


问:
Find Customer demand of specificproduct from Product list in excel
How to find customer demand only smart phone from several products

I tried Mid function to seperate smart phone but it was not available in first column.


问:
Pie Chart Missing Value Specific Column
Let say we have a dataframe like this:

```<code>import pandas as pd,numpy as np
df = pd.DataFrame({'id': ['1','2','3','4','5','6','7','8','9','10'],
                   'name': ['Arnold','Barney','Clark','Devi','Erik','Fiona','Genie','Harry','Isabella','Jane'],
                   'score': [89,92,70,np.NaN,78,np.NaN,80,94,np.NaN,100]})
</code>```

I tried to percentage the missing value for column score

```<code>df[['score']].isnull().mean().mul(100).round(2).astype(str)+'%'
</code>```

But I think it's better to visualize he percentage, so how to make a pie chart for missing value only in column score?

Title: Pie Chart Missing Value Specific Column

Body:
Let say we have a dataframe like this:

import pandas as pd,numpy as np
df = pd.DataFrame({'id': ['1','2','3','4','5','6','7','8','9','10'],
                   'name': ['Arnold','Barney','Clark','Devi','Erik','Fiona','Genie','Harry','Isabella','Jane'],
                   'score': [89,92,70,np.NaN,78,np.NaN,80,94,np.NaN,100]})

I tried to percentage the missing value for column score

df[['score']].isnull().mean().mul(100).round(2).astype(str)+'%'

But I think it's better to visualize he percentage, so how to make a pie chart for missing value only in column score?