问:
Are there good reasons to wrap a single property in a #region in c#?
I recently inherited some C# code where nearly every item in a file was wrapped in an individual #region/#endregion block -- every class, every function, every property, every enum, but not the fields.  Each of these was in turn wrapped in a "grouping" #region (e.g. "Properties", "Constructor", "Methods", etc.).  There are multiple overloads of a single function with different argument lists, but they're each wrapped in individual regions with the same name, rather than a single region for all three overloads.  The person who wrote this code is no longer with the company, and from the history in source control, it appears that these were present in the initial submission, and the practice continues through successive versions of the code as new properties and methods are added.

Any idea why this might be done?  Some thoughts:

An overzealous VS feature (or code-cleanup tool) automatically inserted the #region/#endregion blocks, and the author didn't remove them.

There's an IDE that folds regions but not functions, so this was necessary to get syntax folding.

This is a method of stubbing out the structure of your code prior to implementing it.

EDIT: I chose Jonathan's answer because it contributed a new reason why someone might have chosen to do this.  Thanks for the discussion!

答:
This is excessive regioning.  There is no good reason to wrap every function, every enum with a region statement.

I would consider this bad practice and taking the concept of regioning code too far.

Usually, I do regions like:

```<code>   1. Constructors
   2. Public Methods
   3. Private Methods
</code>```

Etc.

Some sort of logical grouping.  The regioning that you have described does not seem logical.

Body:
This is excessive regioning.  There is no good reason to wrap every function, every enum with a region statement.

I would consider this bad practice and taking the concept of regioning code too far.

Usually, I do regions like:

   1. Constructors
   2. Public Methods
   3. Private Methods

Etc.

Some sort of logical grouping.  The regioning that you have described does not seem logical.


来源: stackexchange

