问:
Algorithm to find pattern based string match
There are 2 input string r, s. The algorithm checks if there is a match between them:
every char in r matches only one non - empty substring in s.
And different chars in r match different substrings in s.
For example if r = "ABA" and s = "hibiehi". there is a match A = "hi", B = "bie"
But if r = "ABA" and s = "hibie" they don`t match.

答:
You can do this with depth-first search, also called backtracking. We can greedily try to match each letter of the pattern to substrings of the word, and backtrack upon failure. Keep track of the previous matches (and inverse matches) using a hashmap.

The running time of this approach is exponential (in the pattern length, at least), although I haven't analyzed it exactly. You can speed this up with early stopping/pruning the search tree, but it would take a new idea to get a fully polynomial runtime.

Python implementation:

def word_pattern(pattern: str, word: str) -> bool:
    """Given a pattern string, check if 'word' can match pattern.
    'Match' here means a bijection between each character in pattern
    with a nonempty substring in word.
    """

    pattern_len = len(pattern)
    word_len = len(word)

    def dfs(biject_pat_to_word: Dict[str, str],
            already_used_strs: Set[str],
            pattern_index: int,
            word_index: int) -> bool:
        """Greedily try to match each pattern character to the shortest
        possible substring of word, consistent with current bijection.
        Return whether this was possible."""

        if pattern_index == pattern_len:  # Reached pattern end
            return word_index == word_len
        next_letter = pattern[pattern_index]

        # If we've already seen this pattern char, it must match again
        if next_letter in biject_pat_to_word:
            pat_match = biject_pat_to_word[next_letter]
            if word[word_index:word_index + len(pat_match)] != pat_match:
                return False

            word_index += len(pat_match)
            pattern_index += 1

            return dfs(biject_pat_to_word, already_used_strs,
                       pattern_index, word_index)

        curr_str_match = ''
        for amount_to_take in range(1, word_len - word_index + 1):
            curr_str_match += word[word_index + amount_to_take - 1]
            if curr_str_match in already_used_strs:
                continue

            biject_pat_to_word[next_letter] = curr_str_match
            already_used_strs.add(curr_str_match)

            # Try to use this pattern
            if dfs(biject_pat_to_word, already_used_strs,
                   pattern_index=pattern_index + 1,
                   word_index=word_index + amount_to_take):
                return True

            already_used_strs.discard(curr_str_match)

        # If we've set which string we match, unset it for future calls
        if next_letter in biject_pat_to_word:
            del biject_pat_to_word[next_letter]

        return False

    return dfs(biject_pat_to_word={},
               already_used_strs=set(),
               pattern_index=0, word_index=0)
```


来源: stackexchange

问:
How to put Arraylist<object> as parameter in HashMap in Java?
I am doing a Java project - Budget manager, which shows how I spend my money.
For that purpose, I used Hashmap to store the type of purchase with parameters of  String(enum), and Arraylist<Product>. Product is a new class where name and price are to be passed.

How can I put multiple values from ArrayList to the same key in HashMap?

```<code>switch (choice) {
    case 1:
        mapProducts.put(Product.Type.FOOD.name(),//add array);
        break;
    case 2:
        mapProducts.put(Product.Type.CLOTHES.name(), );
        break;
    case 3:
        mapProducts.put(Product.Type.ENTERTAINMENT.name(), );
        break;
    case 4:
        mapProducts.put(Product.Type.OTHER.name(), );
        break;
}
</code>```

import java.util.*;

public class Account {
    private ArrayList<String> listOfPurchases;
    private ArrayList<Double> itemPrice;
    private ArrayList<Product> products;
    private double balance;
    private Scanner input = new Scanner(System.in);
    private Map<String, ArrayList<Product>> mapProducts = new HashMap<>();

    public Account() {
        this.listOfPurchases = new ArrayList<>();
        this.itemPrice = new ArrayList<>();
        this.balance = 0.00d;
    }

    public void mainMenuPrint() {
        System.out.println(
                "Choose your action:\n" +
                        "1) Add income\n" +
                        "2) Add purchase\n" +
                        "3) Show list of purchases\n" +
                        "4) Balance\n" +
                        "0) Exit");
    }

    public void startMenu() {
        Scanner input = new Scanner(System.in);
        boolean isOn = true;
        while (isOn) {
            mainMenuPrint();
            int choice = input.nextInt();
            switch (choice) {
                case 0:
                    System.out.println("Bye!");
                    isOn = false;
                    break;
                case 1:
                    addIncome();
                    break;
                case 2:
                    addPurchase();
                    break;
                case 3:
                    showPurchases();
                    break;
                case 4:
                    showBalance();
                    break;
            }
        }
    }

    public void addIncome() {
        double addMoney = 0.00d;
        System.out.println("Enter income:");
        addMoney = input.nextDouble();
        setBalance(addMoney);
        System.out.println("Income was added!");
        System.out.println("");
    }

    public void addPurchase() {
        System.out.println(
                "Choose the type of purchase\n" +
                        "1) Food\n" +
                        "2) Clothes\n" +
                        "3) Entertainment\n" +
                        "4) Other\n" +
                        "5) Back\n");

        int choice = input.nextInt();
        double price = 0.0d;
        if (choice == 5) {
            startMenu();
        } else {
            System.out.println("Enter purchase name:");
            String item = input.next();
            setListOfPurchases(item);
            System.out.println("Enter its price:");
            try {
                price = input.nextDouble();
                setItemPrice(price);
                balanceSubtractFromPurchasePrice(price);
            } catch (
                InputMismatchException e) {
                System.out.println("Wrong input");
            }
            switch (choice) {
                case 1:
                    mapProducts.put(Product.Type.FOOD.name(),//add array);
                    break;
                case 2:
                    mapProducts.put(Product.Type.CLOTHES.name(), );
                    break;
                case 3:
                    mapProducts.put(Product.Type.ENTERTAINMENT.name(), );
                    break;
                case 4:
                    mapProducts.put(Product.Type.OTHER.name(), );
                    break;
            }
            System.out.println("");
        }
    }

    public void showPurchases() {
        double sum = 0.0d;
        if (mapProducts.size() == 0) {
            System.out.println("The purchase list is empty");
        } else {
            System.out.println(
                    "Choose the type of purchase\n" +
                            "1) Food\n" +
                            "2) Clothes\n" +
                            "3) Entertainment\n" +
                            "4) Other\n" +
                            "5) All\n" +
                            "6) Back\n");

            int choice = input.nextInt();
            for (Map.Entry<String, ArrayList<Product>> entry : mapProducts.entrySet()) {
                System.out.println(entry.getKey());
                System.out.println(mapProducts.get("FOOD").get(0));
            }
            for (int i = 0; i < listOfPurchases.size(); i++) {
                sum += itemPrice.get(i);
            }
            System.out.println("Total sum: $" + sum);
        }
        System.out.println("");
    }

    public void showBalance() {
        System.out.printf("Balance: $%.2f", getBalance());
        System.out.println("");
        System.out.println("");
    }

    public void setBalance(double balanceAmount) {
        this.balance += balanceAmount;
    }

    public void balanceSubtractFromPurchasePrice(double purchasePrice) {
        this.balance -= purchasePrice;
    }

    public double getBalance() {
        if (balance < 0) {
            System.out.println("Balance is negative ");
        }
        return this.balance;
    }

    public void setListOfPurchases(String item) {
        this.listOfPurchases.add(item);
    }

    public ArrayList<String> getListOfPurchases() {
        return listOfPurchases;
    }

    public ArrayList<Double> getItemPrice() {
        return itemPrice;
    }

    public void setItemPrice(double itemPrice) {
        this.itemPrice.add(itemPrice);
    }
}
```
<hr />
```public class Product {
    enum Type {
        FOOD, CLOTHES, ENTERTAINMENT, OTHER;
    }

    private String name;
    private double price;
    private Scanner input = new Scanner(System.in);

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }
}
```

Thanks for the help!

答:
You could do it like this:

ArrayList<Product> products = new ArrayList<>();
// add products to list
mapProducts.put(/*String*/, products);
```

ContentLicense: CC BY-SA 4.0

Body:
I am doing a Java project - Budget manager, which shows how I spend my money.
For that purpose, I used Hashmap to store the type of purchase with parameters of  String(enum), and Arraylist<Product>. Product is a new class where name and price are to be passed.

How can I put multiple values from ArrayList to the same key in HashMap?