问:
Error when enabling react/jsx-sort-props [Rules of eslint-plugin-react]
I`m trying to sort props names alphabetically in my project using the plugin eslint-plugin-react.

I've read the jsx-sort-props rules option example and I'm here asking myself: What's props should be used in the <enable> field?

```<code>...
"react/jsx-sort-props": [<enabled>, {
  "callbacksLast": <boolean>,
  "shorthandFirst": <boolean>,
  "shorthandLast": <boolean>,
  "multiline": "ignore" | "first" | "last",
  "ignoreCase": <boolean>,
  "noSortAlphabetically": <boolean>,
  "reservedFirst": <boolean>|<array<string>>,
}]
...
</code>```

I've tried everything but always get an invalid configuration notification:

```<code>*Error: ESLint configuration in .eslintrc.JSON is invalid: Unexpected top-level property "react/jsx-sort-props".*
</code>```

I'm editing it at my .eslintrc.json file:

```<code>{
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "next/core-web-vitals"
  ],

  "react/jsx-sort-props": [<enabled>, {
    "callbacksLast": true,
    "shorthandFirst": false,
    "shorthandLast": true,
    "multiline": "last",
    "ignoreCase": true,
    "noSortAlphabetically": false,
    "reservedFirst": false
  }]
}
</code>```

答:
You need to put your rules into the rules property of the object, not into the top level of the object:

```<code>{
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "next/core-web-vitals"
  ],
  "rules": {
    "react/jsx-sort-props": [<enabled>, {
</code>```

This helps clearly delimit the difference between ESLint configuration settings and rules - otherwise, the overlap would be confusing, and if there were ever a rule whose name conflicted with a possible other top-level property, there'd be problems.

ContentLicense: CC BY-SA 4.0

Body:
I`m trying to sort props names alphabetically in my project using the plugin eslint-plugin-react.

I've read the jsx-sort-props rules option example and I'm here asking myself: What's props should be used in the <enable> field?

...
"react/jsx-sort-props": [<enabled>, {
  "callbacksLast": <boolean>,
  "shorthandFirst": <boolean>,
  "shorthandLast": <boolean>,
  "multiline": "ignore" | "first" | "last",
  "ignoreCase": <boolean>,
  "noSortAlphabetically": <boolean>,
  "reservedFirst": <boolean>|<array<string>>,
}]
...

I've tried everything but always get an invalid configuration notification:

*Error: ESLint configuration in .eslintrc.JSON is invalid: Unexpected top-level property "react/jsx-sort-props".*

I'm editing it at my .eslintrc.json file:

{
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "next/core-web-vitals"
  ],

  "react/jsx-sort-props": [<enabled>, {
    "callbacksLast": true,
    "shorthandFirst": false,
    "shorthandLast": true,
    "multiline": "last",
    "ignoreCase": true,
    "noSortAlphabetically": false,
    "reservedFirst": false
  }]
}

Body:
You need to put your rules into the rules property of the object, not into the top level of the object:

{
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "next/core-web-vitals"
  ],
  "rules": {
    "react/jsx-sort-props": [<enabled>, {

This helps clearly delimit the difference between ESLint configuration settings and rules - otherwise, the overlap would be confusing, and if there were ever a rule whose name conflicted with a possible other top-level property, there'd be problems.


问:
Using Generics in C# to compare conditionally
In my scenario, I have two types of objects. A plan and a tier. Each one shares certain values, while the tier has 3 additional values (Rate, Min, and Max).

I would like to make a generic method to conditionally evaluate whether or not the new object can be written to the database, based on the following conditions:

Creation:

A tier: ((o1.Rate!=o2.Rate) || ((o1.Start!=o2.Start) && (o1.End!=o2.End))) && (MinVal && MaxVal)

A tier or plan: (o1.Name!=o2.Name)

A tier or plan: Only one can have (Active == true), the rest must be false.

Is it possible to create a generic method for something like this? If so, are there any examples of something like this? Or does anyone have suggestions?

thanks!

MORE:
So I have a list of objects, and I need to compare a newly created one with each other object in the database before I actually write it to the database.

答:
In order for this to work, the generic method (or type) would need a constraint that allowed it to understand all of the individual properties you have listed (Rate, Date, MinVal, MaxValue, Start, and End).

If all of the types which you are worried about derive from the same base class or interface, you don't need generics - just build a method that takes two arguments of that base type.

If, however, they don't, again, generics will likely not be a good fit here - however, there is another option.  You could use dynamic to effectively use these properties using runtime binding.  Just realize that, if you pass an argument of a type without those properties, it will fail at runtime.

ContentLicense: CC BY-SA 3.0


问:
Alamofire - add both query parameter and body
I am trying to send a request that should contain both URL parameters and request body in JSON. Backend doesn't recognize the request and returns 400 status code.

This is how I tried to solve the problem

enum MyRequestsRouter: URLRequestConvertible {

    case RequestA(paramA: String, bodyInJsonString: String),
         RequestB(paramB: String)

    var baseURL: URL {
        URL(string: "http://127.0.0.1:8080")!
    }

    var method: HTTPMethod {
        switch self {
        case .RequestA: return .post
        case .RequestB: return .get
        }
    }

    var path: String {
        switch self {
        case .RequestA: return "/api/a"
        case .RequestB: return "/api/b"
        }
    }

    var parameters: Parameters? {
        switch self {
        case .RequestA(let paramA, let bodyInJsonString):
            return [
                "paramA": paramA
            ]

        case .RequestB(let paramB):
            return ["paramB": paramB]

        default:
            return nil
        }
    }

    func asURLRequest() throws -> URLRequest {
        let url = baseURL.appendingPathComponent(path)
        var request = URLRequest(url: url)
        request.method = method

        switch self {
        case let .RequestA(paramA, bodyInJsonString):
            // here I am specifying `paramA` value
            request = try URLEncoding.default.encode(request, with: parameters)

            // here body is already serialized to Json
            request.httpBody = Data(bodyInJsonString.utf8)
            request.setValue("application/json", "Content-Type")

        case let .RequestB(paramB):
            request = try URLEncoding.default.encode(request, with: parameters)

        }

        return request
    }

}
```
<p>And this is how I am making API call</p>
<pre class="lang-swift prettyprint-override"><code>let json: Data = try JSONEncoder().encode(notSerializedBodyObject)
let jsonString = String(data: json, encoding: .utf8)

AF.request(MyRequestsRouter.RequestA(paramA: "paramA", bodyInJsonString: jsonString!)).response { response in
            print("Request: \(response.request)")
            print("Response: \(response.response)")
            print("Error: \(response.error)")

            // etc
            }

}
</code>```

As you can see the request URL is supposed to be

http://127.0.0.1:8080/api/a?paramA=paramA plus request body in JSON. But response is 400 Bad request.

How to properly configure Alomofire?

答:
Alamofire's URLEncoding has an initializer that gets destination as parameter. Based on documentation:

Destination defining where the encoded query string will be applied.
.methodDependent by default.

By default .methodDependent case checks the HTTP method of the request and only on .get, .head and .delete requests it encodes the passed parameters in the URL.

Given that fact, you never see paramA in your request (not even in the body) because you override it in the following line:

```<code>// here body is already serialized to Json
request.httpBody = Data(bodyInJsonString.utf8)
</code>```

So, instead of using the default URLEncoding, you can simply call URLEncoding's initializer directly passing as destination the .queryString case like this:

```<code>// here I am specifying `paramA` value
request = try URLEncoding(destination: .queryString).encode(request, with: parameters)

// here body is already serialized to Json
request.httpBody = Data(bodyInJsonString.utf8)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
</code>```

That way you will have a request with paramA in the URL and your JSON as a body.

Body:
I am trying to send a request that should contain both URL parameters and request body in JSON. Backend doesn't recognize the request and returns 400 status code.

This is how I tried to solve the problem

enum MyRequestsRouter: URLRequestConvertible {

    case RequestA(paramA: String, bodyInJsonString: String),
         RequestB(paramB: String)

    var baseURL: URL {
        URL(string: "http://127.0.0.1:8080")!
    }

    var method: HTTPMethod {
        switch self {
        case .RequestA: return .post
        case .RequestB: return .get
        }
    }

    var path: String {
        switch self {
        case .RequestA: return "/api/a"
        case .RequestB: return "/api/b"
        }
    }

    var parameters: Parameters? {
        switch self {
        case .RequestA(let paramA, let bodyInJsonString):
            return [
                "paramA": paramA
            ]

        case .RequestB(let paramB):
            return ["paramB": paramB]

        default:
            return nil
        }
    }

    func asURLRequest() throws -> URLRequest {
        let url = baseURL.appendingPathComponent(path)
        var request = URLRequest(url: url)
        request.method = method

        switch self {
        case let .RequestA(paramA, bodyInJsonString):
            // here I am specifying `paramA` value
            request = try URLEncoding.default.encode(request, with: parameters)

            // here body is already serialized to Json
            request.httpBody = Data(bodyInJsonString.utf8)
            request.setValue("application/json", "Content-Type")

        case let .RequestB(paramB):
            request = try URLEncoding.default.encode(request, with: parameters)

        }

        return request
    }

}

And this is how I am making API call

let json: Data = try JSONEncoder().encode(notSerializedBodyObject)
let jsonString = String(data: json, encoding: .utf8)

AF.request(MyRequestsRouter.RequestA(paramA: "paramA", bodyInJsonString: jsonString!)).response { response in
            print("Request: \(response.request)")
            print("Response: \(response.response)")
            print("Error: \(response.error)")

            // etc
            }

}

As you can see the request URL is supposed to be

http://127.0.0.1:8080/api/a?paramA=paramA plus request body in JSON. But response is 400 Bad request.

How to properly configure Alomofire?

Body:
Alamofire's URLEncoding has an initializer that gets destination as parameter. Based on documentation:

Destination defining where the encoded query string will be applied.
.methodDependent by default.

By default .methodDependent case checks the HTTP method of the request and only on .get, .head and .delete requests it encodes the passed parameters in the URL.

Given that fact, you never see paramA in your request (not even in the body) because you override it in the following line:

// here body is already serialized to Json
request.httpBody = Data(bodyInJsonString.utf8)

So, instead of using the default URLEncoding, you can simply call URLEncoding's initializer directly passing as destination the .queryString case like this:

// here I am specifying `paramA` value
request = try URLEncoding(destination: .queryString).encode(request, with: parameters)

// here body is already serialized to Json
request.httpBody = Data(bodyInJsonString.utf8)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

That way you will have a request with paramA in the URL and your JSON as a body.


问:
What is the effect of instantiating the object from the subclass?
```<code>    public class BaseClass
    {
        public string Name { get; set; }
    }

    public class SubClass : BaseClass
    {
        public decimal Price { get; set; }
    }
</code>```
```<code>    BaseClass o1 = new SubClass();
    SubClass o2 = new SubClass();

    Console.WriteLine(o1.GetType().Name);
    Console.WriteLine(o2.GetType().Name);
</code>```

Outputs are

```<code>    SubClass
    SubClass
</code>```

What is the main difference between o1 and o2? In which cases is it necessary to define an object with BaseClass and instantiate it with SubClass?

答:
The big difference is evident when you try this

```<code>BaseClass o1 = new SubClass();
SubClass o2 = new SubClass();
var name1 = o1.Name; // works
var price1 = o1.Price; // wont compile
var name2 = o2.Name; // works
var price2 = o2.Price; // works
</code>```

This is becuase BaseClass doesnt have Price

Body:
    public class BaseClass
    {
        public string Name { get; set; }
    }

    public class SubClass : BaseClass
    {
        public decimal Price { get; set; }
    }

    BaseClass o1 = new SubClass();
    SubClass o2 = new SubClass();

    Console.WriteLine(o1.GetType().Name);
    Console.WriteLine(o2.GetType().Name);

Outputs are

    SubClass
    SubClass

What is the main difference between o1 and o2? In which cases is it necessary to define an object with BaseClass and instantiate it with SubClass?

Body:
The big difference is evident when you try this

BaseClass o1 = new SubClass();
SubClass o2 = new SubClass();
var name1 = o1.Name; // works
var price1 = o1.Price; // wont compile
var name2 = o2.Name; // works
var price2 = o2.Price; // works

This is becuase BaseClass doesnt have Price


问:
how to upload and download images to ftp server in flutter?
please help me to downloading and uploading operation to a ftp server in flutter camera Application. which package using for this operation?</p>

答:
What I did is edit the android/app/androidmanifest.xml and add:

```<code>uses-permission android:name="android.permission.INTERNET"
</code>```

Also add this package your pubspec.yaml:

```<code>dependencies:
  ftpconnect: ^1.0.0
</code>```

Body:
What I did is edit the android/app/androidmanifest.xml and add:

uses-permission android:name="android.permission.INTERNET"

Also add this package your pubspec.yaml:

dependencies:
  ftpconnect: ^1.0.0


问:
AppEngine Datatransfer
I am trying to transfer data in the form of objects between a gwt client and the app engine server. The objects i transfer need to be persistable (a blog comment for example). as it turns out AppEngine is uncomfortable to include those persistable objects (annotated as @PersistenceCapable) in the gwt module, because the gwt client cant store such date. Also the gwt client cant call a remote procedure with objects which are not concrete. So there is not the option to define interfaces for accessing those classes.

In short:
GWT Client cant work with interfaces, but also not with persistable annotated classes.

My Question is: how can i design an application which transfers stored data between the gwt client and the appengine. This is currently a real problem for me. it seems to me as if the only option is a DataTransferObejct which is just pure sensless code doing the exact thing the data-objects do: storing data.

I used the appengine.datastore Key for the id's of the classes.

Any suggestions ? Or am i getting something wrong ?

答: What version of GWT are you using? I regularly share data between GWT and GAE using serializable POJOs annotated PersistenceCapable. If you are using Key key, use Long id instead to get it working.</p>

Title: AppEngine Datatransfer


问:
Assigning domain name to Google Cloud VM
I'm attempting to assign a domain name to my Google Cloud VM external IP. I was following some walkthroughs and getting a bit confused. I set up apache with a simple "Hello" message when you visit my external IP. The walkthroughs I'm following are providing steps to reserve a new static external IP and creating a DNS zone.

Could someone provide clarification on why I would need to secure a new static external IP address when it appears I already have one assigned?

答:
As discussed by @Ferregina Pelona in the comment section. The public IP that your VM already has is an ephimeral one which means that if the VM is stopped or restarted, there is a possibility this public IP changes. The problem will be that if it changes, your DNS will continue pointing to the old one which means your site will be not accesible until you update the DNS with the new IP. Reserving the public IP will warranty your VM always has the same IP.

Also, added by @DazWilkin. it should be more explicit in the documentation but I assume (!) it's an ephemeral IP. I submitted doc feedback for this.


问:
SQL function to count the number of times a customer logged in
With this formula, it shows the number of log times perfectly, since day 1:

```<code>SELECT username, COUNT(time) AS session_count
FROM login_history
GROUP BY username;
</code>```

But with this one, which is my (almost) full formula to gather a lot of different data, it doesn't give me the same results regarding the logs count:

```<code>SELECT
    user.username AS 'Contact ID',
    user.firstname AS 'First name',
    user.lastname AS 'Last name',
    user.email AS Email,
    user.orgname AS 'Company ID',
    expiry_date AS 'Expiry date',
    COUNT(time) AS 'Login activity since day 1',
    MAX(time) AS 'Last login date',
    login_history.browser_family AS 'Web browser',
    login_history.browser_version AS 'Web browser version',
    login_history.os_family AS 'Device OS',
    login_history.os_version AS 'OS version',
    login_history.device_family AS 'Device family',
    login_history.device_brand AS 'Device brand',
    login_history.device_model AS 'Device model',
    login_history.ip_address AS 'IP address',
    RIGHT(user.email, length(user.email)-INSTR(user.email, '@')) AS 'Company domain'
FROM
    `user`
INNER JOIN
    `login_history` ON login_history.username = user.username
WHERE
    orgname != 'XXX'
    AND is_active = 1
GROUP BY
    user.username, user.firstname, user.lastname, user.email,
    user.orgname, login_history.browser_family,
    login_history.browser_version, login_history.os_family,
    login_history.os_version, login_history.device_family,
    login_history.device_brand, login_history.device_model,
    login_history.ip_address
ORDER BY
    orgname ASC;
</code>```

I'm also trying to complete this formula to gather session logs count from the past 30 days and also from the past 3 days...

Thanks a lot for your help! :D

答:
Without data is not easy to try to guide you, but I would do as follows. Let's call "user_stuff" the whole user.username, user.firstname, user.lastname, user.email, user.orgname and login_stuff the whole login_history.browser_family, login_history.browser_version, login_history.os_family, login_history.os_version, login_history.device_family, login_history.device_brand, login_history.device_model, login_history.ip_address.

Does the following work as intended?

```<code>SELECT "login_stuff", COUNT(time) AS session_count
FROM login_history
GROUP BY "login_stuff";
</code>```

If so, does the following work as intended?

```<code>SELECT "login_stuff", COUNT(time) AS session_count
FROM login_history
WHERE orgname != 'XXX' AND is_active = 1
GROUP BY "login_stuff";
</code>```

If so, does the full query work as intended? Knowing where you introduced the "bug" (maybe just assumptions about the data) is of vital importance to try to understand how to fix this problem.

Body:
With this formula, it shows the number of log times perfectly, since day 1:

SELECT username, COUNT(time) AS session_count
FROM login_history
GROUP BY username;

But with this one, which is my (almost) full formula to gather a lot of different data, it doesn't give me the same results regarding the logs count:

SELECT
    user.username AS 'Contact ID',
    user.firstname AS 'First name',
    user.lastname AS 'Last name',
    user.email AS Email,
    user.orgname AS 'Company ID',
    expiry_date AS 'Expiry date',
    COUNT(time) AS 'Login activity since day 1',
    MAX(time) AS 'Last login date',
    login_history.browser_family AS 'Web browser',
    login_history.browser_version AS 'Web browser version',
    login_history.os_family AS 'Device OS',
    login_history.os_version AS 'OS version',
    login_history.device_family AS 'Device family',
    login_history.device_brand AS 'Device brand',
    login_history.device_model AS 'Device model',
    login_history.ip_address AS 'IP address',
    RIGHT(user.email, length(user.email)-INSTR(user.email, '@')) AS 'Company domain'
FROM
    `user`
INNER JOIN
    `login_history` ON login_history.username = user.username
WHERE
    orgname != 'XXX'
    AND is_active = 1
GROUP BY
    user.username, user.firstname, user.lastname, user.email,
    user.orgname, login_history.browser_family,
    login_history.browser_version, login_history.os_family,
    login_history.os_version, login_history.device_family,
    login_history.device_brand, login_history.device_model,
    login_history.ip_address
ORDER BY
    orgname ASC;

I'm also trying to complete this formula to gather session logs count from the past 30 days and also from the past 3 days...

Thanks a lot for your help! :D

Body:
Without data is not easy to try to guide you, but I would do as follows. Let's call "user_stuff" the whole user.username, user.firstname, user.lastname, user.email, user.orgname and login_stuff the whole login_history.browser_family, login_history.browser_version, login_history.os_family, login_history.os_version, login_history.device_family, login_history.device_brand, login_history.device_model, login_history.ip_address.

Does the following work as intended?

SELECT "login_stuff", COUNT(time) AS session_count
FROM login_history
GROUP BY "login_stuff";

If so, does the following work as intended?

SELECT "login_stuff", COUNT(time) AS session_count
FROM login_history
WHERE orgname != 'XXX' AND is_active = 1
GROUP BY "login_stuff";

If so, does the full query work as intended? Knowing where you introduced the "bug" (maybe just assumptions about the data) is of vital importance to try to understand how to fix this problem.


问:
Custom WordPress theme showing index.php items in functions.php page
I'm following a video tutorial to convert a custom HTML template into a WordPress website. I copied my files into the themes folder and have renamed my files properly according to WordPress standards. Whilst I managed to get WordPress recognise my theme through edits in style.css, when I launch the website, I got a blank page.

I have an index.php filled with my front page code and a blank functions.php page. When I visit the the website at localhost/wordpress/, I got a blank page. When I open localhost/wordpress/functions.php, I got all the stuff.

I've searched online for solutions but still got no luck. I've also tried the debugging code, but I don't see any issue with my PHP code because I only had <?php get_header(); ?> and <?php get_footer(); ?> in my code.

What could possibly go wrong?

答: You can try to rename index.php to front-page.php, and leave a blank index.php</p>


问:
What is the best way to schedule one-time task on Spring boot from a REST endpoint call?
I'm trying to schedule task on Spring boot that executes based on some time duration. Currently I just put the thread in sleep for specified amount of time. This oviously fails for long durations. So, my question is what is the best way to schedule one time task from an endpoint?

P.S : I'm using spring-boot with Mongo as database.

答:
Take a look at https://www.baeldung.com/spring-scheduled-tasks.

The schedulers can be configured simply and precisely using Cron Expressions.


问:
How to add and remove views in a ScrollView without changing the current position of the view being shown?
I have a LinearLayout inside a ScrollView and I want to create the ilusion of endless scrolling by removing the views that are not visible and putting them as the next elements in the list (basically i do a linearlayout.removeView(viewOutOfScreen) and then linearlayout.addView(viewOutOfScreen). The problem is, every time this happens the view that is currently visible ends up in the top of the ScrollView. I tried doing a scrollView.scrollTo(0, -viewOutOfScreen.contentHeight) and it kinda works but the transition generates an horrible tearing artifact.
Also I'm not able to use RecyclerView given that the views are WebViews with very specific settings and executing js, so i nedd to reutilize/reposition them manually (cant't create more than i initially have).

答:
Also I'm not able to use RecyclerView given that the views are WebViews with very specific settings and executing js, so i nedd to reutilize/reposition them manually (cant't create more than i initially have).

So what if they're WebViews? You could just manually cache the views you want to display (ignoring the "recycling" part of RecyclerView) and return the View you want for each index instead of letting the RecyclerView delete and recreate them.


问:
Visual Studio Code Standard Logic Apps Editing existing logic app
I wonder if someone can give me some advice. I want to know if it is at all possible to edit a current standard logic app in VS Code. I can see it in the designer but not allowed to edit at all. Is this a limitation in VS Code?</p>

答:
You can go to File -> Save or a simple simple ctrl+S should work fine.

Updated Answer

This behavior happens because after you open a logic app's .json file, Visual Studio caches the subscription for future use. To resolve this You can create another logic app and copy the json content from the workflow you are looking at, save it to your newly created logic app workflow and then deploy the new logic app to your old one


问:
Columns not displaying correctly using python dash and mongo db
I am working on a project and after finally getting around some Type errors, I am finally getting my chart to display but it is listing each character in each mongo db json document instead of in proper json form. I am a total noob at this and I cannot seem to get it right so any help that can be offered in getting my interactive chart displayed as well as my pie chart and location chart will be greatly appreciated. I think the problem is derived from how the data is being entered into the dataframe but I can not figure it out.

Here is the read functions that are being used to take the info from the mongo db and send it to the Python script:

```<code>def read(self, data):
        if data !=None:  # checks to make sure that the received data is not null
            result = self.database.animals.find(data).limit(35)
            return result
        else:
            raise Exception("Data entered is null!")

def readAll(self, data):
        found = self.database.animals.find({}).limit(35)
        return(found)
</code>```

Here is the code for the python script that has imported dash:

```<code>from jupyter_plotly_dash import JupyterDash

import dash
import dash_leaflet as dl
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import dash_table
from dash.dependencies import Input, Output
from bson.json_util import dumps,loads
import bson
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pymongo import MongoClient
from AAC import AnimalShelter

###########################
# Data Manipulation / Model
###########################
# FIX ME update with your username and password and CRUD Python module name

username = "aacuser"
password = "Melvin1234!"
shelter = AnimalShelter()
shelter._init_(username,password)

# class read method must support return of cursor object and accept projection json input
df =pd.DataFrame.from_records(list(dumps(shelter.readAll({}))))

dff = pd.DataFrame.from_records(list(dumps(shelter.readAll({}))))

#########################
# Dashboard Layout / View
#########################

app = JupyterDash('SimpleExample')
import base64

app.layout = html.Div([
    html.Div(id='hidden-div', style={'display':'none'}),
    html.Center(html.B(html.H1('SNHU CS-340 Dashboard'))),
    html.Div(className='header',
             children=[html.Center(html.Img(src='/home/16514911_snhu/Downloads/Grazioso Salvare Logo.jpg',width="500", height="600")), #image logo
                      html.Center(html.B(html.H6('Jacqueline Woods')))]), #Unique Handle
    html.Br(),
    html.Div(className ='row',
            children=[
                html.Button(id='submit-button-one',n_clicks=0, children='Cats'),
                html.Button(id='submit-button-two',n_clicks=0,children='Dogs') ]),

    html.Div(dash_table.DataTable(
            id='datatable-interactivity',
                columns=[
                    {"name": i, "id": i,"age_upon_outcome":i, 'animal_id':i,'animal_type':i,'breed':i,"color":i,
                     'date_of_birth':i,'datetime':i,'monthyear':i,'outcome_subtype':i,'outcome_type':i,'sex_upon_outcome':i,
                     'location_lat':i,'location_long':i,'age_upon_outcome_in_weeks':i,
                    "deletable": False, "selectable": True} for i in df.columns]
                    ,data=df.to_dict('records'),editable = False,filter_action='native')),
     html.Br(),
     html.Div(
            dcc.Graph(            #piechart
                id ='graph_id',
                figure=list(dumps(shelter.readAll({})))
                           ),
            title="Outcome_Type"),

      html.Br(),
      html.Div(   #location map
            id='map-id',
            className='col s12 m6',
            title="Location"
            )])

 ##Interaction Between Components / Controller

#This callback will highlight a row on the data table when the user selects it
@app.callback(
    Output('datatable-interactivity',"data"),
    [Input('submit-button-one','n_clicks'),
    Input('submit-button-two','n_clicks')
    ]
)
def on_click(bt1, bt2):
    if(int(bt1) ==0 and int(bt2) ==0):
        df =pd.DataFrame.from_records(shelter.readAll({}))
    elif (int(bt1) > int(bt2)):
            df = pd.DataFrame(dumps(shelter.read({"animal__type":"Cat"})))
            df =pd.DataFrame(dumps(shelter.read({"animal_type":"Dog"})))
    return df.to_dict('records')
@app.callback(
    Output('datatable-interactivity', 'style_data_conditional'),
    [Input('datatable-interactivity', 'selected_columns')]
)
def update_styles(selected_columns):
    return [{
        'if': { 'column_id': i },
        'background_color': '#D2F3FF'
    } for i in selected_columns]

@app.callback(
    Output('graph_id','figure'),
    [Input('datatable-interactivity',"derived_virtual_data")])
def update_Graph(allData):
    dff= pd.DataFrame(allData)
    pieChart = px.pie(
        data_frame=dff,
        names=dff['outcome_type'],
        hole = 3,
    )
    return pieChart

@app.callback(
    Output('map-id', "children"),
    [Input('datatable-interactivity', 'derived_viewport_data'),
     Input('datatable-interactivity', 'derived_virtual_selected_rows')
    ])
def update_map(viewData):
#FIXME Add in the code for your geolocation chart
    dff = pd.DataFrame.from_dict(viewData)
    dff = df if viewData is None else pd.DataFrame(viewData)
    selected_animal = None
    if not derived_virtual_selected_rows:
        slected_animal = dff.iloc[0]
    else:
        slected_animal = dff.iloc[derived_vertual_selected_rows[0]]
    latitude = selected_animal[12]
    longitude =selected_animal[13]
    breed = selected_animal[3]
    name = selected_animal[0]
    # Austin TX is at [30.75,-97.48]
    return [
        dl.Map(style={'width': '1000px', 'height': '500px'}, center=[30.75,-97.48], zoom=10, children=[
            dl.TileLayer(id="base-layer-id"),
            # Marker with tool tip and popup
            dl.Marker(position=[latitude,longitude], children=[
                dl.Tooltip(breed),
                dl.Popup([
                    html.H1("Animal Name"),
                    html.P(name)
                ])
            ])
        ])
    ]

app
</code>```

答:
I was in the same boat as you searching for answers online. I happened to found the answer. Hopefully, this can help others who are experiencing this problem.

```<code>#Convert the pymongo cursor into a pandas DataFrame
df = pd.DataFrame(list(shelter.readAll({})))

#Drop the _id column generated by Mongo
df = df.iloc[:, 1:]
</code>```

After that, you can access the data of the DataFrame by using

```<code>df.to_dict('records')
</code>```

Body:
I am working on a project and after finally getting around some Type errors, I am finally getting my chart to display but it is listing each character in each mongo db json document instead of in proper json form. I am a total noob at this and I cannot seem to get it right so any help that can be offered in getting my interactive chart displayed as well as my pie chart and location chart will be greatly appreciated. I think the problem is derived from how the data is being entered into the dataframe but I can not figure it out.

Here is the read functions that are being used to take the info from the mongo db and send it to the Python script:

def read(self, data):
        if data !=None:  # checks to make sure that the received data is not null
            result = self.database.animals.find(data).limit(35)
            return result
        else:
            raise Exception("Data entered is null!")

def readAll(self, data):
        found = self.database.animals.find({}).limit(35)
        return(found)

Here is the code for the python script that has imported dash:

from jupyter_plotly_dash import JupyterDash

import dash
import dash_leaflet as dl
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import dash_table
from dash.dependencies import Input, Output
from bson.json_util import dumps,loads
import bson
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pymongo import MongoClient
from AAC import AnimalShelter

###########################
# Data Manipulation / Model
###########################
# FIX ME update with your username and password and CRUD Python module name

username = "aacuser"
password = "Melvin1234!"
shelter = AnimalShelter()
shelter._init_(username,password)

# class read method must support return of cursor object and accept projection json input
df =pd.DataFrame.from_records(list(dumps(shelter.readAll({}))))

dff = pd.DataFrame.from_records(list(dumps(shelter.readAll({}))))

#########################
# Dashboard Layout / View
#########################

app = JupyterDash('SimpleExample')
import base64

app.layout = html.Div([
    html.Div(id='hidden-div', style={'display':'none'}),
    html.Center(html.B(html.H1('SNHU CS-340 Dashboard'))),
    html.Div(className='header',
             children=[html.Center(html.Img(src='/home/16514911_snhu/Downloads/Grazioso Salvare Logo.jpg',width="500", height="600")), #image logo
                      html.Center(html.B(html.H6('Jacqueline Woods')))]), #Unique Handle
    html.Br(),
    html.Div(className ='row',
            children=[
                html.Button(id='submit-button-one',n_clicks=0, children='Cats'),
                html.Button(id='submit-button-two',n_clicks=0,children='Dogs') ]),

    html.Div(dash_table.DataTable(
            id='datatable-interactivity',
                columns=[
                    {"name": i, "id": i,"age_upon_outcome":i, 'animal_id':i,'animal_type':i,'breed':i,"color":i,
                     'date_of_birth':i,'datetime':i,'monthyear':i,'outcome_subtype':i,'outcome_type':i,'sex_upon_outcome':i,
                     'location_lat':i,'location_long':i,'age_upon_outcome_in_weeks':i,
                    "deletable": False, "selectable": True} for i in df.columns]
                    ,data=df.to_dict('records'),editable = False,filter_action='native')),
     html.Br(),
     html.Div(
            dcc.Graph(            #piechart
                id ='graph_id',
                figure=list(dumps(shelter.readAll({})))
                           ),
            title="Outcome_Type"),

      html.Br(),
      html.Div(   #location map
            id='map-id',
            className='col s12 m6',
            title="Location"
            )])

 ##Interaction Between Components / Controller

#This callback will highlight a row on the data table when the user selects it
@app.callback(
    Output('datatable-interactivity',"data"),
    [Input('submit-button-one','n_clicks'),
    Input('submit-button-two','n_clicks')
    ]
)
def on_click(bt1, bt2):
    if(int(bt1) ==0 and int(bt2) ==0):
        df =pd.DataFrame.from_records(shelter.readAll({}))
    elif (int(bt1) > int(bt2)):
            df = pd.DataFrame(dumps(shelter.read({"animal__type":"Cat"})))
            df =pd.DataFrame(dumps(shelter.read({"animal_type":"Dog"})))
    return df.to_dict('records')
@app.callback(
    Output('datatable-interactivity', 'style_data_conditional'),
    [Input('datatable-interactivity', 'selected_columns')]
)
def update_styles(selected_columns):
    return [{
        'if': { 'column_id': i },
        'background_color': '#D2F3FF'
    } for i in selected_columns]

@app.callback(
    Output('graph_id','figure'),
    [Input('datatable-interactivity',"derived_virtual_data")])
def update_Graph(allData):
    dff= pd.DataFrame(allData)
    pieChart = px.pie(
        data_frame=dff,
        names=dff['outcome_type'],
        hole = 3,
    )
    return pieChart

@app.callback(
    Output('map-id', "children"),
    [Input('datatable-interactivity', 'derived_viewport_data'),
     Input('datatable-interactivity', 'derived_virtual_selected_rows')
    ])
def update_map(viewData):
#FIXME Add in the code for your geolocation chart
    dff = pd.DataFrame.from_dict(viewData)
    dff = df if viewData is None else pd.DataFrame(viewData)
    selected_animal = None
    if not derived_virtual_selected_rows:
        slected_animal = dff.iloc[0]
    else:
        slected_animal = dff.iloc[derived_vertual_selected_rows[0]]
    latitude = selected_animal[12]
    longitude =selected_animal[13]
    breed = selected_animal[3]
    name = selected_animal[0]
    # Austin TX is at [30.75,-97.48]
    return [
        dl.Map(style={'width': '1000px', 'height': '500px'}, center=[30.75,-97.48], zoom=10, children=[
            dl.TileLayer(id="base-layer-id"),
            # Marker with tool tip and popup
            dl.Marker(position=[latitude,longitude], children=[
                dl.Tooltip(breed),
                dl.Popup([
                    html.H1("Animal Name"),
                    html.P(name)
                ])
            ])
        ])
    ]

app

Body:
I was in the same boat as you searching for answers online. I happened to found the answer. Hopefully, this can help others who are experiencing this problem.

#Convert the pymongo cursor into a pandas DataFrame
df = pd.DataFrame(list(shelter.readAll({})))

#Drop the _id column generated by Mongo
df = df.iloc[:, 1:]

After that, you can access the data of the DataFrame by using

df.to_dict('records')


答:
Maybe something like this:

```<code>// I'm making up the types here; modify to match your actual types
public interface IMyObject {
    public int Rate { get; set; }
    public DateTime Date { get; set; }
    public int MinVal { get; set; }
    public int MaxVal { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
}

public static class MyObjectFactory {
    public static T Create<T>(int rate, DateTime date, /* etc.. */)
            where T : IMyObject, new() {

        if (/* tests */) {
            throw new MyObjectException("Constraint violated ...");
        }

        T obj = new T();

        obj.Rate = rate;
        obj.Date = date;
        // etc ....

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

And then you would use it like so:

```<code>public class SomeMyObject : IMyObject {
    // implementation omitted for brevity ...
}

// somewhere:
SomeMyObject obj = MyObjectFactory.Create<SomeMyObject>(rate, date, /* etc. */);
</code>```

Is that what you're asking for?

Title: Using Generics in C# to compare conditionally

Body:
In my scenario, I have two types of objects. A plan and a tier. Each one shares certain values, while the tier has 3 additional values (Rate, Min, and Max).

I would like to make a generic method to conditionally evaluate whether or not the new object can be written to the database, based on the following conditions:

Creation:

A tier: ((o1.Rate!=o2.Rate) || ((o1.Start!=o2.Start) && (o1.End!=o2.End))) && (MinVal && MaxVal)

A tier or plan: (o1.Name!=o2.Name)

A tier or plan: Only one can have (Active == true), the rest must be false.

Is it possible to create a generic method for something like this? If so, are there any examples of something like this? Or does anyone have suggestions?

thanks!

MORE:
So I have a list of objects, and I need to compare a newly created one with each other object in the database before I actually write it to the database.

Body:
Maybe something like this:

// I'm making up the types here; modify to match your actual types
public interface IMyObject {
    public int Rate { get; set; }
    public DateTime Date { get; set; }
    public int MinVal { get; set; }
    public int MaxVal { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
}

public static class MyObjectFactory {
    public static T Create<T>(int rate, DateTime date, /* etc.. */)
            where T : IMyObject, new() {

        if (/* tests */) {
            throw new MyObjectException("Constraint violated ...");
        }

        T obj = new T();

        obj.Rate = rate;
        obj.Date = date;
        // etc ....

        return obj;
    }
}

And then you would use it like so:

public class SomeMyObject : IMyObject {
    // implementation omitted for brevity ...
}

// somewhere:
SomeMyObject obj = MyObjectFactory.Create<SomeMyObject>(rate, date, /* etc. */);

Is that what you're asking for?


问:
React Typescript: Reflection (listing properties of an interface)
im writing a node-based editor for neural-nets that (currently) uses tensorflow.js for the creation of the networks themself. Tensorflow.js has a layers api with diffrent factory-functions that each have an interface for their arguments. E.g.

interface DenseLayerArgs {
    units: number,
    useBias?: boolean,
    ...
}
const dense(args: DenseLayerArgs): {
...
}
```

My goal is to load all of those factory functions automaticly and create a menu for each thats based on the Args interface. Since its not possible to access properties that might be undefined in plain TS, the solution seems to be some kind of transformer library (eg. https://www.npmjs.com/package/ts-reflection ). But i havnt been able to get any custom transformer running with my create-react-app with typescript setup.

Has anyone been able to get React working with custom transformers or has some other solution for creating a menu from an interface ?

cheers

答:
I recommend the tst-reflect for the TypeScript Reflection.

In the README, there is a section How to Start. You have to use eg. ttypescript to get transformers working. TypeScript does not support transformers out of the box, only by direct calls to their Compiler API. ttypescript is some kind of wrap which allows you to define transformers in tsconfig.

Copy of that How to Start:

Install packages.

```<code>npm i tst-reflect && npm i tst-reflect-transformer -D
</code>```

In order to use transformer plugin you need TypeScript compiler which supports plugins eg. package ttypescript or you can use TypeScript compiler API manually.

```<code>npm i ttypescript -D
</code>```

Add transformer to tsconfig.json

```<code>{
    "compilerOptions": {
        // your options...

        // ADD THIS!
        "plugins": [
            {
                "transform": "tst-reflect-transformer"
            }
        ]
    }
}
</code>```

Now just transpile your code by ttsc instead of tsc

```<code>npx ttsc
</code>```

And usage with Webpack:

Modify your webpack config. Use options.compiler of ts-loader to set ttypescript compiler.

({
    test: /\.(ts|tsx)$/,
    loader: require.resolve("ts-loader"),
    options: {
        compiler: "ttypescript"
    }
})
```
<p><strong>And how to list the properties of an Interface with <code>tst-reflect</code>?</strong></p>
<pre class="lang-js prettyprint-override"><code>import { getType, Property} from "tst-reflect";

interface DenseLayerArgs {
    units: number,
    useBias?: boolean,
    // ...
}

const properties: Array<Property> = getType<DenseLayerArgs>().getProperties();
// Do something with properties...
</code>```

Property is:

interface Property
{
    /**
     * Property name
     */
    readonly name: string;
    /**
     * Property type
     */
    readonly type: Type;
    /**
     * Optional property
     */
    readonly optional: boolean;
    /**
     * Access modifier
     */
    readonly accessModifier: AccessModifier;
    /**
     * Accessor
     */
    readonly accessor: Accessor;
    /**
     * Readonly
     */
    readonly readonly: boolean;
    /**
     * Returns array of decorators
     */
    getDecorators(): ReadonlyArray<Decorator>;
}
```

Body:
im writing a node-based editor for neural-nets that (currently) uses tensorflow.js for the creation of the networks themself. Tensorflow.js has a layers api with diffrent factory-functions that each have an interface for their arguments. E.g.

interface DenseLayerArgs {
    units: number,
    useBias?: boolean,
    ...
}
const dense(args: DenseLayerArgs): {
...
}

My goal is to load all of those factory functions automaticly and create a menu for each thats based on the Args interface. Since its not possible to access properties that might be undefined in plain TS, the solution seems to be some kind of transformer library (eg. https://www.npmjs.com/package/ts-reflection ). But i havnt been able to get any custom transformer running with my create-react-app with typescript setup.

Has anyone been able to get React working with custom transformers or has some other solution for creating a menu from an interface ?

cheers

Body:
I recommend the tst-reflect for the TypeScript Reflection.

In the README, there is a section How to Start. You have to use eg. ttypescript to get transformers working. TypeScript does not support transformers out of the box, only by direct calls to their Compiler API. ttypescript is some kind of wrap which allows you to define transformers in tsconfig.

Copy of that How to Start:

Install packages.

npm i tst-reflect && npm i tst-reflect-transformer -D

In order to use transformer plugin you need TypeScript compiler which supports plugins eg. package ttypescript or you can use TypeScript compiler API manually.

npm i ttypescript -D

Add transformer to tsconfig.json

{
    "compilerOptions": {
        // your options...

        // ADD THIS!
        "plugins": [
            {
                "transform": "tst-reflect-transformer"
            }
        ]
    }
}

Now just transpile your code by ttsc instead of tsc

npx ttsc

And usage with Webpack:

Modify your webpack config. Use options.compiler of ts-loader to set ttypescript compiler.

({
    test: /\.(ts|tsx)$/,
    loader: require.resolve("ts-loader"),
    options: {
        compiler: "ttypescript"
    }
})

And how to list the properties of an Interface with tst-reflect?

import { getType, Property} from "tst-reflect";

interface DenseLayerArgs {
    units: number,
    useBias?: boolean,
    // ...
}

const properties: Array<Property> = getType<DenseLayerArgs>().getProperties();
// Do something with properties...

Property is:

interface Property
{
    /**
     * Property name
     */
    readonly name: string;
    /**
     * Property type
     */
    readonly type: Type;
    /**
     * Optional property
     */
    readonly optional: boolean;
    /**
     * Access modifier
     */
    readonly accessModifier: AccessModifier;
    /**
     * Accessor
     */
    readonly accessor: Accessor;
    /**
     * Readonly
     */
    readonly readonly: boolean;
    /**
     * Returns array of decorators
     */
    getDecorators(): ReadonlyArray<Decorator>;
}


问:
set custom delimiters in Vue.js 3
I am trying to set custom delimiters in Vue.js 3 but it does not seem to work.

The first thing I tried is setting the component parameter delimiters like this:

```<code>export default defineComponent({
    delimiters: ["${", "}$"],
    // ...
})
</code>```

but nothing happens.

Then I tried setting main.ts file like this:

```<code>import { createApp } from "vue";
import router from "./router";
import App from "./App.vue";

App.delimiters = ["${", "}$"];

createApp(App)
   .use(router)
   .mount("#app");
</code>```

Again the string interpolation in the template isn't working.

What am I missing?

答:
If you look at the console in your browser's dev tools you may see something like:

"""
vue.runtime.esm-browser.js:1486 [Vue warn]: Component provided template option but runtime compilation is not supported in this build of Vue. Use "vue.esm-browser.js" instead. at
"""

```<code>import { createApp } from "vue";
</code>```

points to 'vue/dist/vue.runtime.esm-browser' which doesn't support the delimiters option because it requires compilation not available with this build.

Now replace the import line with

```<code>import { createApp } from "vue/dist/vue.esm-browser";
</code>```

or

```<code>import { createApp } from "vue/dist/vue.esm-bundler";
</code>```

It should work just fine.

Title: set custom delimiters in Vue.js 3

Body:
I am trying to set custom delimiters in Vue.js 3 but it does not seem to work.

The first thing I tried is setting the component parameter delimiters like this:

export default defineComponent({
    delimiters: ["${", "}$"],
    // ...
})

but nothing happens.

Then I tried setting main.ts file like this:

import { createApp } from "vue";
import router from "./router";
import App from "./App.vue";

App.delimiters = ["${", "}$"];

createApp(App)
   .use(router)
   .mount("#app");

Again the string interpolation in the template isn't working.

What am I missing?

Body:
If you look at the console in your browser's dev tools you may see something like:

"""
vue.runtime.esm-browser.js:1486 [Vue warn]: Component provided template option but runtime compilation is not supported in this build of Vue. Use "vue.esm-browser.js" instead. at
"""

import { createApp } from "vue";

points to 'vue/dist/vue.runtime.esm-browser' which doesn't support the delimiters option because it requires compilation not available with this build.

Now replace the import line with

import { createApp } from "vue/dist/vue.esm-browser";

or

import { createApp } from "vue/dist/vue.esm-bundler";

It should work just fine.


问:
I want to use next/image to fill half width in div container
i'm learning nextjs and tailwind css.

I want to fill half width using next/image.

but, it's using full width

```<code>
function Slider() {
  return (
    <div className="w-full h-screen flex  relative">
      <div className="Arrow left-[10px]">
        <ArrowLeftOutlined />
      </div>
      <div className="Wrapper h-full flex">
        <div className=" w-screen h-screen flex items-center">
          <div className="ImgContainer h-full flex-1 ">
            <Image
              className=""
              src=""
              layout="fill"
            />
          </div>
          <div className="Info flex-1 p-[50px]"></div>
        </div>
      </div>
      <div className="Arrow right-[10px]">
        <ArrowRightOutlined />
      </div>
    </div>
  );
}

</code>```

This is my code, plz let me know..

答:
Set position: relative for the wrapping div

```<code>function Slider() {
  return (
    <div className="w-full h-screen flex  relative">
      <div className="Arrow left-[10px]">
        <ArrowLeftOutlined />
      </div>
      <div className="Wrapper h-full flex">
        <div className=" w-screen h-screen flex items-center">
          <div className="ImgContainer h-full flex-1 relative">
            <Image
              className=""
              src=""
              layout="fill"
            />
          </div>
          <div className="Info flex-1 p-[50px]"></div>
        </div>
      </div>
      <div className="Arrow right-[10px]">
        <ArrowRightOutlined />
      </div>
    </div>
  );
}
</code>```

Body:
i'm learning nextjs and tailwind css.

I want to fill half width using next/image.

but, it's using full width

function Slider() {
  return (

        <ArrowLeftOutlined />

            <Image
              className=""
              src=""
              layout="fill"
            />

        <ArrowRightOutlined />

  );
}

This is my code, plz let me know..

Body:
Set position: relative for the wrapping div

function Slider() {
  return (
    <div className="w-full h-screen flex  relative">
      <div className="Arrow left-[10px]">
        <ArrowLeftOutlined />
      </div>
      <div className="Wrapper h-full flex">
        <div className=" w-screen h-screen flex items-center">
          <div className="ImgContainer h-full flex-1 relative">
            <Image
              className=""
              src=""
              layout="fill"
            />
          </div>
          <div className="Info flex-1 p-[50px]"></div>
        </div>
      </div>
      <div className="Arrow right-[10px]">
        <ArrowRightOutlined />
      </div>
    </div>
  );
}


问:
Mail returns false
I'm currently using a custom made library at my job. Until just rencently the library was working perfectly. It apparently return false since about today.

The library itself it basically a wrapper around the function mail. It builds the "boundaries" parts and everything.

Since the class is quite big enough I wont post it here ... but I'm wondering, what are the reasons in theory of why mail would return false?

SMTP is set in PHP.ini

Sender is set in headers

Sender is int the form of: sender<sender@email.com>

Everything is sent correctly (body+headers+subject)

Assume that mail( ) works correctly on the website but on this specific page it just doesn't. I know it must be comming from me but would be fun to have somewhere to start looking for.

Oh and yeah the library is undocumented.

[edit]
Just found a smaller function and still doesn't work, I'll print it out then:

```<code>function send_html($from, $email, $subject = "AUCUN", $message, $cc = "", $bcc ="", $priotity = "3") {
    $headers = "";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

    if (strpos($from, "ourwebsite.com") != false || strpos($from, "rencontresportive.com") != "") {
        $headers .= "From: Ourwebsite.com <" . $from . ">\r\n";
    } else {
        $headers .= "From: " . $from . " <" . $from . ">\r\n";
    }

    $headers .= "X-Sender: <" . $from . ">\r\n";
    $headers .= "X-Priority: " . $priotity . "\r\n";
    $headers .= "X-Mailer: PHP\r\n";
    $headers .= "Return-Path: <admin@ourwebsite.com>\r\n";

    if ($cc != "") {
        $headers .= "cc:" . $cc . "\r\n";
    }
    if ($bcc != "") {
        $headers .= "bcc:" . $bcc . "\r\n";
    }
        if (mail($email, $subject, $message, $headers)) {
        return true;
    } else {
        return false;
    }
}
</code>```

I called it with :

```<code>send_html(contact@ourwebsite.com, me@me.com, utf8_decode("the subject"), "<h1>test</h1>");
</code>```

答:
I had similar problem , mail function always returns false even if the email is received successfully.

I found in php configuration file php.ini,
I had set up

```<code>; For Win32 only.
;sendmail_from = me@example.com

; For Unix only.
sendmail_path = "/usr/sbin/sendmail -t -i -f "care@mydomain.com"
</code>```

I have changed it to below

```<code>; For Win32 only.
;sendmail_from = me@example.com

; For Unix only.
sendmail_path = /usr/sbin/sendmail -t -i -f care@mydomain.com
</code>```

As per this sendmail_from is for win32 , so in *unix OS we need to set the value as shown in sendmail_path variable.

Regards
Minesh

ContentLicense: CC BY-SA 2.5

Title: Mail returns false

Body:
I'm currently using a custom made library at my job. Until just rencently the library was working perfectly. It apparently return false since about today.

The library itself it basically a wrapper around the function mail. It builds the "boundaries" parts and everything.

Since the class is quite big enough I wont post it here ... but I'm wondering, what are the reasons in theory of why mail would return false?

SMTP is set in PHP.ini

Sender is set in headers

Sender is int the form of: sender<sender@email.com>

Everything is sent correctly (body+headers+subject)

Assume that mail( ) works correctly on the website but on this specific page it just doesn't. I know it must be comming from me but would be fun to have somewhere to start looking for.

Oh and yeah the library is undocumented.

[edit]
Just found a smaller function and still doesn't work, I'll print it out then:

function send_html($from, $email, $subject = "AUCUN", $message, $cc = "", $bcc ="", $priotity = "3") {
    $headers = "";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

    if (strpos($from, "ourwebsite.com") != false || strpos($from, "rencontresportive.com") != "") {
        $headers .= "From: Ourwebsite.com <" . $from . ">\r\n";
    } else {
        $headers .= "From: " . $from . " <" . $from . ">\r\n";
    }

    $headers .= "X-Sender: <" . $from . ">\r\n";
    $headers .= "X-Priority: " . $priotity . "\r\n";
    $headers .= "X-Mailer: PHP\r\n";
    $headers .= "Return-Path: <admin@ourwebsite.com>\r\n";

    if ($cc != "") {
        $headers .= "cc:" . $cc . "\r\n";
    }
    if ($bcc != "") {
        $headers .= "bcc:" . $bcc . "\r\n";
    }
        if (mail($email, $subject, $message, $headers)) {
        return true;
    } else {
        return false;
    }
}

I called it with :

send_html(contact@ourwebsite.com, me@me.com, utf8_decode("the subject"), "
test
");

Body:
I had similar problem , mail function always returns false even if the email is received successfully.

I found in php configuration file php.ini,
I had set up

; For Win32 only.
;sendmail_from = me@example.com

; For Unix only.
sendmail_path = "/usr/sbin/sendmail -t -i -f "care@mydomain.com"

I have changed it to below

; For Win32 only.
;sendmail_from = me@example.com

; For Unix only.
sendmail_path = /usr/sbin/sendmail -t -i -f care@mydomain.com

As per this sendmail_from is for win32 , so in *unix OS we need to set the value as shown in sendmail_path variable.

Regards
Minesh


问:
Jq strftime() to show time in a specific time zone
How to use jq to convert seconds since Unix epoch to a time string in human readable format but adjusted to Sydney, Australia time zone?

I tried filter:

```<code>now | strftime("%Y-%m-%dT%H:%M:%SZ")
</code>```

But I don't know how to adjust the time format string to convey Sydney, Australia time zone.

Possibly I need to replace "Z" with the relevant time zone?

答:
If you are using jq v1.6, use strflocaltime instead of strftime which displays the time in your timezone.

jq -n 'now | strflocaltime("%Y-%m-%dT%H:%M:%S")'
```
<p>Demo</p>
<p>From the manual:</p>
<blockquote>
<p>The <code>strftime(fmt)</code> builtin formats a time (GMT) with the given format. The <code>strflocaltime</code> does the same, but using the local timezone setting.</p>
</blockquote>
<p>If your timezone is different, set the shell's <code>TZ</code> variable accordingly before calling <code>jq</code></p>
<pre class="lang-sh prettyprint-override"><code>TZ=Australia/Sydney jq -n 'now | strflocaltime("%Y-%m-%dT%H:%M:%S")'
</code>```

Body:
How to use jq to convert seconds since Unix epoch to a time string in human readable format but adjusted to Sydney, Australia time zone?

I tried filter:

now | strftime("%Y-%m-%dT%H:%M:%SZ")

But I don't know how to adjust the time format string to convey Sydney, Australia time zone.

Possibly I need to replace "Z" with the relevant time zone?

Body:
If you are using jq v1.6, use strflocaltime instead of strftime which displays the time in your timezone.

jq -n 'now | strflocaltime("%Y-%m-%dT%H:%M:%S")'

Demo

From the manual:

The strftime(fmt) builtin formats a time (GMT) with the given format. The strflocaltime does the same, but using the local timezone setting.

If your timezone is different, set the shell's TZ variable accordingly before calling jq

TZ=Australia/Sydney jq -n 'now | strflocaltime("%Y-%m-%dT%H:%M:%S")'


问:
How to implement Stripe Payment Element in Laravel
I'm trying to implement Stripe's new Payment Element in Laravel, which supports Apple Pay, Google Pay and cards by default and uses the user's country to select the most relevant payment methods, but all of the guides that I can find online for integrating Stripe with Laravel use the old Card Element or don't even use the PaymentIntents API at all.

Stripe's documentation itself only covers the PHP implementation, and I can't figure out from that how to implement it in a Laravel-idiomatic way, which at the moment seems like an overwhelming task. How exactly would I go about implementing the new Stripe Payment Element in Laravel?

答:
I finally managed to get this working, and as a solution it's sufficient for a site accepting one-time payments, although if you plan to take recurring payments I would recommend taking the plunge and setting up Laravel Cashier as recommended by jszobody.

I made some notable changes to the code in the Stripe docs, although apart from those changes the code below is virtually untouched and could definitely be written in a more Laravel way by someone more experienced in Laravel, and I'd welcome any edits accordingly.

Routes/web.php:

```<code>Route::get('/payment', [PaymentController::class, "index"]);
Route::post('/charge', [PaymentController::class, "pay"]);
</code>```

Create the referenced controller with php artisan make:controller PaymentController, and give PaymentController the following content:

```<code><?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Payment;
use Exception;
use Stripe;

class PaymentController extends Controller
{

    public function index()
    {
        return view('payment');
    }

    public function pay(Request $request)
    {

        // Replace with your secret key, found in your Stripe dashboard
        Stripe\Stripe::setApiKey('<YOUR_SECRET_KEY>');

        function calculateOrderAmount(array $items): int {
            return 499;
        }

        header('Content-Type: application/json');

        try {

            $jsonStr = file_get_contents('php://input');
            $jsonObj = json_decode($jsonStr);

            $paymentIntent = Stripe\PaymentIntent::create([
                'amount' => calculateOrderAmount($jsonObj->items),
                'currency' => 'gbp', // Replace with your country's primary currency
                'automatic_payment_methods' => [
                    'enabled' => true,
                ],
                // Remove if you don't want to send automatic email receipts after successful payment
                "receipt_email" => $request->email
            ]);

            $output = [
                'clientSecret' => $paymentIntent->client_secret,
            ];

            echo json_encode($output);
        } catch (Exception $e) {
            return back()->with(['error' => $e->getMessage()]);
        }
    }
}
</code>```

stripe_checkout.js:

The most significant change here from the Stripe docs was manually passing through the CSRF token in the HTTP headers. Leaving this out results in HTTP 419 errors due to a conflict with Laravel, and it took me much longer than it should have to solve this. Tip: when debugging stuff like this, working your way methodically through each error you see in the browser console is the key to getting things working.

```<code>// Replace with your public key, found in your Stripe dashboard
const stripe = Stripe("<YOUR_PUBLIC_KEY>");

const items = [{ id: "xl-tshirt" }];

let elements;

initialize();
checkStatus();

document
    .querySelector("#payment-form")
    .addEventListener("submit", handleSubmit);

async function initialize() {
    const { clientSecret } = await fetch("/charge", {
        method: "POST",
        headers: {
            "X-CSRF-TOKEN": document.querySelector('input[name="_token"]').value,
        },
        body: JSON.stringify({ items }),
    }).then((r) => r.json());

    elements = stripe.elements({ clientSecret });

    const paymentElement = elements.create("payment");
    paymentElement.mount("#payment-element");
}

async function handleSubmit(e) {
    e.preventDefault();
    setLoading(true);

    const { error } = await stripe.confirmPayment({
        elements,
        confirmParams: {
            // Replace with your payment completion page
            return_url: "http://localhost/success",
        },
    });

    if (error.type === "card_error" || error.type === "validation_error") {
        showMessage(error.message);
    } else {
        showMessage("An unexpected error occured.");
    }

    setLoading(false);
}

async function checkStatus() {
    const clientSecret = new URLSearchParams(window.location.search).get(
        "payment_intent_client_secret"
    );

    if (!clientSecret) {
        return;
    }

    const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);

    switch (paymentIntent.status) {
        case "succeeded":
            showMessage("Payment succeeded!");
            break;
        case "processing":
            showMessage("Your payment is processing.");
            break;
        case "requires_payment_method":
            showMessage("Your payment was not successful, please try again.");
            break;
        default:
            showMessage("Something went wrong.");
            break;
    }
}

// ------- UI helpers -------

function showMessage(messageText) {
    const messageContainer = document.querySelector("#payment-message");

    messageContainer.classList.remove("hidden");
    messageContainer.textContent = messageText;

    setTimeout(function () {
        messageContainer.classList.add("hidden");
        messageText.textContent = "";
    }, 4000);
}

function setLoading(isLoading) {
    if (isLoading) {
        document.querySelector("#submit").disabled = true;
        document.querySelector("#spinner").classList.remove("hidden");
        document.querySelector("#button-text").classList.add("hidden");
    } else {
        document.querySelector("#submit").disabled = false;
        document.querySelector("#spinner").classList.add("hidden");
        document.querySelector("#button-text").classList.remove("hidden");
    }
}
</code>```

stripe_checkout.css  (unchanged from the documentation):

```<code>/* Variables */
* {
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  font-size: 16px;
  -webkit-font-smoothing: antialiased;
  display: flex;
  justify-content: center;
  align-content: center;
  height: 100vh;
  width: 100vw;
}

form {
  width: 30vw;
  min-width: 500px;
  align-self: center;
  box-shadow: 0px 0px 0px 0.5px rgba(50, 50, 93, 0.1),
    0px 2px 5px 0px rgba(50, 50, 93, 0.1), 0px 1px 1.5px 0px rgba(0, 0, 0, 0.07);
  border-radius: 7px;
  padding: 40px;
}

.hidden {
  display: none;
}

#payment-message {
  color: rgb(105, 115, 134);
  font-size: 16px;
  line-height: 20px;
  padding-top: 12px;
  text-align: center;
}

#payment-element {
  margin-bottom: 24px;
}

/* Buttons and links */
button {
  background: #5469d4;
  font-family: Arial, sans-serif;
  color: #ffffff;
  border-radius: 4px;
  border: 0;
  padding: 12px 16px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  display: block;
  transition: all 0.2s ease;
  box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07);
  width: 100%;
}
button:hover {
  filter: contrast(115%);
}
button:disabled {
  opacity: 0.5;
  cursor: default;
}