switch (choice) {
    case 1:
        mapProducts.put(Product.Type.FOOD.name(),//add array);
        break;
    case 2:
        mapProducts.put(Product.Type.CLOTHES.name(), );
        break;
    case 3:
        mapProducts.put(Product.Type.ENTERTAINMENT.name(), );
        break;
    case 4:
        mapProducts.put(Product.Type.OTHER.name(), );
        break;
}

import java.util.*;

public class Account {
    private ArrayList<String> listOfPurchases;
    private ArrayList<Double> itemPrice;
    private ArrayList<Product> products;
    private double balance;
    private Scanner input = new Scanner(System.in);
    private Map<String, ArrayList<Product>> mapProducts = new HashMap<>();

    public Account() {
        this.listOfPurchases = new ArrayList<>();
        this.itemPrice = new ArrayList<>();
        this.balance = 0.00d;
    }

    public void mainMenuPrint() {
        System.out.println(
                "Choose your action:\n" +
                        "1) Add income\n" +
                        "2) Add purchase\n" +
                        "3) Show list of purchases\n" +
                        "4) Balance\n" +
                        "0) Exit");
    }

    public void startMenu() {
        Scanner input = new Scanner(System.in);
        boolean isOn = true;
        while (isOn) {
            mainMenuPrint();
            int choice = input.nextInt();
            switch (choice) {
                case 0:
                    System.out.println("Bye!");
                    isOn = false;
                    break;
                case 1:
                    addIncome();
                    break;
                case 2:
                    addPurchase();
                    break;
                case 3:
                    showPurchases();
                    break;
                case 4:
                    showBalance();
                    break;
            }
        }
    }

    public void addIncome() {
        double addMoney = 0.00d;
        System.out.println("Enter income:");
        addMoney = input.nextDouble();
        setBalance(addMoney);
        System.out.println("Income was added!");
        System.out.println("");
    }

    public void addPurchase() {
        System.out.println(
                "Choose the type of purchase\n" +
                        "1) Food\n" +
                        "2) Clothes\n" +
                        "3) Entertainment\n" +
                        "4) Other\n" +
                        "5) Back\n");

        int choice = input.nextInt();
        double price = 0.0d;
        if (choice == 5) {
            startMenu();
        } else {
            System.out.println("Enter purchase name:");
            String item = input.next();
            setListOfPurchases(item);
            System.out.println("Enter its price:");
            try {
                price = input.nextDouble();
                setItemPrice(price);
                balanceSubtractFromPurchasePrice(price);
            } catch (
                InputMismatchException e) {
                System.out.println("Wrong input");
            }
            switch (choice) {
                case 1:
                    mapProducts.put(Product.Type.FOOD.name(),//add array);
                    break;
                case 2:
                    mapProducts.put(Product.Type.CLOTHES.name(), );
                    break;
                case 3:
                    mapProducts.put(Product.Type.ENTERTAINMENT.name(), );
                    break;
                case 4:
                    mapProducts.put(Product.Type.OTHER.name(), );
                    break;
            }
            System.out.println("");
        }
    }

    public void showPurchases() {
        double sum = 0.0d;
        if (mapProducts.size() == 0) {
            System.out.println("The purchase list is empty");
        } else {
            System.out.println(
                    "Choose the type of purchase\n" +
                            "1) Food\n" +
                            "2) Clothes\n" +
                            "3) Entertainment\n" +
                            "4) Other\n" +
                            "5) All\n" +
                            "6) Back\n");

            int choice = input.nextInt();
            for (Map.Entry<String, ArrayList<Product>> entry : mapProducts.entrySet()) {
                System.out.println(entry.getKey());
                System.out.println(mapProducts.get("FOOD").get(0));
            }
            for (int i = 0; i < listOfPurchases.size(); i++) {
                sum += itemPrice.get(i);
            }
            System.out.println("Total sum: $" + sum);
        }
        System.out.println("");
    }

    public void showBalance() {
        System.out.printf("Balance: $%.2f", getBalance());
        System.out.println("");
        System.out.println("");
    }

    public void setBalance(double balanceAmount) {
        this.balance += balanceAmount;
    }

    public void balanceSubtractFromPurchasePrice(double purchasePrice) {
        this.balance -= purchasePrice;
    }

    public double getBalance() {
        if (balance < 0) {
            System.out.println("Balance is negative ");
        }
        return this.balance;
    }

    public void setListOfPurchases(String item) {
        this.listOfPurchases.add(item);
    }

    public ArrayList<String> getListOfPurchases() {
        return listOfPurchases;
    }

    public ArrayList<Double> getItemPrice() {
        return itemPrice;
    }

    public void setItemPrice(double itemPrice) {
        this.itemPrice.add(itemPrice);
    }
}

public class Product {
    enum Type {
        FOOD, CLOTHES, ENTERTAINMENT, OTHER;
    }

    private String name;
    private double price;
    private Scanner input = new Scanner(System.in);

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }
}

Thanks for the help!


问:
React useReducer - update array of objects
I  want to use React.useReducer to update state. My state is an array of objects. When update action is triggered, not only value from desired index is updated but all of them. I want to have updated only the value from indicated array index. How can I do that?

After I click button1, I want to get

```<code>[{"amount":null,"kcal":null,"name":null,"isPieceType":false},
{"amount":null,"kcal":null,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":null,"name":null,"isPieceType":false}]
</code>```

instead of

```<code>[{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false}]
</code>```

I tried to copy state as const newState = [...state] and use lodash's cloneDeep. Below, link to jsfiddle with code to reproduce.

https://jsfiddle.net/wtj5eyfh/

答:
Your initial state of ingredientsState has references to the same object called initialIngredient. That caused everything to update when one entry was updated. Even though
const stateToUpdate = [...state]; created a new array again all entries refers to the same object.

Fix

Change the following referenced array entries

```<code>const [ingredientsState, ingredientsDispatch] = React.useReducer(mealReducer, [
    initialIngredient,
    initialIngredient,
    initialIngredient,
    initialIngredient
]);
</code>```

To be an array of copies of initialIngredient object (spread operator simply create clones of the referred object)

```<code>const [ingredientsState, ingredientsDispatch] = React.useReducer(mealReducer, [
    { ...initialIngredient },
    { ...initialIngredient },
    { ...initialIngredient },
    { ...initialIngredient }
]);
</code>```

JS Fiddle

Body:
I  want to use React.useReducer to update state. My state is an array of objects. When update action is triggered, not only value from desired index is updated but all of them. I want to have updated only the value from indicated array index. How can I do that?

After I click button1, I want to get

[{"amount":null,"kcal":null,"name":null,"isPieceType":false},
{"amount":null,"kcal":null,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":null,"name":null,"isPieceType":false}]

instead of

[{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false}]

I tried to copy state as const newState = [...state] and use lodash's cloneDeep. Below, link to jsfiddle with code to reproduce.

https://jsfiddle.net/wtj5eyfh/

Body:
Your initial state of ingredientsState has references to the same object called initialIngredient. That caused everything to update when one entry was updated. Even though
const stateToUpdate = [...state]; created a new array again all entries refers to the same object.

Fix

Change the following referenced array entries

const [ingredientsState, ingredientsDispatch] = React.useReducer(mealReducer, [
    initialIngredient,
    initialIngredient,
    initialIngredient,
    initialIngredient
]);

To be an array of copies of initialIngredient object (spread operator simply create clones of the referred object)

const [ingredientsState, ingredientsDispatch] = React.useReducer(mealReducer, [
    { ...initialIngredient },
    { ...initialIngredient },
    { ...initialIngredient },
    { ...initialIngredient }
]);

JS Fiddle


问:
Android Jetpack Compose - java.lang.NoSuchMethodError: No virtual method setContent(Lkotlin/jvm/functions/Function0;)
I'm getting a java.lang.NoSuchMethodError exception when trying to run setContent{ Composable() }.

Full code:

```<code>class ComposeFragment : Fragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
        ComposeView(requireContext()).apply { setContent { Text("hello") } }

}
</code>```

Full exception:

```<code>java.lang.NoSuchMethodError: No virtual method setContent(Lkotlin/jvm/functions/Function0;)V in class Landroidx/compose/ui/platform/ComposeView; or its super classes (declaration of 'androidx.compose.ui.platform.ComposeView' appears in /data/app/~~3OmVKUoYitZ_S4H81xmyuw==/my.app.package-PAQxAKmtRuhnzp4M2DME8w==/base.apk)
</code>```

Solutions/answers to similar questions suggest adding buildFeatures { compose = true } or kotlinCompilerExtensionVersion, I have already done this but the issue persists.

My full compose Gradle config is as follows:

```<code>kotlinOptions {
    jvmTarget = JavaVersion.VERSION_1_8.toString()
    useIR = true
}

buildFeatures {
    compose = true
}

composeOptions{
    kotlinCompilerExtensionVersion = "1.0.5"
}

implementation( "androidx.activity:activity-compose:1.3.1" )
implementation( "androidx.activity:activity-compose:1.3.1" )
implementation( "androidx.compose.material:material:1.0.5" )
implementation( "androidx.compose.animation:animation:1.0.5" )
implementation( "androidx.compose.ui:ui-tooling:1.0.5" )
implementation( "androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha07" )
androidTestImplementation( "androidx.compose.ui:ui-test-junit4:1.0.5" )
</code>```

答:
Your Compose version is very old and is almost certainly the reason for your problems. Update your project gradle with the following. Make sure to upgrade the plugin versions as well:

```<code>buildscript {
    ext {
        compose_version = '1.1.0-rc01'
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.1.0'
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0'
    }
}
</code>```

Make sure all your dependencies are using the most recent stable version.

You should also update your Kotlin plugin version:

211-1.6.10-release-923-AS7442.40

If you don't know where to set this, click on:

Android Studio > Preferences > Languages & Frameworks > Kotlin

Finally, I strongly recommend that you use Java 11 instead of 8 and set your app's build.gradle to this:

```<code>plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

apply from: 'codeinc.gradle'

android {
    compileSdkVersion 31
    buildToolsVersion "31.0.0"

    defaultConfig {
        applicationId "mydomain.myapp.blablahblah"
        minSdkVersion 21
        targetSdkVersion 31
        versionName "1.0.0"

        versionCode 1
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }
    kotlinOptions {
        jvmTarget = '11'
        useIR = true
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
        kotlinCompilerVersion '1.6.0'
    }
}
</code>```

Body:
I'm getting a java.lang.NoSuchMethodError exception when trying to run setContent{ Composable() }.

Full code:

class ComposeFragment : Fragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
        ComposeView(requireContext()).apply { setContent { Text("hello") } }

}

Full exception:

java.lang.NoSuchMethodError: No virtual method setContent(Lkotlin/jvm/functions/Function0;)V in class Landroidx/compose/ui/platform/ComposeView; or its super classes (declaration of 'androidx.compose.ui.platform.ComposeView' appears in /data/app/~~3OmVKUoYitZ_S4H81xmyuw==/my.app.package-PAQxAKmtRuhnzp4M2DME8w==/base.apk)

Solutions/answers to similar questions suggest adding buildFeatures { compose = true } or kotlinCompilerExtensionVersion, I have already done this but the issue persists.

My full compose Gradle config is as follows:

kotlinOptions {
    jvmTarget = JavaVersion.VERSION_1_8.toString()
    useIR = true
}

buildFeatures {
    compose = true
}

composeOptions{
    kotlinCompilerExtensionVersion = "1.0.5"
}

implementation( "androidx.activity:activity-compose:1.3.1" )
implementation( "androidx.activity:activity-compose:1.3.1" )
implementation( "androidx.compose.material:material:1.0.5" )
implementation( "androidx.compose.animation:animation:1.0.5" )
implementation( "androidx.compose.ui:ui-tooling:1.0.5" )
implementation( "androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha07" )
androidTestImplementation( "androidx.compose.ui:ui-test-junit4:1.0.5" )

Body:
Your Compose version is very old and is almost certainly the reason for your problems. Update your project gradle with the following. Make sure to upgrade the plugin versions as well:

buildscript {
    ext {
        compose_version = '1.1.0-rc01'
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.1.0'
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0'
    }
}

Make sure all your dependencies are using the most recent stable version.

You should also update your Kotlin plugin version:

211-1.6.10-release-923-AS7442.40

If you don't know where to set this, click on:

Android Studio > Preferences > Languages & Frameworks > Kotlin

Finally, I strongly recommend that you use Java 11 instead of 8 and set your app's build.gradle to this:

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

apply from: 'codeinc.gradle'

android {
    compileSdkVersion 31
    buildToolsVersion "31.0.0"

    defaultConfig {
        applicationId "mydomain.myapp.blablahblah"
        minSdkVersion 21
        targetSdkVersion 31
        versionName "1.0.0"

        versionCode 1
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }
    kotlinOptions {
        jvmTarget = '11'
        useIR = true
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
        kotlinCompilerVersion '1.6.0'
    }
}


问:
How to htmlify response text
I am getting a response in text as follows

```<code><span class='text-4xl'>description1</span>
</code>```

And when i print it on screen:

import React,{useContext, useEffect} from 'react';
import blogsContext from '../context/blogsContext';
import { useParams } from 'react-router-dom';

export const Blog_read = (props) => {
    const context = useContext(blogsContext)
    const slug = useParams().slug
    const {read_blog,readblog} = context
    useEffect(()=>{read_blog(slug)},[readblog])
    props.changetitle(readblog.title)
    const title = readblog.title
    const description = readblog.description
  return (
      <>
    {title}
    {description}
      </>
  );
};```

Then it prints raw text as shown in

How to render it in html form

ThankYou

答:
Here is a function for you to decode HTML entities, hope it helps:

```<code>function htmlDecode(input) {
  var escaped = new DOMParser().parseFromString(input, "text/html");
  return escaped.documentElement.textContent;
}
</code>```

EDIT: This also works, but may risk XSS, make sure the HTML is clean before decoding:

```<code>function htmlDecode(input) {
    var escaped = document.createElement("textarea");
    escaped.innerHTML = input;
    return escaped.value;
}
</code>```

Title: How to htmlify response text

Body:
I am getting a response in text as follows

description1

And when i print it on screen:

import React,{useContext, useEffect} from 'react';
import blogsContext from '../context/blogsContext';
import { useParams } from 'react-router-dom';

export const Blog_read = (props) => {
    const context = useContext(blogsContext)
    const slug = useParams().slug
    const {read_blog,readblog} = context
    useEffect(()=>{read_blog(slug)},[readblog])
    props.changetitle(readblog.title)
    const title = readblog.title
    const description = readblog.description
  return (
      <>
    {title}
    {description}
      </>
  );
};

Then it prints raw text as shown in

How to render it in html form

ThankYou

Body:
Here is a function for you to decode HTML entities, hope it helps:

function htmlDecode(input) {
  var escaped = new DOMParser().parseFromString(input, "text/html");
  return escaped.documentElement.textContent;
}

EDIT: This also works, but may risk XSS, make sure the HTML is clean before decoding:

function htmlDecode(input) {
    var escaped = document.createElement("textarea");
    escaped.innerHTML = input;
    return escaped.value;
}


问:
change words at particular location in javascript string

var str = "Hello world";

str.charAt(2)="P"//instead of l i am assigning the value P

console.log(str)```

I want to replace some Text from the string by checking some coditions but i am getting error i also tried replace function but that return nothing does no changes in the string

答:
You need to make an array out of the string to replace by index.
The following should do the trick.</p>
```<code>const changeChar = (str, newValue, index) => {
  let splitted = str.split("");
  splitted[index] = newValue;
  return splitted.join("");
}
</code>```

Body:
var str = "Hello world";

str.charAt(2)="P"//instead of l i am assigning the value P

console.log(str)

I want to replace some Text from the string by checking some coditions but i am getting error i also tried replace function but that return nothing does no changes in the string

Body:
You need to make an array out of the string to replace by index.
The following should do the trick.

const changeChar = (str, newValue, index) => {
  let splitted = str.split("");
  splitted[index] = newValue;
  return splitted.join("");
}


问:
Bad Access at UIApplicationMain() if Keyboard's Correction is set to Default or Yes
In my project, there is a simple table view and search controller. Everything loads and works fine, until I type into the text field. It then crashes at UIApplicationMain(), with a stack track of several UIKeyboardInputImpl methods. On a whim, I decided to mess with the settings in IB for the Search Bar itself—turns out, setting the option for Correction to Default or Yes causes the crash. I've never seen this happen before, and I'm tempted to call this a bug in the SDK. Can anyone confirm or provide more insight?

Xcode 4 Project:
http://db.tt/V6POWik

答: Bug in the SDK…not much that I can do.</p>

ContentLicense: CC BY-SA 3.0

Body: Bug in the SDK…not much that I can do.


问:
Which is the best way to read_dir a network path in Rust?
i can't read a path in my network using this code.
Maybe fs::read_dir work only for local dirs.</p>
```<code>use std::fs;

fn main() {

    let paths = fs::read_dir("\\nbsvr01").unwrap();
    for path in paths {
        println!("Name: {}", path.unwrap().path().display())
    }

}
</code>```

答:
As @rodrigo said, you can use r"\\nbsvr01", which is more straightforward and easy to unserstand.

If you are not familiar with this, check this out:)

Body:
i can't read a path in my network using this code.
Maybe fs::read_dir work only for local dirs.

use std::fs;

fn main() {

    let paths = fs::read_dir("\\nbsvr01").unwrap();
    for path in paths {
        println!("Name: {}", path.unwrap().path().display())
    }

}


问:
Parameters are not passed in the POST request
I'm trying to pass data in POST request. In swagger, which runs automatically, they are passed, if you use POSTMAN or other client parameters are not passed.
Thank you in advance for your help</p>
```<code>[ApiController]
    public class UsersController
    {
        DatabaseContext context = new DatabaseContext();

        [Route("loginUser")]
        [HttpPost]
        public string LoginUser(string email, string password)
        {
            # some logic
        }
    }
</code>```

答:
You can convert your parameters for your API to a strongly defined Model:

```<code>public class MyData
{
  public string email {get;set;}
  public string password {get;set;}
}
</code>```

And then you can use the [FromBody] attribute to get your values in your API method:

```<code>[ApiController]
public class UsersController
{
    DatabaseContext context = new DatabaseContext();

    [Route("loginUser")]
    [HttpPost]
    public string LoginUser([FromBody]MyData data)
    {
        string email=data.email;
        string password=data.password;
        # some logic
    }
}
</code>```

Body:
I'm trying to pass data in POST request. In swagger, which runs automatically, they are passed, if you use POSTMAN or other client parameters are not passed.
Thank you in advance for your help

[ApiController]
    public class UsersController
    {
        DatabaseContext context = new DatabaseContext();

        [Route("loginUser")]
        [HttpPost]
        public string LoginUser(string email, string password)
        {
            # some logic
        }
    }

Body:
You can convert your parameters for your API to a strongly defined Model:

public class MyData
{
  public string email {get;set;}
  public string password {get;set;}
}

And then you can use the [FromBody] attribute to get your values in your API method:

[ApiController]
public class UsersController
{
    DatabaseContext context = new DatabaseContext();

    [Route("loginUser")]
    [HttpPost]
    public string LoginUser([FromBody]MyData data)
    {
        string email=data.email;
        string password=data.password;
        # some logic
    }
}


问:
Displaying the Error Messages in Laravel after being Redirected from controller
How can I display the validation message in the view that is being redirected in Laravel ?

Here is my function in a Controller

```<code>public function registeruser()
{
    $firstname = Input::get('firstname');
    $lastname = Input::get('lastname');
    $data  =  Input::except(array('_token')) ;
    $rule  =  array(
                'firstname'       => 'required',
                'lastname'         => 'required',
                   ) ;
    $validator = Validator::make($data,$rule);
    if ($validator->fails())
    {
    $messages = $validator->messages();
    return Redirect::to('/')->with('message', 'Register Failed');
    }
    else
    {
    DB::insert('insert into user (firstname, lastname) values (?, ?)',
                                array($firstname, $lastname));
    return Redirect::to('/')->with('message', 'Register Success');
    }
    }
</code>```

I know the below given code is a bad try, But how can I fix it and what am
 I missing

```<code>@if($errors->has())
    @foreach ($errors->all() as $error)
        <div>{{ $error }}</div>
    @endforeach
@endif
</code>```

Update : And how do I display the error messages near to the particular fields

答:
You can use like below to print with html tags :</p>
```<code>@if($errors->any())
    {!! implode('', $errors->all('<div>:message</div>')) !!}
@endif
</code>```

Body:
How can I display the validation message in the view that is being redirected in Laravel ?

Here is my function in a Controller

public function registeruser()
{
    $firstname = Input::get('firstname');
    $lastname = Input::get('lastname');
    $data  =  Input::except(array('_token')) ;
    $rule  =  array(
                'firstname'       => 'required',
                'lastname'         => 'required',
                   ) ;
    $validator = Validator::make($data,$rule);
    if ($validator->fails())
    {
    $messages = $validator->messages();
    return Redirect::to('/')->with('message', 'Register Failed');
    }
    else
    {
    DB::insert('insert into user (firstname, lastname) values (?, ?)',
                                array($firstname, $lastname));
    return Redirect::to('/')->with('message', 'Register Success');
    }
    }

I know the below given code is a bad try, But how can I fix it and what am
 I missing

@if($errors->has())
    @foreach ($errors->all() as $error)

{{ $error }}

    @endforeach
@endif

Update : And how do I display the error messages near to the particular fields

Body:
You can use like below to print with html tags :

@if($errors->any())
    {!! implode('', $errors->all('<div>:message</div>')) !!}
@endif


问:
When is it the right time to use C# class library (.dll)?
I'm a programmer who has never really used .dll files.
Of cause, when I need 3rd party software, such as a graphics library, a library to help me create graphs etc. I do add the references/ddl files to my program and use them in my code.

Also, it seems like you can use .dll for a lot of different things, so I'd like the topic to concentrate on C#.

Right now I am working on a sanitizing library(?) (I think that is the correct term), which will be full of relevant methods that can sanitize variables in all sorts of different ways.

What I want to know is:

would there be any advantage to:

1) Write the methods to class library -> compile/build it -> add the library as a reference to the program - which would need to sanitize some variables ?