/* spinner/processing state, errors */
.spinner,
.spinner:before,
.spinner:after {
  border-radius: 50%;
}
.spinner {
  color: #ffffff;
  font-size: 22px;
  text-indent: -99999px;
  margin: 0px auto;
  position: relative;
  width: 20px;
  height: 20px;
  box-shadow: inset 0 0 0 2px;
  -webkit-transform: translateZ(0);
  -ms-transform: translateZ(0);
  transform: translateZ(0);
}
.spinner:before,
.spinner:after {
  position: absolute;
  content: "";
}
.spinner:before {
  width: 10.4px;
  height: 20.4px;
  background: #5469d4;
  border-radius: 20.4px 0 0 20.4px;
  top: -0.2px;
  left: -0.2px;
  -webkit-transform-origin: 10.4px 10.2px;
  transform-origin: 10.4px 10.2px;
  -webkit-animation: loading 2s infinite ease 1.5s;
  animation: loading 2s infinite ease 1.5s;
}
.spinner:after {
  width: 10.4px;
  height: 10.2px;
  background: #5469d4;
  border-radius: 0 10.2px 10.2px 0;
  top: -0.1px;
  left: 10.2px;
  -webkit-transform-origin: 0px 10.2px;
  transform-origin: 0px 10.2px;
  -webkit-animation: loading 2s infinite ease;
  animation: loading 2s infinite ease;
}