Or would it be exactly the same if I where to:

2) Create a new SanitizeClass in the program -> add all the sanitize methods -> call the methods from the SanitizeClass in the different classes in the program that needs to sanitize variables

In general, I also want to know when it is an advantage to use compiled class libraries.
I'm thinking of speed, security, all of it.

Could anyone enlightenment me? :)

答: I think the easiest way is to add SanitizeLibrary project as Library Class project to your solution and reference this project in your application. If you find it useful you may then extract library from current project and reference it as dll in your other projects.</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: empi


问:
Where is the mistake in my HTTP form login program?
I am trying to view a protected html page by posting the login values with the http request... The site is sportguru.co.uk and I cannot seem to correctly post the password!? When I run this code (with my actual login details):

```<code>/**
 *  $Id: LoginByHttpPost.java 101 2010-03-13 23:52:31Z oneyour $
 *
 * This is an accompanying program for the article
 * http://www.1your.com/drupal/LoginToWebsiteByHTTPPOSTCodeListing
 *
 * Copyright (c) 2009 - 2010 www.1your.com.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of www.1your.com nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

import java.net.*;
import java.io.*;

public class LoginByHttpPost
{
    private static final String POST_CONTENT_TYPE = "application/x-www-form-urlencoded";
    private static final String LOGIN_ACTION_NAME = "Log in";
    private static final String LOGIN_USER_NAME_PARAMETER_NAME = "email";
    private static final String LOGIN_PASSWORD_PARAMETER_NAME = "password";

    private static final String LOGIN_USER_NAME = "emailAddress";
    private static final String LOGIN_PASSWORD = "password";

    private static final String TARGET_URL = "http://www.sportguru.co.uk/login_form.asp";

    public static void main (String args[])
    {
        System.out.println("About to run the 'LogInByHttpPost' downloaded from www.1Your.com");
        LoginByHttpPost httpUrlBasicAuthentication = new LoginByHttpPost();
        httpUrlBasicAuthentication.httpPostLogin();
    }

    /**
     * The single public method of this class that
     * 1. Prepares a login message
     * 2. Makes the HTTP POST to the target URL
     * 3. Reads and returns the response
     *
     * @throws IOException
     * Any problems while doing the above.
     *
     */
    public void httpPostLogin ()
    {
        try
        {
            // Prepare the content to be written
            // throws UnsupportedEncodingException
            String urlEncodedContent = preparePostContent(LOGIN_USER_NAME, LOGIN_PASSWORD);

            HttpURLConnection urlConnection = doHttpPost(TARGET_URL, urlEncodedContent);

            String response = readResponse(urlConnection);

            System.out.println("Successfully made the HTPP POST.");
            System.out.println("Recevied response is: '/n" + response + "'");

            System.out.println("/n Hope you found the article and this sample program useful./nPlease leave your feed back at www.1your.com and support us.");
        }
        catch(IOException ioException)
        {
            System.out.println("Problems encounterd.");
        }
    }

    /**
     * Using the given username and password, and using the static string variables, prepare
     * the login message. Note that the username and password will encoded to the
     * UTF-8 standard.
     *
     * @param loginUserName
     * The user name for login
     *
     * @param loginPassword
     * The password for login
     *
     * @return
     * The complete login message that can be HTTP Posted
     *
     * @throws UnsupportedEncodingException
     * Any problems during URL encoding
     */
    private String preparePostContent(String loginUserName, String loginPassword) throws UnsupportedEncodingException
    {
        // Encode the user name and password to UTF-8 encoding standard
        // throws UnsupportedEncodingException
        String encodedLoginUserName = URLEncoder.encode(loginUserName, "UTF-8");
        String encodedLoginPassword = URLEncoder.encode(loginPassword, "UTF-8");

        String content = "Log in=" + LOGIN_ACTION_NAME +" &" + LOGIN_USER_NAME_PARAMETER_NAME +"="
        + encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword;

        return content;

    }

    /**
     * Makes a HTTP POST to the target URL by using an HttpURLConnection.
     *
     * @param targetUrl
     * The URL to which the HTTP POST is made.
     *
     * @param content
     * The contents which will be POSTed to the target URL.
     *
     * @return
     * The open URLConnection which can be used to read any response.
     *
     * @throws IOException
     */
    public HttpURLConnection doHttpPost(String targetUrl, String content) throws IOException
    {
        HttpURLConnection urlConnection = null;
        DataOutputStream dataOutputStream = null;
        try
        {
            // Open a connection to the target URL
            // throws IOException
            urlConnection = (HttpURLConnection)(new URL(targetUrl).openConnection());

            // Specifying that we intend to use this connection for input
            urlConnection.setDoInput(true);

            // Specifying that we intend to use this connection for output
            urlConnection.setDoOutput(true);

            // Specifying the content type of our post
            urlConnection.setRequestProperty("Content-Type", POST_CONTENT_TYPE);

            // Specifying the method of HTTP request which is POST
            // throws ProtocolException
            urlConnection.setRequestMethod("POST");

            // Prepare an output stream for writing data to the HTTP connection
            // throws IOException
            dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());

            // throws IOException
            dataOutputStream.writeBytes(content);
            dataOutputStream.flush();
            dataOutputStream.close();

            return urlConnection;
        }
        catch(IOException ioException)
        {
            System.out.println("I/O problems while trying to do a HTTP post.");
            ioException.printStackTrace();

            // Good practice: clean up the connections and streams
            // to free up any resources if possible
            if (dataOutputStream != null)
            {
                try
                {
                    dataOutputStream.close();
                }
                catch(Throwable ignore)
                {
                    // Cannot do anything about problems while
                    // trying to clean up. Just ignore
                }
            }
            if (urlConnection != null)
            {
                urlConnection.disconnect();
            }

            // throw the exception so that the caller is aware that
            // there was some problems
            throw ioException;
        }
    }

    /**
     * Read response from the URL connection
     *
     * @param urlConnection
     * The URLConncetion from which the response will be read
     *
     * @return
     * The response read from the URLConnection
     *
     * @throws IOException
     * When problems encountered during reading the response from the
     * URLConnection.
     */
    private String readResponse(HttpURLConnection urlConnection) throws IOException
    {

        BufferedReader bufferedReader = null;
        try
        {
            // Prepare a reader to read the response from the URLConnection
            // throws IOException
            bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String responeLine;

            // Good Practice: Use StringBuilder in this case
            StringBuilder response = new StringBuilder();

            // Read untill there is nothing left in the stream
            // throws IOException
            while ((responeLine = bufferedReader.readLine()) != null)
            {
                response.append('\n'+responeLine);
            }

            return response.toString();
        }
        catch(IOException ioException)
        {
            System.out.println("Problems while reading the response");
            ioException.printStackTrace();

            // throw the exception so that the caller is aware that
            // there was some problems
            throw ioException;

        }
        finally
        {
            // Good practice: clean up the connections and streams
            // to free up any resources if possible
            if (bufferedReader != null)
            {
                try
                {
                    // throws IOException
                    bufferedReader.close();
                }
                catch(Throwable ignore)
                {
                    // Cannot do much with exceptions doing clean up
                    // Ignoring all exceptions
                }
            }

        }
    }
}
</code>```

The HTML page I receive contains this form:

```<code><form name="loginPage" method="post" action="login.asp" onSubmit="return submitForm()" style="margin:0px;padding:0px">
    <input type="hidden" name="pageReferer" value="" />
    <input type="hidden" name="logintype" value="page" />
    <input type="hidden" name="pagePoolCode" value="" />

<div style="border:2px solid #666666;width:486px">
    <div style="background-image:url(home/images/structure/header_login.gif);height:28px;"></div>
    <div style="padding:7px;">
        <table cellspacing="2" cellspacing="0">
        <tr>
            <td align="right" width="62">Email:</td>
            <td><input type="text" name="pageEmail" value="emailAddress" size="32"></td>
        </tr>
        <tr>
            <td align="right">Password:</td>
            <td><input type="password" name="pagePassword" size="32"></td>
        </tr>
        <tr>
            <td align="right"></td>
            <td class="small"><a href="forgotten.asp"><strong>Forgotten</strong> your email address or password? Or has your<br /><strong>email changed</strong> since last you used the site? <strong>Click here</strong> »</a></td>
        </tr>
        <tr>
            <td> </td>
            <td style="padding-top:7px;"><input type="image" src="/home/images/buttons/login.gif" value="Log in"></td>
        </tr>

    </table>
    </div>
</div>
</form>
</code>```

As can be seen the email address is posted into the form correctly. But I wish to view the source of the html page after the post... Do I need cookies or something?

答:
```<code>String content = "Log in=" + LOGIN_ACTION_NAME +" &" + LOGIN_USER_NAME_PARAMETER_NAME +"="
   + encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword;
</code>```

Are you that there really should be a space in Log in?