@-webkit-keyframes loading {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@keyframes loading {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@media only screen and (max-width: 600px) {
  form {
    width: 80vw;
    min-width: initial;
  }
}
</code>```

payment.blade.view:

```<code><script src="https://js.stripe.com/v3/"></script>
<script src="{{ asset('js/stripe_checkout.js') }}" defer></script>
<link href="{{ asset('css/stripe_checkout.css') }}" rel="stylesheet" />

  ...

<div class="stripe-container">
  {{ csrf_field() }}
  <form id="payment-form">
  <div id="payment-element">
  <!-- Stripe.js injects the Payment Element here-->
  </div>
  <button id="submit">
  <div class="spinner hidden" id="spinner"></div>
  <span id="button-text">Pay £9.99</span>
  </button>
  <div id="payment-message" class="hidden"></div>
  </form>
</div>
</code>```

Body:
I finally managed to get this working, and as a solution it's sufficient for a site accepting one-time payments, although if you plan to take recurring payments I would recommend taking the plunge and setting up Laravel Cashier as recommended by jszobody.

I made some notable changes to the code in the Stripe docs, although apart from those changes the code below is virtually untouched and could definitely be written in a more Laravel way by someone more experienced in Laravel, and I'd welcome any edits accordingly.

Routes/web.php:

Route::get('/payment', [PaymentController::class, "index"]);
Route::post('/charge', [PaymentController::class, "pay"]);

Create the referenced controller with php artisan make:controller PaymentController, and give PaymentController the following content:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Payment;
use Exception;
use Stripe;

class PaymentController extends Controller
{

    public function index()
    {
        return view('payment');
    }

    public function pay(Request $request)
    {

        // Replace with your secret key, found in your Stripe dashboard
        Stripe\Stripe::setApiKey('<YOUR_SECRET_KEY>');

        function calculateOrderAmount(array $items): int {
            return 499;
        }

        header('Content-Type: application/json');

        try {

            $jsonStr = file_get_contents('php://input');
            $jsonObj = json_decode($jsonStr);

            $paymentIntent = Stripe\PaymentIntent::create([
                'amount' => calculateOrderAmount($jsonObj->items),
                'currency' => 'gbp', // Replace with your country's primary currency
                'automatic_payment_methods' => [
                    'enabled' => true,
                ],
                // Remove if you don't want to send automatic email receipts after successful payment
                "receipt_email" => $request->email
            ]);

            $output = [
                'clientSecret' => $paymentIntent->client_secret,
            ];

            echo json_encode($output);
        } catch (Exception $e) {
            return back()->with(['error' => $e->getMessage()]);
        }
    }
}

stripe_checkout.js:

The most significant change here from the Stripe docs was manually passing through the CSRF token in the HTTP headers. Leaving this out results in HTTP 419 errors due to a conflict with Laravel, and it took me much longer than it should have to solve this. Tip: when debugging stuff like this, working your way methodically through each error you see in the browser console is the key to getting things working.

// Replace with your public key, found in your Stripe dashboard
const stripe = Stripe("<YOUR_PUBLIC_KEY>");

const items = [{ id: "xl-tshirt" }];

let elements;

initialize();
checkStatus();

document
    .querySelector("#payment-form")
    .addEventListener("submit", handleSubmit);

async function initialize() {
    const { clientSecret } = await fetch("/charge", {
        method: "POST",
        headers: {
            "X-CSRF-TOKEN": document.querySelector('input[name="_token"]').value,
        },
        body: JSON.stringify({ items }),
    }).then((r) => r.json());

    elements = stripe.elements({ clientSecret });

    const paymentElement = elements.create("payment");
    paymentElement.mount("#payment-element");
}

async function handleSubmit(e) {
    e.preventDefault();
    setLoading(true);

    const { error } = await stripe.confirmPayment({
        elements,
        confirmParams: {
            // Replace with your payment completion page
            return_url: "http://localhost/success",
        },
    });

    if (error.type === "card_error" || error.type === "validation_error") {
        showMessage(error.message);
    } else {
        showMessage("An unexpected error occured.");
    }

    setLoading(false);
}

async function checkStatus() {
    const clientSecret = new URLSearchParams(window.location.search).get(
        "payment_intent_client_secret"
    );

    if (!clientSecret) {
        return;
    }

    const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);

    switch (paymentIntent.status) {
        case "succeeded":
            showMessage("Payment succeeded!");
            break;
        case "processing":
            showMessage("Your payment is processing.");
            break;
        case "requires_payment_method":
            showMessage("Your payment was not successful, please try again.");
            break;
        default:
            showMessage("Something went wrong.");
            break;
    }
}

// ------- UI helpers -------

function showMessage(messageText) {
    const messageContainer = document.querySelector("#payment-message");

    messageContainer.classList.remove("hidden");
    messageContainer.textContent = messageText;

    setTimeout(function () {
        messageContainer.classList.add("hidden");
        messageText.textContent = "";
    }, 4000);
}

function setLoading(isLoading) {
    if (isLoading) {
        document.querySelector("#submit").disabled = true;
        document.querySelector("#spinner").classList.remove("hidden");
        document.querySelector("#button-text").classList.add("hidden");
    } else {
        document.querySelector("#submit").disabled = false;
        document.querySelector("#spinner").classList.add("hidden");
        document.querySelector("#button-text").classList.remove("hidden");
    }
}

stripe_checkout.css  (unchanged from the documentation):

/* Variables */
* {
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  font-size: 16px;
  -webkit-font-smoothing: antialiased;
  display: flex;
  justify-content: center;
  align-content: center;
  height: 100vh;
  width: 100vw;
}

form {
  width: 30vw;
  min-width: 500px;
  align-self: center;
  box-shadow: 0px 0px 0px 0.5px rgba(50, 50, 93, 0.1),
    0px 2px 5px 0px rgba(50, 50, 93, 0.1), 0px 1px 1.5px 0px rgba(0, 0, 0, 0.07);
  border-radius: 7px;
  padding: 40px;
}

.hidden {
  display: none;
}

#payment-message {
  color: rgb(105, 115, 134);
  font-size: 16px;
  line-height: 20px;
  padding-top: 12px;
  text-align: center;
}

#payment-element {
  margin-bottom: 24px;
}

/* Buttons and links */
button {
  background: #5469d4;
  font-family: Arial, sans-serif;
  color: #ffffff;
  border-radius: 4px;
  border: 0;
  padding: 12px 16px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  display: block;
  transition: all 0.2s ease;
  box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07);
  width: 100%;
}
button:hover {
  filter: contrast(115%);
}
button:disabled {
  opacity: 0.5;
  cursor: default;
}

/* spinner/processing state, errors */
.spinner,
.spinner:before,
.spinner:after {
  border-radius: 50%;
}
.spinner {
  color: #ffffff;
  font-size: 22px;
  text-indent: -99999px;
  margin: 0px auto;
  position: relative;
  width: 20px;
  height: 20px;
  box-shadow: inset 0 0 0 2px;
  -webkit-transform: translateZ(0);
  -ms-transform: translateZ(0);
  transform: translateZ(0);
}
.spinner:before,
.spinner:after {
  position: absolute;
  content: "";
}
.spinner:before {
  width: 10.4px;
  height: 20.4px;
  background: #5469d4;
  border-radius: 20.4px 0 0 20.4px;
  top: -0.2px;
  left: -0.2px;
  -webkit-transform-origin: 10.4px 10.2px;
  transform-origin: 10.4px 10.2px;
  -webkit-animation: loading 2s infinite ease 1.5s;
  animation: loading 2s infinite ease 1.5s;
}
.spinner:after {
  width: 10.4px;
  height: 10.2px;
  background: #5469d4;
  border-radius: 0 10.2px 10.2px 0;
  top: -0.1px;
  left: 10.2px;
  -webkit-transform-origin: 0px 10.2px;
  transform-origin: 0px 10.2px;
  -webkit-animation: loading 2s infinite ease;
  animation: loading 2s infinite ease;
}

@-webkit-keyframes loading {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@keyframes loading {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@media only screen and (max-width: 600px) {
  form {
    width: 80vw;
    min-width: initial;
  }
}

payment.blade.view:

<script src="https://js.stripe.com/v3/"></script>
<script src="{{ asset('js/stripe_checkout.js') }}" defer></script>
<link href="{{ asset('css/stripe_checkout.css') }}" rel="stylesheet" />

  ...

<div class="stripe-container">
  {{ csrf_field() }}
  <form id="payment-form">
  <div id="payment-element">
  <!-- Stripe.js injects the Payment Element here-->
  </div>
  <button id="submit">
  <div class="spinner hidden" id="spinner"></div>
  <span id="button-text">Pay £9.99</span>
  </button>
  <div id="payment-message" class="hidden"></div>
  </form>
</div>


问:
Emacs packages not loaded when adding to configuration.nix
I am following the documentation on https://nixos.org/nixos/manual/ to add packages to emacs. I installed emacs with nix-env -i emacs. As it describes I created a file called emacs.nix

```<code>{ pkgs ? import <nixpkgs> {} }:
let
    myEmacs = pkgs.emacs;
    emacsWithPackages = (pkgs.emacsPackagesNgGen myEmacs).emacsWithPackages;
in
    emacsWithPackages (
        epkgs:  (with epkgs.melpaStablePackages; [
            magit
            labburn-theme
            cider
            company
            flycheck
            iedit
            yasnippet
            nix-mode
] )
)
</code>```

And then run nix-build emacs.nix. After that I had a result symlink, as expected. Finally, I confirmed that my packages are working by running emacs with ./result/bin/emacs, run package-initialized and finally checked that the extensions are working.

Now the problem is after I try to add it to my global configuration. As suggested I added the following to my configuration.nix file:

```<code>{
 environment.systemPackages = [
   # [...]
   (import ./emacs.nix { inherit pkgs; })
  ];
}
</code>```

I run nixos-rebuild switch. This procedure doesn't give access to the packages on emacs.

答: I recently ran into this problem. Make sure you remove vanilla "pkgs.emacs" from your environment.systemPackages list. Once that is done it worked as expected for me.</p>

Body:
I am following the documentation on https://nixos.org/nixos/manual/ to add packages to emacs. I installed emacs with nix-env -i emacs. As it describes I created a file called emacs.nix

{ pkgs ? import <nixpkgs> {} }:
let
    myEmacs = pkgs.emacs;
    emacsWithPackages = (pkgs.emacsPackagesNgGen myEmacs).emacsWithPackages;
in
    emacsWithPackages (
        epkgs:  (with epkgs.melpaStablePackages; [
            magit
            labburn-theme
            cider
            company
            flycheck
            iedit
            yasnippet
            nix-mode
] )
)

And then run nix-build emacs.nix. After that I had a result symlink, as expected. Finally, I confirmed that my packages are working by running emacs with ./result/bin/emacs, run package-initialized and finally checked that the extensions are working.

Now the problem is after I try to add it to my global configuration. As suggested I added the following to my configuration.nix file:

{
 environment.systemPackages = [
   # [...]
   (import ./emacs.nix { inherit pkgs; })
  ];
}

I run nixos-rebuild switch. This procedure doesn't give access to the packages on emacs.


问:
Why does NVCC not optimize away ceilf() for literals?
(Followup question for Compile-time ceiling function, for literals, in C?)

Considering the following CUDA function:

```<code>__device__ int foo_f() { return ceilf(1007.1111); }
</code>```

It should be easy to optimize this to produce a device function which simply returns 1008:

```<code>mov.u32         %r1, 1008;
st.param.b32    [func_retval0+0], %r1;
ret;
</code>```

but instead, it compiles (using NVCC 11.5) into the costlier:

```<code>mov.f32          %f1, 0f447C0000;
cvt.rzi.s32.f32  %r1, %f1;
st.param.b32     [func_retval0+0], %r1;
ret;
</code>```

The optimization is also missed if the code is:

```<code>static __device__ int poor_mans_ceilf(float x)
{
    return (int) x + ( ((float)(int) x < x) ? 1 : 0);
}

__device__ int foo_pf() { return poor_mans_ceilf(1007.1111); }
</code>```

which should be even easier for the compiler to "notice" as an optimization opportunity.

So, why is NVCC failing to make the optimization here (while typical C/C++ compilers do take it)? Is there some subtle hitch preventing the optimization in (edit) PTX code? I realize that the ptxas has its own chance of optimizing this away eventually, but this is not a microarchitecture-specific optimization.

See it all on GodBolt.

PS: I know that this might be circumvented by using constexpr.

答:
As you are no doubt fully aware, PTX is a virtual assembly language and isn't run by the GPU. If we compile your code to machine code, we see this:

```<code>$ cat bogogogo.cu
__device__ int foo_f() { return ceilf(1007.1111); }

$ nvcc -dc -Xptxas='-v' bogogogo.cu
ptxas info    : 0 bytes gmem
ptxas info    : Function properties for _Z5foo_fv
    0 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads

$ cuobjdump -sass bogogogo.o

Fatbin elf code:
================
arch = sm_52
code version = [1,7]
producer = <unknown>
host = linux
compile_size = 64bit
compressed

        code for sm_52
                Function : _Z5foo_fv
        .headerflags    @"EF_CUDA_SM52 EF_CUDA_PTX_SM(EF_CUDA_SM52)"
                                                       /* 0x001ffc00ffe007f0 */
        /*0008*/         {         MOV32I R4, 0x3f0 ;  /* 0x010000003f07f004 */
        /*0010*/                   RET         }
                                                       /* 0xe32000000007000f */
        /*0018*/                   BRA 0x18 ;          /* 0xe2400fffff87000f */
                                                       /* 0x001f8000fc0007e0 */
        /*0028*/                   NOP;                /* 0x50b0000000070f00 */
        /*0030*/                   NOP;                /* 0x50b0000000070f00 */
        /*0038*/                   NOP;                /* 0x50b0000000070f00 */
</code>```

You can clearly see that the conversion has been optimized to an immediate constant (0x3f0 = 1008 = ceilf(1007.1111)) in the final assembler output. So the optimization you are demanding is performed, but by the PTX assembler and not by the front end C++ compiler.

If you want to know why the NVIDIA toolchain designers decided to perform the optimization work split between compiler and assembler in this fashion, you would have to ask them directly.

Body:
(Followup question for Compile-time ceiling function, for literals, in C?)

Considering the following CUDA function:

__device__ int foo_f() { return ceilf(1007.1111); }

It should be easy to optimize this to produce a device function which simply returns 1008:

mov.u32         %r1, 1008;
st.param.b32    [func_retval0+0], %r1;
ret;

but instead, it compiles (using NVCC 11.5) into the costlier:

mov.f32          %f1, 0f447C0000;
cvt.rzi.s32.f32  %r1, %f1;
st.param.b32     [func_retval0+0], %r1;
ret;

The optimization is also missed if the code is:

static __device__ int poor_mans_ceilf(float x)
{
    return (int) x + ( ((float)(int) x < x) ? 1 : 0);
}

__device__ int foo_pf() { return poor_mans_ceilf(1007.1111); }

which should be even easier for the compiler to "notice" as an optimization opportunity.

So, why is NVCC failing to make the optimization here (while typical C/C++ compilers do take it)? Is there some subtle hitch preventing the optimization in (edit) PTX code? I realize that the ptxas has its own chance of optimizing this away eventually, but this is not a microarchitecture-specific optimization.

See it all on GodBolt.

PS: I know that this might be circumvented by using constexpr.

Body:
As you are no doubt fully aware, PTX is a virtual assembly language and isn't run by the GPU. If we compile your code to machine code, we see this:

$ cat bogogogo.cu
__device__ int foo_f() { return ceilf(1007.1111); }

$ nvcc -dc -Xptxas='-v' bogogogo.cu
ptxas info    : 0 bytes gmem
ptxas info    : Function properties for _Z5foo_fv
    0 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads

$ cuobjdump -sass bogogogo.o

Fatbin elf code:
================
arch = sm_52
code version = [1,7]
producer = <unknown>
host = linux
compile_size = 64bit
compressed

        code for sm_52
                Function : _Z5foo_fv
        .headerflags    @"EF_CUDA_SM52 EF_CUDA_PTX_SM(EF_CUDA_SM52)"
                                                       /* 0x001ffc00ffe007f0 */
        /*0008*/         {         MOV32I R4, 0x3f0 ;  /* 0x010000003f07f004 */
        /*0010*/                   RET         }
                                                       /* 0xe32000000007000f */
        /*0018*/                   BRA 0x18 ;          /* 0xe2400fffff87000f */
                                                       /* 0x001f8000fc0007e0 */
        /*0028*/                   NOP;                /* 0x50b0000000070f00 */
        /*0030*/                   NOP;                /* 0x50b0000000070f00 */
        /*0038*/                   NOP;                /* 0x50b0000000070f00 */

You can clearly see that the conversion has been optimized to an immediate constant (0x3f0 = 1008 = ceilf(1007.1111)) in the final assembler output. So the optimization you are demanding is performed, but by the PTX assembler and not by the front end C++ compiler.

If you want to know why the NVIDIA toolchain designers decided to perform the optimization work split between compiler and assembler in this fashion, you would have to ask them directly.


问:
Is there a way to make a google query sum multiple columns scalable?
Right now I use the function below to sum the quantities in each column shown in the image below. Occasionally I need to add more columns, and I might even need as much as 50+ but I don't want to have a super long query formula. Is there a way to condense it and write it to be scalable to the amount of columns I require?

Function: =ARRAYFORMULA(IF(ISBLANK(AN4:AN), "", TRANSPOSE(QUERY({VALUE(L4:AM)}, "SELECT sum(Col1), sum(Col2), sum(Col3), sum(Col4), sum(Col5), sum(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), sum(Col16), sum(Col17), sum(Col18), sum(Col19), sum(Col20), sum(Col21), sum(Col22), sum(Col23), sum(Col24), sum(Col25), sum(Col26), sum(Col27), sum(Col28) LABEL sum(Col1) '', sum(Col2) '', sum(Col3) '', sum(Col4) '', sum(Col5) '', sum(Col6) '',  sum(Col7) '', sum(Col8) '', sum(Col9) '', sum(Col10) '', sum(Col11) '', sum(Col12) '', sum(Col13) '', sum(Col14) '', sum(Col15) '',  sum(Col16) '', sum(Col17) '', sum(Col18) '', sum(Col19) '', sum(Col20) '', sum(Col21) '', sum(Col22) '', sum(Col23) '', sum(Col24) '', sum(Col25) '', sum(Col26) '', sum(Col27) '', sum(Col28) ''"))))

Picture below is with the cell selected with function, and the output. You can see the range it sums up the columns for.

答:
yes:

```<code>=INDEX(IF(AN4:AN="",,FLATTEN(QUERY(QUERY({VALUE(INDIRECT("L4:"&ROWS(L4:L)))},
 "select "&JOIN(",", " sum(Col"&SEQUENCE(30)&")")), "offset 1", ))))
</code>```

to add more columns change 30 to something else

circular dependency is from INDIRECT("L4:"&ROWS(L4:L))

you can either go with a flow and enable iterations

or use something like:

```<code>=INDEX(IF(AN4:AN="",,FLATTEN(QUERY(QUERY({VALUE(
 INDIRECT("L4:"&ADDRESS(ROWS(L4:L), COLUMN()-1, 4)))},
 "select "&JOIN(",", " sum(Col"&SEQUENCE(30)&")")), "offset 1", ))))
</code>```

Body:
yes:

=INDEX(IF(AN4:AN="",,FLATTEN(QUERY(QUERY({VALUE(INDIRECT("L4:"&ROWS(L4:L)))},
 "select "&JOIN(",", " sum(Col"&SEQUENCE(30)&")")), "offset 1", ))))

to add more columns change 30 to something else

circular dependency is from INDIRECT("L4:"&ROWS(L4:L))

you can either go with a flow and enable iterations

or use something like:

=INDEX(IF(AN4:AN="",,FLATTEN(QUERY(QUERY({VALUE(
 INDIRECT("L4:"&ADDRESS(ROWS(L4:L), COLUMN()-1, 4)))},
 "select "&JOIN(",", " sum(Col"&SEQUENCE(30)&")")), "offset 1", ))))


问:
identifier "Node" is undefined in Linked list
This is my program to insert linked lists and print them. I'm getting error in void Insert(int x) function where I point temp variable to a new node. The error its showing is identifier "Node" is undefined. What am I supposed to do?

```<code>#include <stdio.h>
#include <stdlib.h>

struct Node{
    int data;
    struct Node *next;
};
struct Node* head;  //global variable head

void Insert(int x){

    struct Node* temp=(Node*)malloc(sizeof(struct Node));
    temp->data=x;
    temp->next=head;  //it is the same as temp->next=NULL
    head=temp;

}

void Print(){
    struct Node* temp = head;
    printf("List is: ");
    while(temp!=NULL){
        printf("%d",temp->data);
        temp=temp->next;
    }
    printf("\n");
}

int main() {
    head = NULL;
    printf("How many numbers?\n");
    int n,i,x;
    scanf("%d",&n);
    for(i=0;i<n;i++){
        scanf("%d",&x);
        Insert(x);
        Print();
    }

    return 0;
}
</code>```

答:
its called forward declaration</p>
```<code>struct Node;
struct Node{
    int data;
    struct Node *next;
};
</code>```

Body:
This is my program to insert linked lists and print them. I'm getting error in void Insert(int x) function where I point temp variable to a new node. The error its showing is identifier "Node" is undefined. What am I supposed to do?

#include <stdio.h>
#include <stdlib.h>

struct Node{
    int data;
    struct Node *next;
};
struct Node* head;  //global variable head

void Insert(int x){

    struct Node* temp=(Node*)malloc(sizeof(struct Node));
    temp->data=x;
    temp->next=head;  //it is the same as temp->next=NULL
    head=temp;

}

void Print(){
    struct Node* temp = head;
    printf("List is: ");
    while(temp!=NULL){
        printf("%d",temp->data);
        temp=temp->next;
    }
    printf("\n");
}

int main() {
    head = NULL;
    printf("How many numbers?\n");
    int n,i,x;
    scanf("%d",&n);
    for(i=0;i<n;i++){
        scanf("%d",&x);
        Insert(x);
        Print();
    }

    return 0;
}

Body:
its called forward declaration

struct Node;
struct Node{
    int data;
    struct Node *next;
};


问:
Convert javascript object to polars dataframe in node.js and populate missing values with null
I'm trying to use nodejs-polars library but have encountered a problem converting a javascript object to a polars dataframe.

Consider the following data for example

const myData = [
    {
        "id": "a",
        "name": "fred",
        "country": "france",
        "age": 30,
        "city": "paris" // there's no "city" property elsewhere in `myData`
    },
    {
        "id": "b",
        "name": "alexandra",
        "country": "usa",
        "age": 40
    },
    {
        "id": "c",
        "name": "george",
        "country": "argentina",
        "age": 50
    }
]
```
<p>So if we do</p>
<pre class="lang-js prettyprint-override"><code>const pl = require("nodejs-polars")

const output = pl.DataFrame(myData)
</code>```

We get the error:

Error: Lengths don't match: Could not create a new DataFrame from Series. The Series have different lengths

Is there no way to create a polars dataframe from object such that it will automatically populate missing values with null?

答:
While this is not currently supported using pl.Dataframe, the desired behavior is supported via pl.readJSON. If you don't mind doing a small amount of pre-processing, this is easily achievable

const ndJSONData = myData
  .map(row => JSON.stringify(row))
  .join("\n")

// -1 will do a full scan, set to a length that best fits your use case.
const df = pl.readJSON(ndJSONData, {"inferSchemaLength": -1})
```
<p><strong>Edit:</strong>
This is now supported with newer versions of polars via <code>readRecords</code>. nested dtypes do have limited support.</p>
<pre class="lang-js prettyprint-override"><code>const df = pl.readRecords(myData, {inferSchemaLength: 10)
</code>```

Body:
I'm trying to use nodejs-polars library but have encountered a problem converting a javascript object to a polars dataframe.

Consider the following data for example

const myData = [
    {
        "id": "a",
        "name": "fred",
        "country": "france",
        "age": 30,
        "city": "paris" // there's no "city" property elsewhere in `myData`
    },
    {
        "id": "b",
        "name": "alexandra",
        "country": "usa",
        "age": 40
    },
    {
        "id": "c",
        "name": "george",
        "country": "argentina",
        "age": 50
    }
]

So if we do

const pl = require("nodejs-polars")

const output = pl.DataFrame(myData)

We get the error:

Error: Lengths don't match: Could not create a new DataFrame from Series. The Series have different lengths

Is there no way to create a polars dataframe from object such that it will automatically populate missing values with null?

Body:
While this is not currently supported using pl.Dataframe, the desired behavior is supported via pl.readJSON. If you don't mind doing a small amount of pre-processing, this is easily achievable

const ndJSONData = myData
  .map(row => JSON.stringify(row))
  .join("\n")

// -1 will do a full scan, set to a length that best fits your use case.
const df = pl.readJSON(ndJSONData, {"inferSchemaLength": -1})

Edit:
This is now supported with newer versions of polars via readRecords. nested dtypes do have limited support.

const df = pl.readRecords(myData, {inferSchemaLength: 10)