Maybe Log%20in or Log+in would be better here. (As I don't see your complete form, I can only guess here.)

So, we have to send these form fields:

pageReferer (empty)

logintype (page)

pagePoolCode (empty)

pageEmail  (an email address?)

pagePassword (a password?)

There also is a <input type="image" src="/home/images/buttons/login.gif" value="Log in"> - but this has no name attribute, so it can't be sent. So, my first guess would be simply omitting this "Log in=" part in your content string.

```<code>String content = LOGIN_USER_NAME_PARAMETER_NAME + "="
   + encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword;
</code>```

If this doesn't work, add the first three fields also to the string:

```<code>String content = "pageReferer=&loginType=page&pagePoolCode=&" +
    LOGIN_USER_NAME_PARAMETER_NAME + "="
   + encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword;
</code>```

Body:
I am trying to view a protected html page by posting the login values with the http request... The site is sportguru.co.uk and I cannot seem to correctly post the password!? When I run this code (with my actual login details):

/**
 *  $Id: LoginByHttpPost.java 101 2010-03-13 23:52:31Z oneyour $
 *
 * This is an accompanying program for the article
 * http://www.1your.com/drupal/LoginToWebsiteByHTTPPOSTCodeListing
 *
 * Copyright (c) 2009 - 2010 www.1your.com.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of www.1your.com nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

import java.net.*;
import java.io.*;

public class LoginByHttpPost
{
    private static final String POST_CONTENT_TYPE = "application/x-www-form-urlencoded";
    private static final String LOGIN_ACTION_NAME = "Log in";
    private static final String LOGIN_USER_NAME_PARAMETER_NAME = "email";
    private static final String LOGIN_PASSWORD_PARAMETER_NAME = "password";

    private static final String LOGIN_USER_NAME = "emailAddress";
    private static final String LOGIN_PASSWORD = "password";

    private static final String TARGET_URL = "http://www.sportguru.co.uk/login_form.asp";

    public static void main (String args[])
    {
        System.out.println("About to run the 'LogInByHttpPost' downloaded from www.1Your.com");
        LoginByHttpPost httpUrlBasicAuthentication = new LoginByHttpPost();
        httpUrlBasicAuthentication.httpPostLogin();
    }

    /**
     * The single public method of this class that
     * 1. Prepares a login message
     * 2. Makes the HTTP POST to the target URL
     * 3. Reads and returns the response
     *
     * @throws IOException
     * Any problems while doing the above.
     *
     */
    public void httpPostLogin ()
    {
        try
        {
            // Prepare the content to be written
            // throws UnsupportedEncodingException
            String urlEncodedContent = preparePostContent(LOGIN_USER_NAME, LOGIN_PASSWORD);

            HttpURLConnection urlConnection = doHttpPost(TARGET_URL, urlEncodedContent);

            String response = readResponse(urlConnection);

            System.out.println("Successfully made the HTPP POST.");
            System.out.println("Recevied response is: '/n" + response + "'");

            System.out.println("/n Hope you found the article and this sample program useful./nPlease leave your feed back at www.1your.com and support us.");
        }
        catch(IOException ioException)
        {
            System.out.println("Problems encounterd.");
        }
    }

    /**
     * Using the given username and password, and using the static string variables, prepare
     * the login message. Note that the username and password will encoded to the
     * UTF-8 standard.
     *
     * @param loginUserName
     * The user name for login
     *
     * @param loginPassword
     * The password for login
     *
     * @return
     * The complete login message that can be HTTP Posted
     *
     * @throws UnsupportedEncodingException
     * Any problems during URL encoding
     */
    private String preparePostContent(String loginUserName, String loginPassword) throws UnsupportedEncodingException
    {
        // Encode the user name and password to UTF-8 encoding standard
        // throws UnsupportedEncodingException
        String encodedLoginUserName = URLEncoder.encode(loginUserName, "UTF-8");
        String encodedLoginPassword = URLEncoder.encode(loginPassword, "UTF-8");

        String content = "Log in=" + LOGIN_ACTION_NAME +" &" + LOGIN_USER_NAME_PARAMETER_NAME +"="
        + encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword;

        return content;

    }

    /**
     * Makes a HTTP POST to the target URL by using an HttpURLConnection.
     *
     * @param targetUrl
     * The URL to which the HTTP POST is made.
     *
     * @param content
     * The contents which will be POSTed to the target URL.
     *
     * @return
     * The open URLConnection which can be used to read any response.
     *
     * @throws IOException
     */
    public HttpURLConnection doHttpPost(String targetUrl, String content) throws IOException
    {
        HttpURLConnection urlConnection = null;
        DataOutputStream dataOutputStream = null;
        try
        {
            // Open a connection to the target URL
            // throws IOException
            urlConnection = (HttpURLConnection)(new URL(targetUrl).openConnection());

            // Specifying that we intend to use this connection for input
            urlConnection.setDoInput(true);

            // Specifying that we intend to use this connection for output
            urlConnection.setDoOutput(true);

            // Specifying the content type of our post
            urlConnection.setRequestProperty("Content-Type", POST_CONTENT_TYPE);

            // Specifying the method of HTTP request which is POST
            // throws ProtocolException
            urlConnection.setRequestMethod("POST");

            // Prepare an output stream for writing data to the HTTP connection
            // throws IOException
            dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());

            // throws IOException
            dataOutputStream.writeBytes(content);
            dataOutputStream.flush();
            dataOutputStream.close();

            return urlConnection;
        }
        catch(IOException ioException)
        {
            System.out.println("I/O problems while trying to do a HTTP post.");
            ioException.printStackTrace();

            // Good practice: clean up the connections and streams
            // to free up any resources if possible
            if (dataOutputStream != null)
            {
                try
                {
                    dataOutputStream.close();
                }
                catch(Throwable ignore)
                {
                    // Cannot do anything about problems while
                    // trying to clean up. Just ignore
                }
            }
            if (urlConnection != null)
            {
                urlConnection.disconnect();
            }

            // throw the exception so that the caller is aware that
            // there was some problems
            throw ioException;
        }
    }

    /**
     * Read response from the URL connection
     *
     * @param urlConnection
     * The URLConncetion from which the response will be read
     *
     * @return
     * The response read from the URLConnection
     *
     * @throws IOException
     * When problems encountered during reading the response from the
     * URLConnection.
     */
    private String readResponse(HttpURLConnection urlConnection) throws IOException
    {

        BufferedReader bufferedReader = null;
        try
        {
            // Prepare a reader to read the response from the URLConnection
            // throws IOException
            bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String responeLine;

            // Good Practice: Use StringBuilder in this case
            StringBuilder response = new StringBuilder();

            // Read untill there is nothing left in the stream
            // throws IOException
            while ((responeLine = bufferedReader.readLine()) != null)
            {
                response.append('\n'+responeLine);
            }

            return response.toString();
        }
        catch(IOException ioException)
        {
            System.out.println("Problems while reading the response");
            ioException.printStackTrace();

            // throw the exception so that the caller is aware that
            // there was some problems
            throw ioException;

        }
        finally
        {
            // Good practice: clean up the connections and streams
            // to free up any resources if possible
            if (bufferedReader != null)
            {
                try
                {
                    // throws IOException
                    bufferedReader.close();
                }
                catch(Throwable ignore)
                {
                    // Cannot do much with exceptions doing clean up
                    // Ignoring all exceptions
                }
            }

        }
    }
}

The HTML page I receive contains this form:

<form name="loginPage" method="post" action="login.asp" onSubmit="return submitForm()" style="margin:0px;padding:0px">
    <input type="hidden" name="pageReferer" value="" />
    <input type="hidden" name="logintype" value="page" />
    <input type="hidden" name="pagePoolCode" value="" />

            Email:
            <input type="text" name="pageEmail" value="emailAddress" size="32">

            Password:
            <input type="password" name="pagePassword" size="32">

            Forgotten your email address or password? Or has your
email changed since last you used the site? Click here »

            <input type="image" src="/home/images/buttons/login.gif" value="Log in">

</form>

As can be seen the email address is posted into the form correctly. But I wish to view the source of the html page after the post... Do I need cookies or something?

Body:
String content = "Log in=" + LOGIN_ACTION_NAME +" &" + LOGIN_USER_NAME_PARAMETER_NAME +"="
   + encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword;

Are you that there really should be a space in Log in?

Maybe Log%20in or Log+in would be better here. (As I don't see your complete form, I can only guess here.)

So, we have to send these form fields:

pageReferer (empty)

logintype (page)

pagePoolCode (empty)

pageEmail  (an email address?)

pagePassword (a password?)

There also is a <input type="image" src="/home/images/buttons/login.gif" value="Log in"> - but this has no name attribute, so it can't be sent. So, my first guess would be simply omitting this "Log in=" part in your content string.

String content = LOGIN_USER_NAME_PARAMETER_NAME + "="
   + encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword;

If this doesn't work, add the first three fields also to the string:

String content = "pageReferer=&loginType=page&pagePoolCode=&" +
    LOGIN_USER_NAME_PARAMETER_NAME + "="
   + encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword;


问:
Typescript alternative to Java <? super SomeType>
Have a specific use-case where one of the generic params that are used to instantiate my class should be a superclass of another class, in java this is easily doable via <? super SomeType>

What would the alternative in typescript be?

答: <E extends Partial<SomeType>>  is the closest we can get with typescript


问:
Binance API doesn't display EUR price pair
Recently trying to figure it out why "OOKIDAO" doesn't show up as pair when calling binance api url.

For example BTC EUR price or other crypto shows up this URL:

https://api.binance.com/api/v3/ticker/price?symbol=BTCEUR

But I need OOKIDAO to show with EUR pair so this URL doesn't work: https://api.binance.com/api/v3/ticker/price?symbol=OOKIEUR

I tried also OOKIDAO or '_' but no success.
However pairing with USDT works but I need EUR.

thanks for advice since I didnt found it at all in github docs.

答:
Binance doesn't not have the pair OOKI / EUR that's why you can't find the working API.
The only pairs listed on Binance for OOKI are USDT, BUSD, BNB, ETH.</p>


问:
How merge a collection of associative arrays?
Consider

```<code>$c = collect([['name' => 'Joe'], ['score' => 98]])
$c->flatten(1)
</code>```

which gives

```<code>=> Illuminate\Support\Collection {#1153
     all: [
       "Joe",
       98,
     ],
   }
</code>```

Which is not what I expected. I would expect it to combine them to get the following:

```<code>[
    'name' => "Joe",
    'score' =>   98,
]
</code>```

How can I do that? Preferably with a collection method.

答:
Collection::collapse() might be the method you're looking for:

```<code>$c = collect([['name' => 'Joe'], ['score' => 98]]);
$c->collapse();
</code>```

which results in an array like this:

```<code>[
  "name" => "Joe",
  "score" => 98,
]
</code>```

Body:
Consider

$c = collect([['name' => 'Joe'], ['score' => 98]])
$c->flatten(1)

which gives

=> Illuminate\Support\Collection {#1153
     all: [
       "Joe",
       98,
     ],
   }

Which is not what I expected. I would expect it to combine them to get the following:

[
    'name' => "Joe",
    'score' =>   98,
]

How can I do that? Preferably with a collection method.

Body:
Collection::collapse() might be the method you're looking for:

$c = collect([['name' => 'Joe'], ['score' => 98]]);
$c->collapse();

which results in an array like this:

[
  "name" => "Joe",
  "score" => 98,
]


问:
C# Delegates to methods with different optional parameters
I know that I can declare delegates that have default constant parameters such as:

```<code>delegate void MyDelegate(int x, int y = 5);
</code>```

and then call it anywhere with any method that matches the signature.

Ok, I've got LOTS of methods declared like this way:

```<code>public Something FirstMethod(float val = 10, int skip = 0){ ... return sth; }
public Something SecondMethod(float val = 20, int skip = 0){ ... return sth; }
public Something ThirdMethod(float val = 5, int skip = 0){ ... return sth; }
</code>```

... this list goes up all the way down, anyway, they all have that signature structure. The point here is that, they all have floating point argument, that defaults to something different.

Then, I want to create a delegate that will point to one of these methods:

```<code>delegate Something ProblematicDelegateType(<<WHAT WILL GO HERE>>);
ProblematicDelegateType myFunc;
if(someValue == someParameter){
    myFunc = FirstMethod;
}else if(...){
    myFunc = SecondMethod;
}else...
...
}

myFunc();
myFunc(skip:100);
</code>```

I want to be able to call myFunc both parameterless or with the skip parameter. In this part of code, the first parameter, val, is NOT used. (they are used elsewhere).

What will go to the delegate's argument list? I want to preserve that method's default val argument, whatever it is.

答:
Use a lambda to bind the value that you want.  Default values are effectively overloads that have bound the value you desire to the function parameter.  Since you have the various if's separating out the functions, just pass around a delegate to a function that only takes a integer.

In other words,

```<code>delegate Something ProblematicDelegateType(int skip = 0)

//...

ProblematicDelegateType myDelegate;
if (someCondition)
  myDelegate = (_1) => FirstMethod(10, _1);
else if (someOtherCondition)
  myDelegate = (_1) => SecondMethod(20, _1);
</code>```

and so on..

Body:
I know that I can declare delegates that have default constant parameters such as:

delegate void MyDelegate(int x, int y = 5);

and then call it anywhere with any method that matches the signature.

Ok, I've got LOTS of methods declared like this way:

public Something FirstMethod(float val = 10, int skip = 0){ ... return sth; }
public Something SecondMethod(float val = 20, int skip = 0){ ... return sth; }
public Something ThirdMethod(float val = 5, int skip = 0){ ... return sth; }

... this list goes up all the way down, anyway, they all have that signature structure. The point here is that, they all have floating point argument, that defaults to something different.

Then, I want to create a delegate that will point to one of these methods:

delegate Something ProblematicDelegateType(<<WHAT WILL GO HERE>>);
ProblematicDelegateType myFunc;
if(someValue == someParameter){
    myFunc = FirstMethod;
}else if(...){
    myFunc = SecondMethod;
}else...
...
}

myFunc();
myFunc(skip:100);

I want to be able to call myFunc both parameterless or with the skip parameter. In this part of code, the first parameter, val, is NOT used. (they are used elsewhere).

What will go to the delegate's argument list? I want to preserve that method's default val argument, whatever it is.

Body:
Use a lambda to bind the value that you want.  Default values are effectively overloads that have bound the value you desire to the function parameter.  Since you have the various if's separating out the functions, just pass around a delegate to a function that only takes a integer.

In other words,

delegate Something ProblematicDelegateType(int skip = 0)

//...

ProblematicDelegateType myDelegate;
if (someCondition)
  myDelegate = (_1) => FirstMethod(10, _1);
else if (someOtherCondition)
  myDelegate = (_1) => SecondMethod(20, _1);

and so on..


问:
X Unique Randomize Numbers
i need a little bit help.
Is it possible to fill a list with random numbers and to check this list before each loop to see if the number already exists?

I think im on the wrong way with my VBA.

```<code>Sub Zufallszahlen()

Dim Rng As Range

Max = 6
Min = 1
Anzahl = 4
counter = 0
innercounter = 0
SZeile = 2
AWert = "X"

Range("C:C").Clear

Do
    counter = counter + 1
    ZZahl = Int((Max * Rnd) + Min)
    innercounter = 0

    Do
        innercounter = innercounter + 1
            If Cells(innercounter, 2) = ZZahl Then
            ZZahl = Int((Max * Rnd) + Min)

        Else
    Loop Until innercounter = Anzahl

    ' Cells(counter, 1).Value = counter
    Cells(counter, 2).Value = ZZahl
    Cells(ZZahl, 3).Value = AWert

Loop Until counter = Anzahl

Range("B:B").Clear
End Sub

</code>```

答:
Ty Guys thats perfect =) i use this now and it works very nice + i understand my
misconception

```<code>    Sub Zufallszahlen()

Const MaxN = 29
Const MinN = 1
Const Anzahl = 4
Const Awert = "X"

Dim ar, n As Long, r As Long
n = MaxN - MinN + 1
If n < Anzahl Then
    MsgBox "Min to Max range must be >= " & Anzahl
    Exit Sub
End If

ReDim ar(1 To n, 1 To 1)

For i = 1 To Anzahl
    Do
        r = 1 + Int(n * Rnd())
    Loop Until ar(r, 1) = ""
    ar(r, 1) = Awert
Next
Range("C:C").Clear
Range("C" & MinN).Resize(n) = ar
</code>```

End Sub

Buts not finally completed.
Can I include this part in another if?

This is intended to ensure that the values of the cells to the left of the cells randomly marked with an x add up to between 10 and 20, for example. Otherwise the random cells should be regenerated

Title: X Unique Randomize Numbers

Body:
i need a little bit help.
Is it possible to fill a list with random numbers and to check this list before each loop to see if the number already exists?

I think im on the wrong way with my VBA.

Sub Zufallszahlen()

Dim Rng As Range

Max = 6
Min = 1
Anzahl = 4
counter = 0
innercounter = 0
SZeile = 2
AWert = "X"

Range("C:C").Clear

Do
    counter = counter + 1
    ZZahl = Int((Max * Rnd) + Min)
    innercounter = 0

    Do
        innercounter = innercounter + 1
            If Cells(innercounter, 2) = ZZahl Then
            ZZahl = Int((Max * Rnd) + Min)

        Else
    Loop Until innercounter = Anzahl

    ' Cells(counter, 1).Value = counter
    Cells(counter, 2).Value = ZZahl
    Cells(ZZahl, 3).Value = AWert

Loop Until counter = Anzahl

Range("B:B").Clear
End Sub

Body:
Ty Guys thats perfect =) i use this now and it works very nice + i understand my
misconception

    Sub Zufallszahlen()

Const MaxN = 29
Const MinN = 1
Const Anzahl = 4
Const Awert = "X"

Dim ar, n As Long, r As Long
n = MaxN - MinN + 1
If n < Anzahl Then
    MsgBox "Min to Max range must be >= " & Anzahl
    Exit Sub
End If

ReDim ar(1 To n, 1 To 1)

For i = 1 To Anzahl
    Do
        r = 1 + Int(n * Rnd())
    Loop Until ar(r, 1) = ""
    ar(r, 1) = Awert
Next
Range("C:C").Clear
Range("C" & MinN).Resize(n) = ar

End Sub

Buts not finally completed.
Can I include this part in another if?

This is intended to ensure that the values of the cells to the left of the cells randomly marked with an x add up to between 10 and 20, for example. Otherwise the random cells should be regenerated


问:
Docker pull error : x509: certificate has expired or is not yet valid
Description of problem:

I'm trying to pull ubuntu from the public registry with this command :

```<code>docker pull ubuntu
</code>```

And then i got this results (the previous command was working yesterday) :

"Error while pulling image: Get https://index.docker.io/v1/repositories/library/ubuntu/images: x509: certificate has expired or is not yet valid"

docker version :

```<code>Client:
Version: 1.10.0
API version: 1.22
Go version: go1.5.3
Git commit: 590d510
Built: Thu Feb 4 18:36:33 2016
OS/Arch: linux/amd64

Server:
Version: 1.10.0
API version: 1.22
Go version: go1.5.3
Git commit: 590d510
Built: Thu Feb 4 18:36:33 2016
OS/Arch: linux/amd64
</code>```

docker info :

```<code>Containers: 4
Running: 0
Paused: 0
Stopped: 4
Images: 20
Server Version: 1.10.0
Storage Driver: aufs
Root Dir: /var/lib/docker/aufs
Backing Filesystem: extfs
Dirs: 44
Dirperm1 Supported: true
Execution Driver: native-0.2
Logging Driver: json-file
Plugins:
Volume: local
Network: bridge null host
Kernel Version: 3.19.0-49-generic
Operating System: Ubuntu 14.04.3 LTS
OSType: linux
Architecture: x86_64
CPUs: 4
Total Memory: 5.815 GiB
Name: ubuntu
ID: Y6OO:23T2:BAPU:DVQJ:HJCJ:USEP:T6EU:PMG4:O4M6:46C7:JKPC:BQHT
WARNING: No swap limit support
</code>```

uname -a :

```<code>Linux ubuntu 3.19.0-49-generic #55~14.04.1-Ubuntu SMP Fri Jan 22 11:24:31 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
</code>```

I verify my "date" and everything is good. I don't know where this issue can come from.

答:
in my case i had to add

```<code>registry_nginx['ssl_certificate'] = "/path/to/certificate.pem"
registry_nginx['ssl_certificate_key'] = "/path/to/certificate.key"
</code>```

to my /etc/gitlab/gitlab.rb , because I was using certbot for ssl certification of my gitlab.example.com domain.
I used the same fullchain.pem and privkey.pem for my registry and the error gone.

Body:
Description of problem:

I'm trying to pull ubuntu from the public registry with this command :

docker pull ubuntu

And then i got this results (the previous command was working yesterday) :

"Error while pulling image: Get https://index.docker.io/v1/repositories/library/ubuntu/images: x509: certificate has expired or is not yet valid"

docker version :

Client:
Version: 1.10.0
API version: 1.22
Go version: go1.5.3
Git commit: 590d510
Built: Thu Feb 4 18:36:33 2016
OS/Arch: linux/amd64

Server:
Version: 1.10.0
API version: 1.22
Go version: go1.5.3
Git commit: 590d510
Built: Thu Feb 4 18:36:33 2016
OS/Arch: linux/amd64

docker info :

Containers: 4
Running: 0
Paused: 0
Stopped: 4
Images: 20
Server Version: 1.10.0
Storage Driver: aufs
Root Dir: /var/lib/docker/aufs
Backing Filesystem: extfs
Dirs: 44
Dirperm1 Supported: true
Execution Driver: native-0.2
Logging Driver: json-file
Plugins:
Volume: local
Network: bridge null host
Kernel Version: 3.19.0-49-generic
Operating System: Ubuntu 14.04.3 LTS
OSType: linux
Architecture: x86_64
CPUs: 4
Total Memory: 5.815 GiB
Name: ubuntu
ID: Y6OO:23T2:BAPU:DVQJ:HJCJ:USEP:T6EU:PMG4:O4M6:46C7:JKPC:BQHT
WARNING: No swap limit support

uname -a :

Linux ubuntu 3.19.0-49-generic #55~14.04.1-Ubuntu SMP Fri Jan 22 11:24:31 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

I verify my "date" and everything is good. I don't know where this issue can come from.

Body:
in my case i had to add

registry_nginx['ssl_certificate'] = "/path/to/certificate.pem"
registry_nginx['ssl_certificate_key'] = "/path/to/certificate.key"

to my /etc/gitlab/gitlab.rb , because I was using certbot for ssl certification of my gitlab.example.com domain.
I used the same fullchain.pem and privkey.pem for my registry and the error gone.


问:
How to multiply and group using laravel eloquent with relation
I'd like to export data from my database but have problems with multiplying and sum using laravel eloquent with relation

So i have 2 tables there (budgets, items)

Budget's:

```<code>// Table
+----+---------------+-----------------+------+-----+--------------------+
| id | delivery_plan | item_code       | curr | qty | price              |
+----+---------------+-----------------+------+-----+--------------------+
|  1 | 2022-08       | 201.0001        | IDR  |   1 |    2000.0000000000 |
|  2 | 2022-08       | 201.0001        | IDR  |   3 |    2000.0000000000 |
|  3 | 2022-07       | 201.9999        | IDR  |   2 |    2000.0000000000 |
+----+---------------+-----------------+------+-----+--------------------+

// Relation

public function item()
{
    return $this->belongsTo(Item::class, 'item_code', 'item_code');
}
</code>```

Items :

```<code>// Table
+----+----------------+-----------+
| id | subgroup       | item_code |
+----+----------------+-----------+
|  1 | KOMPONEN MESIN | 201.0001  |
|  2 | EQUIPMENT LAIN | 201.9999  |
+----+----------------+-----------+

// Relation
public function budgets()
{
    return $this->hasMany(Budget::class, 'item_code', 'item_code');
}
</code>```

So, the scenario is :

Multiply the "qty" * "price" columns and name them as "total" like so

Group them by "subgroup" column, which came from item() relationship

Group them by "delivery_plan"

I prefer using eloquent because to minimize the complexity because i need that "whereHas" method
This is what i've tried so far and isn't working :

```<code>$budgets = Budget::with('item', 'rate')->whereHas('period.term', function (Builder $builder) {
    $builder->where('name', '=', Session::get('term-budget'));
})->where('section', Session::get('section-budget'))->getQuery();

$result = $budgets->sum('price * qty')->get();
</code>```

How can i achieve this ?

答:
This can be solved by a join with SUM(), something like below (untested):</p>
```<code>Budget::leftJoin('items', 'budgets.item_code', '=', 'items.item_code')
    ->addSelect('subgroup')
    ->addSelect('delivery_plan')
    ->addselect(\DB::raw('SUM(qty * price) as total'))
    ->groupBy('subgroup', 'delivery_plan')
    ->get();
</code>```

Body:
I'd like to export data from my database but have problems with multiplying and sum using laravel eloquent with relation

So i have 2 tables there (budgets, items)

Budget's:

// Table
+----+---------------+-----------------+------+-----+--------------------+
| id | delivery_plan | item_code       | curr | qty | price              |
+----+---------------+-----------------+------+-----+--------------------+
|  1 | 2022-08       | 201.0001        | IDR  |   1 |    2000.0000000000 |
|  2 | 2022-08       | 201.0001        | IDR  |   3 |    2000.0000000000 |
|  3 | 2022-07       | 201.9999        | IDR  |   2 |    2000.0000000000 |
+----+---------------+-----------------+------+-----+--------------------+

// Relation

public function item()
{
    return $this->belongsTo(Item::class, 'item_code', 'item_code');
}

Items :

// Table
+----+----------------+-----------+
| id | subgroup       | item_code |
+----+----------------+-----------+
|  1 | KOMPONEN MESIN | 201.0001  |
|  2 | EQUIPMENT LAIN | 201.9999  |
+----+----------------+-----------+

// Relation
public function budgets()
{
    return $this->hasMany(Budget::class, 'item_code', 'item_code');
}

So, the scenario is :

Multiply the "qty" * "price" columns and name them as "total" like so

Group them by "subgroup" column, which came from item() relationship

Group them by "delivery_plan"

I prefer using eloquent because to minimize the complexity because i need that "whereHas" method
This is what i've tried so far and isn't working :

$budgets = Budget::with('item', 'rate')->whereHas('period.term', function (Builder $builder) {
    $builder->where('name', '=', Session::get('term-budget'));
})->where('section', Session::get('section-budget'))->getQuery();

$result = $budgets->sum('price * qty')->get();

How can i achieve this ?

Body:
This can be solved by a join with SUM(), something like below (untested):

Budget::leftJoin('items', 'budgets.item_code', '=', 'items.item_code')
    ->addSelect('subgroup')
    ->addSelect('delivery_plan')
    ->addselect(\DB::raw('SUM(qty * price) as total'))
    ->groupBy('subgroup', 'delivery_plan')
    ->get();


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

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

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

Now taking the context of heap allocated variables,

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

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

答:
Stack (most implementations use stack for automatic storage duration objects) and static storage duration objects memory is allocated during the program load and startup.

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

I do not know what is the "logical address" but compilers do "calculate" the references to the automatic storage duration objects. How? Simply compiler knows how far from the stack pointer address the automatic storage duration object is located (offset).

Generally the same applies to the static duration objects and the code, the compiler only calculates the offset from the their sections.

Is the heap of the same size for all programs?

It is implementation defined.


问:
transfer data from view to controller
How do this.
I want to transfer data
What I did:

js

```<code>    $("#add-ling-user-couch").click(function () {
    var CoucnId = $(this).data('couch-id');
    var data = { "CoucnId": curentUserId };
    $.ajax({
        url: '/AppUser/AddLink',
        type: "POST",
        data: data,
        success: function (result) { console.log(result) }
       // dataType: dataType
    });
});
</code>```

cshtml

```<code> @foreach (var a in Model)
    {
        <tr>

            <td>@a.FirstName</td>

            <td>
                <div class="btn-group" role="group">
                    @Html.ActionLink("edit", "Edit", new { id = a.Id }, new { @class = "btn btn-secondary" })
                    @Html.ActionLink("Del", "Delete", new { id = a.Id }, new { @class = "btn btn-secondary" })
                    <a id="add-ling-user-couch" data-couch-id="@a.Id">Add Link</a>
                </div>

            </td>

        </tr>
</code>```

Contoller

```<code>        [HttpPost]
    [AllowAnonymous]
    public JsonResult AddLink(AddLinkViewModel model)
    {

        return new JsonResult()
        {
            Data = new { success = true, message ="Success" }
        };
    }
</code>```

I get some problem use it.

How can to do it other wise?
My way create more problem than it solve

it would work but I dont find it's correct

```<code><form method="post">
                                <input type="hidden" value="@a.Id" name="CoucnId" />
                                <input type="submit" value="Sender" />
                            </form>
</code>```

答:
javascript:

```<code>$.post("/AppUser/AddLink", { CoucnId: curentUserId }, function (data) {

    });
</code>```

then in controller return partialview with modle:

```<code> [HttpPost]
    [AllowAnonymous]
    public JsonResult AddLink(int CoucnId)
    {
      fetch data and fill modle:
      return partialview("viewname",model);
    }
</code>```

Title: transfer data from view to controller

Body:
How do this.
I want to transfer data
What I did:

js

    $("#add-ling-user-couch").click(function () {
    var CoucnId = $(this).data('couch-id');
    var data = { "CoucnId": curentUserId };
    $.ajax({
        url: '/AppUser/AddLink',
        type: "POST",
        data: data,
        success: function (result) { console.log(result) }
       // dataType: dataType
    });
});

cshtml

 @foreach (var a in Model)
    {

            @a.FirstName

                    @Html.ActionLink("edit", "Edit", new { id = a.Id }, new { @class = "btn btn-secondary" })
                    @Html.ActionLink("Del", "Delete", new { id = a.Id }, new { @class = "btn btn-secondary" })
                    Add Link

Contoller

        [HttpPost]
    [AllowAnonymous]
    public JsonResult AddLink(AddLinkViewModel model)
    {

        return new JsonResult()
        {
            Data = new { success = true, message ="Success" }
        };
    }

I get some problem use it.

How can to do it other wise?
My way create more problem than it solve

it would work but I dont find it's correct

<form method="post">
                                <input type="hidden" value="@a.Id" name="CoucnId" />
                                <input type="submit" value="Sender" />
                            </form>

Body:
javascript:

$.post("/AppUser/AddLink", { CoucnId: curentUserId }, function (data) {

    });

then in controller return partialview with modle:

 [HttpPost]
    [AllowAnonymous]
    public JsonResult AddLink(int CoucnId)
    {
      fetch data and fill modle:
      return partialview("viewname",model);
    }


问:
Ansible facts: An error (1332) occurred while enumerating the group membership. The member's SID could not be resolved
I'm trying to register a CNAME inside our Microsoft DNS server using this playbook:

- hosts: windns
  remote_user: "{{ lookup('env', 'USER') }}@MYDOMAIN.COM"

  tasks:

  - name: Create alias
    win_dns_record:
      computer_name: "{{ inventory_hostname }}"
      name: "myalias"
      type: "CNAME"
      value: "myhost.mydomain.com"
      zone: "MYDOMAIN.COM"
      state: present
```
<p>I'm stuck on this error when <code>gather_facts: true</code></p>
```An error (1332) occurred while enumerating the group membership.  The member's SID could not be resolved.
```
```$ ansible-playbook --check dns_alias.yml --ask-vault-pass -k
SSH password:
Vault password:

PLAY [windns] ***********************************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
fatal: [windns]: FAILED! => {"ansible_facts": {}, "changed": false, "msg": "The following modules failed to execute: setup\n  setup: Unhandled exception while executing module: An error (1332) occurred while enumerating the group membership.  The member's SID could not be resolved.\n"}

PLAY RECAP ******************************************************************************************************************************
windns                 : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0
```

If I set gather_fatcs: false it works.

<s>CNAME is not created.</s>. The user is domain admin.

Any hints?

答:
After some research regarding the error message

An error (1332) occurred while enumerating the group membership. The member's SID could not be resolved.

and your hint

The user is domain admin

it seems according

How to overcome the "The member's SID could not be resolved" error when checking if user is a member of group?

Unable to add/remove objects to group due to orphaned SIDs: PrincipalOperationException: An error (1332) occurred

and others, 3, 4, 5, ...

that the issue is caused not by Ansible but the environment and deleted, renamed or orphaned accounts.

Body:
I'm trying to register a CNAME inside our Microsoft DNS server using this playbook:

- hosts: windns
  remote_user: "{{ lookup('env', 'USER') }}@MYDOMAIN.COM"

  tasks:

  - name: Create alias
    win_dns_record:
      computer_name: "{{ inventory_hostname }}"
      name: "myalias"
      type: "CNAME"
      value: "myhost.mydomain.com"
      zone: "MYDOMAIN.COM"
      state: present

I'm stuck on this error when gather_facts: true

An error (1332) occurred while enumerating the group membership.  The member's SID could not be resolved.

$ ansible-playbook --check dns_alias.yml --ask-vault-pass -k
SSH password:
Vault password:

PLAY [windns] ***********************************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
fatal: [windns]: FAILED! => {"ansible_facts": {}, "changed": false, "msg": "The following modules failed to execute: setup\n  setup: Unhandled exception while executing module: An error (1332) occurred while enumerating the group membership.  The member's SID could not be resolved.\n"}

PLAY RECAP ******************************************************************************************************************************
windns                 : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

If I set gather_fatcs: false it works.

<s>CNAME is not created.</s>. The user is domain admin.

Any hints?


问:
CSV file Infinity value issue with AWS Glue job
I have a csv file which I am reading with Pandas and trying to convert NaN and Infinity to 0.0. I have the code which I run locally and get the conversion properly such as:

```<code>df = pd.read_csv('test.csv')
print(df['C1'])
df.replace([np.inf, -np.inf], np.nan, inplace=True)
df = df.fillna(0.00)
print(df['C1'])
</code>```
```<code>0    NaN
1    inf
2    NaN
Name: C1, dtype: float64
0    0.0
1    0.0
2    0.0
Name: C1, dtype: float64
</code>```

Here, the infinity and NaN value is converted properly into 0.0 as can be seen in the output. But when I do the same in AWS Glue Python Shell job, it does not convert the infinity value to 0.0. The code and output for Glue job is as below:

```<code>df = pd.read_csv('s3://bucket/test.csv')
print(df['C1'])
df = df.replace([np.Infinity, -np.Infinity], np.nan)
df = df.fillna(0.00)
print(df['C1'])
</code>```
```<code>0         NaN
1    Infinity
2         NaN
Name: C1, dtype: object
0           0
1    Infinity
2           0
Name: C1, dtype: object
</code>```

The same file is being used locally and on S3, but the issue is with infinity value. Also, locally, the data types are read as float64, but object type in Glue. Any help around this?

答:
I was able to resolve it based on BdR response in the comments so here is the answer:</p>
```<code>df = pd.read_csv(input_path, na_values=["Infinity", "-Infinity"])
df = df.replace([np.Infinity, -np.Infinity], np.nan)
df = df.fillna(0.00)
</code>```

Body:
I have a csv file which I am reading with Pandas and trying to convert NaN and Infinity to 0.0. I have the code which I run locally and get the conversion properly such as:

df = pd.read_csv('test.csv')
print(df['C1'])
df.replace([np.inf, -np.inf], np.nan, inplace=True)
df = df.fillna(0.00)
print(df['C1'])

0    NaN
1    inf
2    NaN
Name: C1, dtype: float64
0    0.0
1    0.0
2    0.0
Name: C1, dtype: float64

Here, the infinity and NaN value is converted properly into 0.0 as can be seen in the output. But when I do the same in AWS Glue Python Shell job, it does not convert the infinity value to 0.0. The code and output for Glue job is as below:

df = pd.read_csv('s3://bucket/test.csv')
print(df['C1'])
df = df.replace([np.Infinity, -np.Infinity], np.nan)
df = df.fillna(0.00)
print(df['C1'])

0         NaN
1    Infinity
2         NaN
Name: C1, dtype: object
0           0
1    Infinity
2           0
Name: C1, dtype: object

The same file is being used locally and on S3, but the issue is with infinity value. Also, locally, the data types are read as float64, but object type in Glue. Any help around this?

Body:
I was able to resolve it based on BdR response in the comments so here is the answer:

df = pd.read_csv(input_path, na_values=["Infinity", "-Infinity"])
df = df.replace([np.Infinity, -np.Infinity], np.nan)
df = df.fillna(0.00)


问:
How to get parameter name with C#
How can we get parameter name called by a method in C#?

Example:

```<code>public static void PrintList (List<string> list)
{
    Console.WriteLine("\n");
    foreach (var item in list)
    {
        Console.WriteLine(item);
    }
    Console.WriteLine("\n");
}

PrintList(oxygenList);
</code>```

I need the method to print:

oxygenList

Thanks.

答:
If you're using C# 10 or later, you can use the new CallerArgumentExpression attribute to achieve this:

```<code>using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

public static class Program
{
    public static void Main()
    {
        List<string> oxygenList = new List<string> { "A", "B", "C" };
        PrintList(oxygenList);
    }

    public static void PrintList(List<string> list, [CallerArgumentExpression("list")] string? name = null)
    {
        Console.WriteLine("Argument name = " + name); // Prints "Argument name = oxygenList
        Console.WriteLine("\n");

        foreach (var item in list)
        {
            Console.WriteLine(item);
        }

        Console.WriteLine("\n");
    }
}
</code>```

However, note that this gives the expression used when calling the method - so if you call it with this code:

```<code>public static void Main()
{
    PrintList(getOxygenList());
}

public static List<string> getOxygenList()
{
    return new List<string> { "A", "B", "C" };
}
</code>```

the value passed as name will be "getOxygenList()".

It has to work like this because an expression can be used for the parameter - it's not restricted to a simple variable name.

Title: How to get parameter name with C#

Body:
How can we get parameter name called by a method in C#?

Example:

public static void PrintList (List<string> list)
{
    Console.WriteLine("\n");
    foreach (var item in list)
    {
        Console.WriteLine(item);
    }
    Console.WriteLine("\n");
}

PrintList(oxygenList);

I need the method to print:

oxygenList

Thanks.

Body:
If you're using C# 10 or later, you can use the new CallerArgumentExpression attribute to achieve this:

using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

public static class Program
{
    public static void Main()
    {
        List<string> oxygenList = new List<string> { "A", "B", "C" };
        PrintList(oxygenList);
    }

    public static void PrintList(List<string> list, [CallerArgumentExpression("list")] string? name = null)
    {
        Console.WriteLine("Argument name = " + name); // Prints "Argument name = oxygenList
        Console.WriteLine("\n");

        foreach (var item in list)
        {
            Console.WriteLine(item);
        }

        Console.WriteLine("\n");
    }
}

However, note that this gives the expression used when calling the method - so if you call it with this code:

public static void Main()
{
    PrintList(getOxygenList());
}

public static List<string> getOxygenList()
{
    return new List<string> { "A", "B", "C" };
}

the value passed as name will be "getOxygenList()".

It has to work like this because an expression can be used for the parameter - it's not restricted to a simple variable name.


问:
Time complexity of Sieve of erastothenes
I do not understand why there is no factor of √n in time complexity.
Here is the code

def sieve_of_erastothenes(max):
    flags = [True] * (max+1)
    num = 2
    while num*num <= max:
        if flags[num] is True:  # if it is a prime number
            cross_off(flags, num)
        num += 1
    return [i for i in range(2,len(flags)) if flags[i] is True]

def cross_off(flags, prime):
    # no point in crossing anything before prime*prime
    for num in range(prime*prime, len(flags), prime):
        flags[num] = False
        num += prime
```

The outer loop (num*num <= max) runs for √n times. If flag has been set, inner loop runs for n/p times. Summation of n/p where p is only prime gives n*loglogn
So time complexity should be O(√n * n * loglogn). But everywhere I read, it is given as O(nloglogn)

答:
I think I have figured it out with the help of comments from Matt Timmermans and rici. I had 2 misunderstandings

The inner loop for a given prime runs n / prime times.
The summation n/2 + n/3 + n/5 + n/7 + n/11 .... is already taking into account the outer √n factor. The summation itself is because of the outer loop.

The failure case of if condition IS being counted, but it is being overpowered by the other factor. So we can write it as,

```<code>num => 2     3     4   5     6   7     8   9   10  11
sum => n/2 + n/3 + 1 + n/5 + 1 + n/7 + 1 + 1 + 1 + n/11...

sum => (n/2 + n/3 + n/5 ...) + (1 + 1 + 1 + 1....)
sum => (nloglogn) + (n)    #  Worst case. 1+1+1.. will always be less than n
</code>```

O(nloglogn + n) = O(nloglogn)

Body:
I do not understand why there is no factor of √n in time complexity.
Here is the code

def sieve_of_erastothenes(max):
    flags = [True] * (max+1)
    num = 2
    while num*num <= max:
        if flags[num] is True:  # if it is a prime number
            cross_off(flags, num)
        num += 1
    return [i for i in range(2,len(flags)) if flags[i] is True]

def cross_off(flags, prime):
    # no point in crossing anything before prime*prime
    for num in range(prime*prime, len(flags), prime):
        flags[num] = False
        num += prime

The outer loop (num*num <= max) runs for √n times. If flag has been set, inner loop runs for n/p times. Summation of n/p where p is only prime gives n*loglogn
So time complexity should be O(√n * n * loglogn). But everywhere I read, it is given as O(nloglogn)

Body:
I think I have figured it out with the help of comments from Matt Timmermans and rici. I had 2 misunderstandings

The inner loop for a given prime runs n / prime times.
The summation n/2 + n/3 + n/5 + n/7 + n/11 .... is already taking into account the outer √n factor. The summation itself is because of the outer loop.

The failure case of if condition IS being counted, but it is being overpowered by the other factor. So we can write it as,

num => 2     3     4   5     6   7     8   9   10  11
sum => n/2 + n/3 + 1 + n/5 + 1 + n/7 + 1 + 1 + 1 + n/11...

sum => (n/2 + n/3 + n/5 ...) + (1 + 1 + 1 + 1....)
sum => (nloglogn) + (n)    #  Worst case. 1+1+1.. will always be less than n

O(nloglogn + n) = O(nloglogn)