问:
beatiful soup 4 getting an output as (['link1'] ['link2'] ['link3']). How to change as a required format? (['link1', 'link2', 'link3'])
beatiful soup 4 getting an output as (example - ['link1']['link2']['link3']). How to change as a required format? (example - ['link1', 'link2', 'link3'])

I am getting this below output.

```<code>['link1']
['link2']
['link3']
</code>```

I need an output as i mentioned below like this to form a data frame, so what i need to do now.

```<code>['link1', 'link2', 'link3']
</code>```

Exaplain with code also fine. please help me to solve this issue, thanks in advance.

My code

```<code>import bs4
from bs4 import BeautifulSoup
from csv import writer
import requests
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0'}
HOST = 'https://www.zocdoc.com'
#PAGE = 'gastroenterologists/2'
web_page = 'https://www.zocdoc.com/search?address=Houston%2C%20TX&insurance_carrier=&city=Houston&date_searched_for=&day_filter=AnyDay&filters=%7B%7D&gender=-1&language=-1&latitude=29.7604267&locationType=placemark&longitude=-95.3698028&offset=1&insurance_plan=-1&reason_visit=386&search_query=Gastroenterologist&searchType=specialty&sees_children=false&after_5pm=false&before_10am=false&sort_type=Default&dr_specialty=106&state=TX&visitType=inPersonVisit&&timesgridType='
with requests.Session() as session:
    (r := session.get(HOST, headers=headers)).raise_for_status()
    #(r := session.get(f'{HOST}/{PAGE}', headers=headers)).raise_for_status()
    (r := session.get(f'{web_page}', headers=headers)).raise_for_status()
    # process content from here
print(r.text)
soup = BeautifulSoup(r.text, 'lxml')
soup
print(soup.prettify())
</code>```

code 1 to get as a link

```<code>for item in soup.find_all('img'):
    images = []
    items = (item['src'])
    images = 'https:'+items
    print(images)
</code>```

code 2 to get below mentioned output format

```<code>for item in soup.find_all('img'):
    c = []
    items = (item['src'])
    image = ('https:'+items)
    c.append(image)
    print(c)
</code>```

Output - ['link1']
.
.
['linkn']

答:
The reason is you're setting up a list in each for loop and then overwriting it. Defining the list first then appending to it will work like below.</p>
```<code>images = []
for item in soup.find_all('img'):
    items = (item['src'])
    images += [f"https:{i}" for i in items]
    print(images)
</code>```

Body:
beatiful soup 4 getting an output as (example - ['link1']['link2']['link3']). How to change as a required format? (example - ['link1', 'link2', 'link3'])

I am getting this below output.

['link1']
['link2']
['link3']

I need an output as i mentioned below like this to form a data frame, so what i need to do now.

['link1', 'link2', 'link3']

Exaplain with code also fine. please help me to solve this issue, thanks in advance.

My code

import bs4
from bs4 import BeautifulSoup
from csv import writer
import requests
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0'}
HOST = 'https://www.zocdoc.com'
#PAGE = 'gastroenterologists/2'
web_page = 'https://www.zocdoc.com/search?address=Houston%2C%20TX&insurance_carrier=&city=Houston&date_searched_for=&day_filter=AnyDay&filters=%7B%7D&gender=-1&language=-1&latitude=29.7604267&locationType=placemark&longitude=-95.3698028&offset=1&insurance_plan=-1&reason_visit=386&search_query=Gastroenterologist&searchType=specialty&sees_children=false&after_5pm=false&before_10am=false&sort_type=Default&dr_specialty=106&state=TX&visitType=inPersonVisit&&timesgridType='
with requests.Session() as session:
    (r := session.get(HOST, headers=headers)).raise_for_status()
    #(r := session.get(f'{HOST}/{PAGE}', headers=headers)).raise_for_status()
    (r := session.get(f'{web_page}', headers=headers)).raise_for_status()
    # process content from here
print(r.text)
soup = BeautifulSoup(r.text, 'lxml')
soup
print(soup.prettify())

code 1 to get as a link

for item in soup.find_all('img'):
    images = []
    items = (item['src'])
    images = 'https:'+items
    print(images)

code 2 to get below mentioned output format

for item in soup.find_all('img'):
    c = []
    items = (item['src'])
    image = ('https:'+items)
    c.append(image)
    print(c)

Output - ['link1']
.
.
['linkn']

Body:
The reason is you're setting up a list in each for loop and then overwriting it. Defining the list first then appending to it will work like below.

images = []
for item in soup.find_all('img'):
    items = (item['src'])
    images += [f"https:{i}" for i in items]
    print(images)


来源: stackexchange

问:
VSCode: There is no Pip installer available in the selected environment
I'm trying to run the autopep8 linter on a Python file in VSCode.

I've followed the instructions here: https://code.visualstudio.com/docs/python/environments and selected my interpreter (⇧⌘P): /usr/local/bin/python

I then try to format my code, and VSCode says autopep8 isn't installed, and can be installed via Pip. However, when I try to install via Pip, it says There is no Pip installer available in the selected environment.

I then tried launching a terminal in the current environment by selecting Python: Create Terminal from the Command Palette.

The terminal opens fine, pip is present, and I'm even able to pip install autopep8 in the terminal that opened in VSCode, but when I try running the Format Document command I get the same errors that autopep8 and pip aren't available in the environment.

答:
Note: This is a solution for Windows.

First make Sure your Python is installed properly. Run the following command:

```<code>py --version
</code>```

If the Previous command is running fine it will give you your python version. In that case go ahead and check if pip is present or not. Run the below command to check:

```<code>py -m pip
</code>```

If pip is present in your system it show give you a list of option and info. If that's the case then go Ahead and run pip. All you need to do is precede the command you would normally write with py -m. For example:

```<code>pip install flask

py -m pip install flask
</code>```

This should solve your problem.

ContentLicense: CC BY-SA 4.0

Body:
Note: This is a solution for Windows.

First make Sure your Python is installed properly. Run the following command:

py --version

If the Previous command is running fine it will give you your python version. In that case go ahead and check if pip is present or not. Run the below command to check:

py -m pip

If pip is present in your system it show give you a list of option and info. If that's the case then go Ahead and run pip. All you need to do is precede the command you would normally write with py -m. For example:

pip install flask

py -m pip install flask

This should solve your problem.


问:
Adding on click event to Galleria link using JSON
I have set up my first Galleria gallery using JSON.

Would it be possible to add another function to the on click event for each of the four links I have for my four images?

Is there a way to add another variable to the JSON data or assign a class to each individual image?

The analytics my CMS uses has to be called via an on click function so this is essential on my site.

Many thanks,
H

答: Yes, you can add more variables to Galleria's JSON structure. I have successfully added a property called "video" for every object to stream M-JPG when the picture loads.

ContentLicense: CC BY-SA 3.0


问:
Remove scopes from Firebase OAuthProvider('google.com')
I am using a vanilla configuration of the firebase Auth SDK. It is currently asking for all of these scopes.

I do not need profile picture or name, and would love to remove them. Is it possible?

答:
Simple answer is No name, and picture permissions are granted to your application when you request the profile scope as part of signin.

explanation

Assuming you are following the example found here.  If you check the lines called addScopes.

```<code>provider.addScope('profile');
provider.addScope('email');
</code>```

This is where you define what permissions your applicating needs.  The email and profile scopes are part of Google sign in (Open Id Connect)  The profile scope give you access to some basic profile information about the user.  Part of basic profile information is their picture.

These two claims are actually returned by the user info endpoint. This is the response from the userinfo endpoint when I authorized only with the profile scope.

```<code>{
  "family_name": "Lawton",
  "name": "Linda Lawton",
  "picture": "https://lh3.googleusercontent.com/a-/AOh14GhroCYJp2P9xeYeYk1npchBPK-zbtTxzNQo0WAHI20=s96-c",
  "locale": "en",
  "given_name": "Linda",
  "id": "1172004755376"
}
</code>```

This is all default, so its not something you can change.

full example

```<code>// Using a redirect.
firebase.auth().getRedirectResult().then(function(result) {
  if (result.credential) {
    // This gives you the OAuth Access Token for that provider.
    var token = result.credential.accessToken;
  }
  var user = result.user;
});

// Start a sign in process for an unauthenticated user.
var provider = new firebase.auth.OAuthProvider('google.com');
provider.addScope('profile');
provider.addScope('email');
firebase.auth().signInWithRedirect(provider);
</code>```

Body:
Simple answer is No name, and picture permissions are granted to your application when you request the profile scope as part of signin.

explanation

Assuming you are following the example found here.  If you check the lines called addScopes.

provider.addScope('profile');
provider.addScope('email');

This is where you define what permissions your applicating needs.  The email and profile scopes are part of Google sign in (Open Id Connect)  The profile scope give you access to some basic profile information about the user.  Part of basic profile information is their picture.

These two claims are actually returned by the user info endpoint. This is the response from the userinfo endpoint when I authorized only with the profile scope.

{
  "family_name": "Lawton",
  "name": "Linda Lawton",
  "picture": "https://lh3.googleusercontent.com/a-/AOh14GhroCYJp2P9xeYeYk1npchBPK-zbtTxzNQo0WAHI20=s96-c",
  "locale": "en",
  "given_name": "Linda",
  "id": "1172004755376"
}

This is all default, so its not something you can change.

full example

// Using a redirect.
firebase.auth().getRedirectResult().then(function(result) {
  if (result.credential) {
    // This gives you the OAuth Access Token for that provider.
    var token = result.credential.accessToken;
  }
  var user = result.user;
});

// Start a sign in process for an unauthenticated user.
var provider = new firebase.auth.OAuthProvider('google.com');
provider.addScope('profile');
provider.addScope('email');
firebase.auth().signInWithRedirect(provider);


问:
Can I load two large csv files in pandas and perform Upsert ( Update / Insert )
I have Two 5GB CSV files with 10 Columns, I need to perform update/Insert logic and generate a final CSV by comparing both CSV files.

How to do it in Python Pandas?

Ex:

If you have any alternatives solutions to do the job, let me know

答:
Try using the isin() method or the merge() method to compare the 2 csv files.

```<code>import pandas as pd
csv1 = pd.read_csv("file1.csv")
csv2 = pd.read_csv("file2.csv")

#comparing the data using isin()

result = csv1[csv1.apply(tuple,1).isin(csv2.apply(tuple,1))]
print(result)

#comparing the data using merge()

result2 = csv1.merge(csv2, indicator=True, how='outer').loc[lambda v : V['_merge'] != 'both']
print(result2)
</code>```

To update or insert into csv files, check out the following link.
Updating Values in csv files

Body:
Try using the isin() method or the merge() method to compare the 2 csv files.

import pandas as pd
csv1 = pd.read_csv("file1.csv")
csv2 = pd.read_csv("file2.csv")

#comparing the data using isin()

result = csv1[csv1.apply(tuple,1).isin(csv2.apply(tuple,1))]
print(result)

#comparing the data using merge()

result2 = csv1.merge(csv2, indicator=True, how='outer').loc[lambda v : V['_merge'] != 'both']
print(result2)

To update or insert into csv files, check out the following link.
Updating Values in csv files


问:
Find span with 2 attributes Selenium
Just trying to code a web scraper with selenium which searchs for a span in a div which has an other span with a title in it.

```<code><div class="col-lg-3 col-6 attributes-column"><div class="p-3 bg-color-third d-flex flex-column border-radius-8px h-100 position-relative attributes-main"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAD4SURBVHgB3ZXNEYIwEIVfGA/iiRLszBawArACpQOtDDrAEwkX1iyQ8WY2BDj4zfAzzNtskn1sgI1R7qXXfUFEuf2SeaMIb3t/Hk/HqyiBMeZug3IEQqBbmqalV2g60xptSGt9hgDWsb43fSvRg8V8IQBpzAHLacTKJSuQkmBjRFsUY2HvCtjC1o6laHCGdQq5dVr5HeRHDWIt7K/BPHP7QzUQ4HR2SzNZgkimBFNhIN2G4ASkqOKngqrnetRYiTEBN6yBhsqtZFdi+9RORf7vBIEWdjql1BjnbXZsYWvfYrYwpNBArzGRRNx13SNBcpF2U56U6Kxegw+CobhgOuqV7gAAAABJRU5ErkJggg==" alt="copy"><span class="fs-11px text-uppercase letter-spacing-3 text-truncate tw-text-secondary" title="Total Volume (ALL Time, ALL Marketplaces)">Total Volume (ALL Time, ALL Marketplaces)</span><span class="text-white fs-14px text-truncate attribute-value" title="5325.23 ◎">5325.23 ◎</span></div></div>
</code>```

The problem is that there are multiple divs with this class. So I have to find only this div which has the span with the title=Total Volume (ALL Time, ALL Marketplaces) in it and then print the span with the class=text-white fs-14px text-truncate attribute-value

Can anyone help me with this problem?
So I only can scrap the right span in the div?

Thank you very much <3

答:
I think this would be helpful :
WebElement el=driver.findElement(By.xpath("//div//span[contains(text(),'Total Volume')]//following-sibling::span"));
System.out.println(el.getText());</p>

Title: Find span with 2 attributes Selenium

Body:
Just trying to code a web scraper with selenium which searchs for a span in a div which has an other span with a title in it.

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAD4SURBVHgB3ZXNEYIwEIVfGA/iiRLszBawArACpQOtDDrAEwkX1iyQ8WY2BDj4zfAzzNtskn1sgI1R7qXXfUFEuf2SeaMIb3t/Hk/HqyiBMeZug3IEQqBbmqalV2g60xptSGt9hgDWsb43fSvRg8V8IQBpzAHLacTKJSuQkmBjRFsUY2HvCtjC1o6laHCGdQq5dVr5HeRHDWIt7K/BPHP7QzUQ4HR2SzNZgkimBFNhIN2G4ASkqOKngqrnetRYiTEBN6yBhsqtZFdi+9RORf7vBIEWdjql1BjnbXZsYWvfYrYwpNBArzGRRNx13SNBcpF2U56U6Kxegw+CobhgOuqV7gAAAABJRU5ErkJggg==" alt="copy">Total Volume (ALL Time, ALL Marketplaces)5325.23 ◎

The problem is that there are multiple divs with this class. So I have to find only this div which has the span with the title=Total Volume (ALL Time, ALL Marketplaces) in it and then print the span with the class=text-white fs-14px text-truncate attribute-value

Can anyone help me with this problem?
So I only can scrap the right span in the div?

Thank you very much <3


问:
list.append vs pd.series.append
I noticed that while list.append changes the original list, pd.series.append doesn't change the original series:

```<code>b = [1,2,3,4,5]

b.append(9)

b

# returns [1, 2, 3, 4, 5, 9]
</code>```
```<code>s = pd.Series([1,2,3,4,5])

s.append(pd.Series([9]))

s

# returns
0    1
1    2
2    3
3    4
4    5

</code>```

Despite using Python for quite a while I never realized this and spent a long time debugging because I kept getting errors or unintended values while running a for loop for a series using the 'append' method inside. Python is my first programming language btw.

Why is there a discrepancy although both are the same methods? Or is the 'append' method an exception? It gets personally confusing because it makes a huge difference in writing python code and getting the results I want. And it makes me wonder if there are similar discrepancies for other methods between lists and series(or dataframes) as well that I should be aware of.

I'm just a bit frustrated whenever I encounter these seemingly trivial things because I personally tend to forget them later on and repeat the same mistake.

Should I just memorize this and get over with it? I wish to know the approach I should take when trying to learn new things like these because I don't know whether I'll be able to remember these kinds of subtle differences as time passes. I would appreciate any good tips or advice.

答:
In Pandas, the append method does NOT change the original DataFrame.

In contrast, append method of list changes target list.

Let's take a look.

```<code>b = [1,2,3,4,5]

b.append(9)

b

# returns [1, 2, 3, 4, 5, 9] # target list 'b' has been changed.

</code>```

Case of pandas.

```<code>import pandas as pd

df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'), index=['x', 'y'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'), index=['x', 'y'])
df.append(df2)

df

# result =
           A    B
        x  1    2
        y  3    4
</code>```

So we have to assign clearly that we are going to change the DataFrame.
e.g.

```<code>df = df.append(df2) # this changes df.

df
# result =  A   B
        x   1   2
        y   3   4
        x   5   6
        y   7   8
</code>```

Hopefully it helps :)

Title: list.append vs pd.series.append

Body:
I noticed that while list.append changes the original list, pd.series.append doesn't change the original series:

b = [1,2,3,4,5]

b.append(9)

b

# returns [1, 2, 3, 4, 5, 9]

s = pd.Series([1,2,3,4,5])

s.append(pd.Series([9]))

s

# returns
0    1
1    2
2    3
3    4
4    5

Despite using Python for quite a while I never realized this and spent a long time debugging because I kept getting errors or unintended values while running a for loop for a series using the 'append' method inside. Python is my first programming language btw.

Why is there a discrepancy although both are the same methods? Or is the 'append' method an exception? It gets personally confusing because it makes a huge difference in writing python code and getting the results I want. And it makes me wonder if there are similar discrepancies for other methods between lists and series(or dataframes) as well that I should be aware of.

I'm just a bit frustrated whenever I encounter these seemingly trivial things because I personally tend to forget them later on and repeat the same mistake.

Should I just memorize this and get over with it? I wish to know the approach I should take when trying to learn new things like these because I don't know whether I'll be able to remember these kinds of subtle differences as time passes. I would appreciate any good tips or advice.

Body:
In Pandas, the append method does NOT change the original DataFrame.

In contrast, append method of list changes target list.

Let's take a look.

b = [1,2,3,4,5]

b.append(9)

b

# returns [1, 2, 3, 4, 5, 9] # target list 'b' has been changed.

Case of pandas.

import pandas as pd

df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'), index=['x', 'y'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'), index=['x', 'y'])
df.append(df2)

df

# result =
           A    B
        x  1    2
        y  3    4

So we have to assign clearly that we are going to change the DataFrame.
e.g.

df = df.append(df2) # this changes df.

df
# result =  A   B
        x   1   2
        y   3   4
        x   5   6
        y   7   8

Hopefully it helps :)


问:
MiniZinc - Constraint to enforce two arrays be equal
I'm trying to model a satisfaction problem with MiniZinc but I'm stuck at coding this constraint:

Given two arrays A and B of equal length, enforce that A is a permutation of B

In other words, I'm looking for a constraint that enforces [1,2,2]=[1,2,2] and also [1,2,2]=[2,2,1]. Informally, A and B have to be equal. The arrays are both defined on the same set of integers, in particular the set 1..n-1, for some n. Values in both A and B can be repeated (see example).

Is there such a global constraint in MiniZinc? Thank you.

答:
In addition to the predicate shown by hakank, here are two other ways to express the same predicate

```<code>include "globals.mzn";

%
% Ensure that a and b are perumutations of each other by
% counting the number of occurences of each value in the
% domains of a and b,
%
predicate permutation_count(array[int] of var int: a,
                            array[int] of var int: b) =
    let {
        set of int: I = index_set(a),
        constraint assert(I = index_set(b), "Index sets of a and b must match"),
        set of int: domain = dom_array(a) intersect dom_array(b),
        set of int: NValues = 1..card(domain),
        array[NValues] of int: values = [ v | v in domain ],
        array[NValues] of var 0..card(I): counts,
    } in
    global_cardinality_closed(a, values, counts) /\
    global_cardinality_closed(b, values, counts);

%
% Ensure that a and b are permutations of each other by
% sorting each and constraining that to be the same.
%
predicate permutation_sort(array[int] of var int: a,
                           array[int] of var int: b) =
    let {
        set of int: I = index_set(a),
        constraint assert(I = index_set(b), "Index sets of a and b must match"),
        set of int: domain = dom_array(a) intersect dom_array(b),
        array[I] of var domain: sorted_values,
    } in
    sorted_values = sort(a) /\
    sorted_values = sort(b);

int: n = 3;

array[1..n] of var 1..2: x;
array[1..n] of var 1..2: y;

constraint permutation_count(x, y);

solve satisfy;
</code>```

The first one counts the values in both input arrays, since in permutations the counts must be the same. The second variant uses the sorting constraint to sort both a and b to check that they are the same.

Which variant works best can vary between solvers, problems, and problem isntances. The counting solution may be problematic if the domains of the inputs are large, which is worth remembering.

Body:
In addition to the predicate shown by hakank, here are two other ways to express the same predicate

include "globals.mzn";

%
% Ensure that a and b are perumutations of each other by
% counting the number of occurences of each value in the
% domains of a and b,
%
predicate permutation_count(array[int] of var int: a,
                            array[int] of var int: b) =
    let {
        set of int: I = index_set(a),
        constraint assert(I = index_set(b), "Index sets of a and b must match"),
        set of int: domain = dom_array(a) intersect dom_array(b),
        set of int: NValues = 1..card(domain),
        array[NValues] of int: values = [ v | v in domain ],
        array[NValues] of var 0..card(I): counts,
    } in
    global_cardinality_closed(a, values, counts) /\
    global_cardinality_closed(b, values, counts);

%
% Ensure that a and b are permutations of each other by
% sorting each and constraining that to be the same.
%
predicate permutation_sort(array[int] of var int: a,
                           array[int] of var int: b) =
    let {
        set of int: I = index_set(a),
        constraint assert(I = index_set(b), "Index sets of a and b must match"),
        set of int: domain = dom_array(a) intersect dom_array(b),
        array[I] of var domain: sorted_values,
    } in
    sorted_values = sort(a) /\
    sorted_values = sort(b);

int: n = 3;

array[1..n] of var 1..2: x;
array[1..n] of var 1..2: y;

constraint permutation_count(x, y);

solve satisfy;

The first one counts the values in both input arrays, since in permutations the counts must be the same. The second variant uses the sorting constraint to sort both a and b to check that they are the same.

Which variant works best can vary between solvers, problems, and problem isntances. The counting solution may be problematic if the domains of the inputs are large, which is worth remembering.


问:
How can I call a controller method in a view using ASP.NET CORE
I have a controller with a method that returns a value:

```<code>public float GetShoppingCartTotal()
    {
        string user = User.Identity.Name;

        var total = _context.ShutterOrders.Where(c => c.User == user).Select(c => c.Price * c.Amount).Sum();

        return total;
    }
</code>```

How can I call this method from a view so I can show its value, here is my view (P.S. I took out some code of the view since I think it really is unnecessary for the purpose of this question. I have marked the part where I would like to call my controller function):

```<code>@model IEnumerable<ShuttersInc.Areas.Identity.Data.ShutterOrders>
<tfoot>
    <tr>
        <td colspan="3" class="text-right">Total:</td>
        <td class="text-right">
         **I'd like to place it here**
        </td>
    </tr>
</tfoot>
</code>```

P.P.S - I have an IEnumerable model since I list items from a list. I think this is one of the main problems why I can't call the method from the controller, although I might be mistaken.

答:
Your wrong solution must first in controller in action return view with modle:

```<code>public IActionResult  GetShoppingCartTotal()
    {
        string user = User.Identity.Name;

        var total = _context.ShutterOrders.Where(c => c.User == user).Select(c
        => c.Price * c.Amount).Sum();

        return View("viewName",total );
    }
</code>```

then in view :

```<code>@model string
<tfoot>
    <tr>
        <td colspan="3" class="text-right">@Model</td>
        <td class="text-right">
         **I'd like to place it here**
        </td>
    </tr>
</tfoot>
</code>```

Body:
I have a controller with a method that returns a value:

public float GetShoppingCartTotal()
    {
        string user = User.Identity.Name;

        var total = _context.ShutterOrders.Where(c => c.User == user).Select(c => c.Price * c.Amount).Sum();

        return total;
    }

How can I call this method from a view so I can show its value, here is my view (P.S. I took out some code of the view since I think it really is unnecessary for the purpose of this question. I have marked the part where I would like to call my controller function):

@model IEnumerable<ShuttersInc.Areas.Identity.Data.ShutterOrders>

        Total:

         **I'd like to place it here**

P.P.S - I have an IEnumerable model since I list items from a list. I think this is one of the main problems why I can't call the method from the controller, although I might be mistaken.

Body:
Your wrong solution must first in controller in action return view with modle:

public IActionResult  GetShoppingCartTotal()
    {
        string user = User.Identity.Name;

        var total = _context.ShutterOrders.Where(c => c.User == user).Select(c
        => c.Price * c.Amount).Sum();

        return View("viewName",total );
    }

then in view :

@model string
<tfoot>
    <tr>
        <td colspan="3" class="text-right">@Model</td>
        <td class="text-right">
         **I'd like to place it here**
        </td>
    </tr>
</tfoot>


问:
Guzzle: Sending POST with Nested JSON to an API
I am trying to hit a POST API Endpoint with Guzzle in PHP (Wordpress CLI) to calculate shipping cost. The route expects a RAW JSON data in the following format:

```<code>{
   "startCountryCode": "CH"
   "endCountryCode": "US",
   "products": {
       "quantity": 1,
       "vid": x         //Variable ID
    }
}
</code>```

Link to the API I am consuming: https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate

```<code>$body = [
     "endCountryCode"    => "US",
     "startCountryCode"  => "CN",
     "products"          => [
             'vid'               => $vid,
             'quantity'          => 1
     ],
 ];

 $request = $this->client->request(
     'POST', 'https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate',
     [
         'headers' => [
                'CJ-Access-Token' => $this->auth_via_cj(), // unnecessary, no auth required. Ignore this header
         ],
         'body' => json_encode( $body )
     ],
);

</code>```

I've also tried using 'json' => $body instead of the 'body' parameter.

I am getting 400 Bad Request error.

Any ideas?

答:
I spent so many hours on this to just realise that products is actually expecting array of objects. I've been sending just a one-dimensional array and that was  causing the 'Bad Request' error.

In order to fix this, just encapsulate 'vid' and 'quantity' into an array and voila!

Body:
I am trying to hit a POST API Endpoint with Guzzle in PHP (Wordpress CLI) to calculate shipping cost. The route expects a RAW JSON data in the following format:

{
   "startCountryCode": "CH"
   "endCountryCode": "US",
   "products": {
       "quantity": 1,
       "vid": x         //Variable ID
    }
}

Link to the API I am consuming: https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate

$body = [
     "endCountryCode"    => "US",
     "startCountryCode"  => "CN",
     "products"          => [
             'vid'               => $vid,
             'quantity'          => 1
     ],
 ];

 $request = $this->client->request(
     'POST', 'https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate',
     [
         'headers' => [
                'CJ-Access-Token' => $this->auth_via_cj(), // unnecessary, no auth required. Ignore this header
         ],
         'body' => json_encode( $body )
     ],
);

I've also tried using 'json' => $body instead of the 'body' parameter.

I am getting 400 Bad Request error.

Any ideas?


问:
How to create alert when indicator color changes pine script
I am trying to create an alert when the indicator color turns from red to green and vis versa. I am not familiar with the needed code to do so. Can someone help me what to be added to the indicator code to generate this alert?

```<code>//@version=4
//[SHK] STC colored indicator
//https://www.tradingview.com/u/shayankm/

study(title="[SHK] Schaff Trend Cycle (STC)", shorttitle="STC", overlay=false)
EEEEEE=input(12,"Length")
BBBB=input(26,"FastLength")
BBBBB=input(50,"SlowLength")

AAAA(BBB, BBBB, BBBBB) =>
fastMA = ema(BBB, BBBB)
slowMA = ema(BBB, BBBBB)
AAAA = fastMA - slowMA
AAAA

AAAAA(EEEEEE, BBBB, BBBBB) =>
AAA=input(0.5)
var CCCCC = 0.0
var DDD = 0.0
var DDDDDD = 0.0
var EEEEE = 0.0
BBBBBB = AAAA(close,BBBB,BBBBB)
CCC = lowest(BBBBBB, EEEEEE)
CCCC = highest(BBBBBB, EEEEEE) - CCC
CCCCC := (CCCC > 0 ? ((BBBBBB - CCC) / CCCC) * 100 : nz(CCCCC[1]))
DDD := (na(DDD[1]) ? CCCCC : DDD[1] + (AAA * (CCCCC - DDD[1])))
DDDD = lowest(DDD, EEEEEE)
DDDDD = highest(DDD, EEEEEE) - DDDD
DDDDDD := (DDDDD > 0 ? ((DDD - DDDD) / DDDDD) * 100 : nz(DDDDDD[1]))
EEEEE := (na(EEEEE[1]) ? DDDDDD : EEEEE[1] + (AAA * (DDDDDD - EEEEE[1])))
EEEEE

mAAAAA = AAAAA(EEEEEE,BBBB,BBBBB)
mColor = mAAAAA > mAAAAA[1] ? color.new(color.green,20) : color.new(color.red,20)

plot(mAAAAA,color=mColor, title="STC",linewidth=2)

ul=plot(25,color=color.new(color.gray,70))
ll=plot(75,color=color.new(color.gray,70))
fill(ul,ll,color=color.new(color.gray,96))
</code>```

答:
Below line is where the color handling is done:

```<code>mColor = mAAAAA > mAAAAA[1] ? color.new(color.green,20) : color.new(color.red,20)
</code>```

And the condition is mAAAAA > mAAAAA[1]. So you need to look for a state change in this condition.

Below code will do it:

```<code>mColor = mAAAAA > mAAAAA[1] ? color.new(color.green,20) : color.new(color.red,20)
_mColor = mAAAAA > mAAAAA[1]
alertcondition((not _mColor[1] and _mColor), "Red to Green", "Red to Green")
alertcondition((_mColor[1] and not _mColor), "Green to Red", "Green to Red")
</code>```

Body:
I am trying to create an alert when the indicator color turns from red to green and vis versa. I am not familiar with the needed code to do so. Can someone help me what to be added to the indicator code to generate this alert?

//@version=4
//[SHK] STC colored indicator
//https://www.tradingview.com/u/shayankm/

study(title="[SHK] Schaff Trend Cycle (STC)", shorttitle="STC", overlay=false)
EEEEEE=input(12,"Length")
BBBB=input(26,"FastLength")
BBBBB=input(50,"SlowLength")

AAAA(BBB, BBBB, BBBBB) =>
fastMA = ema(BBB, BBBB)
slowMA = ema(BBB, BBBBB)
AAAA = fastMA - slowMA
AAAA

AAAAA(EEEEEE, BBBB, BBBBB) =>
AAA=input(0.5)
var CCCCC = 0.0
var DDD = 0.0
var DDDDDD = 0.0
var EEEEE = 0.0
BBBBBB = AAAA(close,BBBB,BBBBB)
CCC = lowest(BBBBBB, EEEEEE)
CCCC = highest(BBBBBB, EEEEEE) - CCC
CCCCC := (CCCC > 0 ? ((BBBBBB - CCC) / CCCC) * 100 : nz(CCCCC[1]))
DDD := (na(DDD[1]) ? CCCCC : DDD[1] + (AAA * (CCCCC - DDD[1])))
DDDD = lowest(DDD, EEEEEE)
DDDDD = highest(DDD, EEEEEE) - DDDD
DDDDDD := (DDDDD > 0 ? ((DDD - DDDD) / DDDDD) * 100 : nz(DDDDDD[1]))
EEEEE := (na(EEEEE[1]) ? DDDDDD : EEEEE[1] + (AAA * (DDDDDD - EEEEE[1])))
EEEEE

mAAAAA = AAAAA(EEEEEE,BBBB,BBBBB)
mColor = mAAAAA > mAAAAA[1] ? color.new(color.green,20) : color.new(color.red,20)

plot(mAAAAA,color=mColor, title="STC",linewidth=2)

ul=plot(25,color=color.new(color.gray,70))
ll=plot(75,color=color.new(color.gray,70))
fill(ul,ll,color=color.new(color.gray,96))

Body:
Below line is where the color handling is done:

mColor = mAAAAA > mAAAAA[1] ? color.new(color.green,20) : color.new(color.red,20)

And the condition is mAAAAA > mAAAAA[1]. So you need to look for a state change in this condition.

Below code will do it:

mColor = mAAAAA > mAAAAA[1] ? color.new(color.green,20) : color.new(color.red,20)
_mColor = mAAAAA > mAAAAA[1]
alertcondition((not _mColor[1] and _mColor), "Red to Green", "Red to Green")
alertcondition((_mColor[1] and not _mColor), "Green to Red", "Green to Red")


问:
Send request to wordnet
I need to get send a request on wordnet knowing the tar_id (taken from Imagenet) to get the lemma assigned to that tar (e.g., I have a tar with houses, I need to send the request and obtain the lemma written on wordnet "living accommodation").

I used requests.get() first, with the URL. Then BeautifulSoup's parser.

I get the parsed HTML as a return but, there is no reference to the "body", meaning the part of the Noun and hypernyms / hyponyms.

Can you tell me how to get that part of Wordnet parsed with the rest of the page?

This is the URL I'm working on: http://wordnet-rdf.princeton.edu/pwn30/03546340-n

答:
Just use the JSON endpoint.

For example:

import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:96.0) Gecko/20100101 Firefox/96.0",
}

url = "http://wordnet-rdf.princeton.edu/json/pwn30/03546340-n"
data = requests.get(url, headers=headers).json()
print(data[0]["definition"])
```
<p>Output:</p>
```structures collectively in which people are housed
```
<p>And if you switch the endpoint to</p>
<pre class="lang-py prettyprint-override"><code>url = "http://wordnet-rdf.princeton.edu/json_rel/03551520-n"
</code>```

You'll get all the word relation data.

Title: Send request to wordnet

Body:
Just use the JSON endpoint.

For example:

import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:96.0) Gecko/20100101 Firefox/96.0",
}

url = "http://wordnet-rdf.princeton.edu/json/pwn30/03546340-n"
data = requests.get(url, headers=headers).json()
print(data[0]["definition"])

Output:

structures collectively in which people are housed

And if you switch the endpoint to

url = "http://wordnet-rdf.princeton.edu/json_rel/03551520-n"

You'll get all the word relation data.


问:
Mips Syscall 5 Invalid Integer Input Error
I am new to Mips. While using syscall 5, I saw that I cannot get integers bigger than 2,147,483,647. I get the error below:

Runtime exception at 0x00400004: invalid integer input (syscall 5)

The syscall I use to get integers

```<code>li $v0, 5
syscall
</code>```

答:
You need to move the value in $v0  to a registor.
You should use this:</p>
```<code> li $v0 , 5
 syscall
 move $t1 , $v0
</code>```
```<code></code>```

Body:
I am new to Mips. While using syscall 5, I saw that I cannot get integers bigger than 2,147,483,647. I get the error below:

Runtime exception at 0x00400004: invalid integer input (syscall 5)

The syscall I use to get integers

li $v0, 5
syscall

Body:
You need to move the value in $v0  to a registor.
You should use this:

 li $v0 , 5
 syscall
 move $t1 , $v0


问:
How to execute some code based on ip address in javascript or jQuery?
I am trying to make a premium version of my website and allowing only premium members to view some divs or hide ads, etc. I wanted to do it based on IP addresses. For that I searched the web and found this snippet:

```

But as always the above code doesn't work. I tried to do document.write and the output comes perfectly fine. What seems to be the problem here. Please explain.

Note 1: I am still learning JavaScript.

Note 2: The platform of my website is Blogger (Idk if that matters)

答:
Try to use function(). Your src not fully ready, so the userip is null userip == 0.0.0.0 always be false.

```<code><script type="text/javascript" src="https://l2.io/ip.js?var=userip"></script>
<script type="text/javascript">
    (function() {
       if (userip== 0.0.0.0 || 1.1.1.1) { // More addresses as required. Given addresses are for example only
       document. getElementsByClassName('ads-here'). style. display = "none";
    }
    })();
    </script>
</code>```

Edit: made it to work. Should first define userip. PS: Ublock Origin blocking l2.io.

 dsgdfgadf

```

Body:
I am trying to make a premium version of my website and allowing only premium members to view some divs or hide ads, etc. I wanted to do it based on IP addresses. For that I searched the web and found this snippet:

But as always the above code doesn't work. I tried to do document.write and the output comes perfectly fine. What seems to be the problem here. Please explain.

Note 1: I am still learning JavaScript.

Note 2: The platform of my website is Blogger (Idk if that matters)

Body:
Try to use function(). Your src not fully ready, so the userip is null userip == 0.0.0.0 always be false.

<script type="text/javascript" src="https://l2.io/ip.js?var=userip"></script>
<script type="text/javascript">
    (function() {
       if (userip== 0.0.0.0 || 1.1.1.1) { // More addresses as required. Given addresses are for example only
       document. getElementsByClassName('ads-here'). style. display = "none";
    }
    })();
    </script>

Edit: made it to work. Should first define userip. PS: Ublock Origin blocking l2.io.

<div class="ads-here"> dsgdfgadf </div>

<script type="text/javascript">
  var userip;
</script>
<script type="text/javascript" src="https://l2.io/ip.js?var=userip"></script>
<script type="text/javascript">
   (function() {
  if (userip == '0.0.0.0') {
      document. getElementsByClassName('ads-here')[0].style.display = "none";
    }
      console.log(userip)
   })();
</script>


问:
how to change dart line length in vscode when formatting dart files?
i'm using VS Code for flutter development and one issue i have is code formatting (styling) which is not as customizable as it is in android-studio. my problem is that each time vs code saves dart files it will break my lines very short like below:

var tuple =
       settings.arguments as Tuple3<String, int, Field>;
```

<p>obviously this is what i want :</p>

<pre class="lang-dart prettyprint-override"><code>var tuple = settings.arguments as Tuple3<String, int, Field>;
</code>```

how can i solve this problem?

答:
For Android Studio

```<code>Android Studio -> Preferences -> Editor -> Code Style -> Dart -> Line length
</code>```

Body:
i'm using VS Code for flutter development and one issue i have is code formatting (styling) which is not as customizable as it is in android-studio. my problem is that each time vs code saves dart files it will break my lines very short like below:

var tuple =
       settings.arguments as Tuple3<String, int, Field>;

obviously this is what i want :

var tuple = settings.arguments as Tuple3<String, int, Field>;

how can i solve this problem?

Body:
For Android Studio

Android Studio -> Preferences -> Editor -> Code Style -> Dart -> Line length


问:
don't know why but somehow substr() doesn't work in code??(php)
recently I'm developing project via PHP, and today I faced a ridiculous situation, and couldn't get the reason still. So here's my problem

let's suppose that I have a string like this : 'myid(myname)'

what  I wanted to get was myid and myname separately, so first I tried it with explode(), and I got result like below:

```<code>$order_identity= myid(myname);
$idexplode=explode("(", $order_identity);
$idexplode= Array ( [0] => myid [1] => myname) )
</code>```

It was good, but not satisfied, because I still have ')' after 'myname' so to get rid of ')'

I used substr() which is very basic built-in php method to slice string value.

```<code>$order_name = substr($idexplode[1],0,-1);
</code>```

and I thought I've done quite good and logged it,However, contrary to my expectations.

I still got 'myname)' when I echoed "echo $order_name";  !!!

I never met problem like this before and do not know why this happened to me :/.

can you tell me what's going on here and how to solve my problem?
thx for reading, your help will be appreciated.

p.s I  already checked type and it was string! and also I checked if my php sever being lagged but it wasn't!!

答: use this $order_name - rtrim($idexplode[1],')') Instead of substr()....you get what your want.....hope you got the answer....

Body:
recently I'm developing project via PHP, and today I faced a ridiculous situation, and couldn't get the reason still. So here's my problem

let's suppose that I have a string like this : 'myid(myname)'

what  I wanted to get was myid and myname separately, so first I tried it with explode(), and I got result like below:

$order_identity= myid(myname);
$idexplode=explode("(", $order_identity);
$idexplode= Array ( [0] => myid [1] => myname) )

It was good, but not satisfied, because I still have ')' after 'myname' so to get rid of ')'

I used substr() which is very basic built-in php method to slice string value.

$order_name = substr($idexplode[1],0,-1);

and I thought I've done quite good and logged it,However, contrary to my expectations.

I still got 'myname)' when I echoed "echo $order_name";  !!!

I never met problem like this before and do not know why this happened to me :/.

can you tell me what's going on here and how to solve my problem?
thx for reading, your help will be appreciated.

p.s I  already checked type and it was string! and also I checked if my php sever being lagged but it wasn't!!


问:
How to derive pseudo-random values of a preset probability from a seed?
I have a bunch of classes that I'd like to instantiate using seeds. Such a class would only have one constructor; taking in a single argument, the seed. A very simple pseudo example could be:

```<code>class Person {
    int age;
    Person(uint32 seed){
        age = deriveAgeFromSeed(seed);
    }
}
</code>```

If I instantiate a Person with a random given seed, e.g. 123456789, it should evaluate to a Person with a specific age, e.g 30. The same seed will always generate the same person (same age).

To achieve this specific example, I could use a regular random-number-generator and use my seed as its seed to generate a random number between e.g. 0-100 for age.
However, I may not want it to be linearly random. Maybe I'd want a 50% chance that the age is in the range of 30-40. I guess I could chain a bunch of "random" numbers operations with my logic, e.g. generating a number from 0 to 1 which would indicate which age-range should be used, and then generate a new number to decide what specific age within this given range. But this would be a very ugly chain of hard code, and very hard to make adjustments to later.

I'd rather want a way to bundle an "option probability set" with the application. For instance an XML file that would specify the probability for all variable. The file could be loaded into memory at launch to prevent having to read the same file every time a person is instantiated. Unrealistic example to give an idea of what I mean:

```<code>"Person":
    "age":
        0-30: 25%,
        30-40: 50%,
        40-100: 25%
</code>```

The application would use this information to automagically set an age based on the seed, with these given "probability parameters".
Having such a file would drastically decrease the workload for future adjustments of parameters, and would even let me change parameters without having to rebuild the application. But is it viable?

In addition to this, there may be cases where a second parameter could be dependent on the first. An example could be enum Occupation, where certain occupations are more common for certain ages (e.g. 'fast food employee' being more common at younger ages and CEO more common the older they get).

This type of logic seems rather common for certain types of video games, e.g. RTS such as "Civilization", where the game seed would be used to create the map, place its resources and the player spawn locations. It appears to also be used for procedural sandbox games such as Minecraft, where there's a certain probability for biomes. The latter is probably more noise-based, but still, noise would only give an output between 0 and 1, and they somehow derive a certain biome probability from it.

(I will code in C++, but language doesn't matter for the question)

So

What is the optimal/best practice procedure to derive many values at preset probabilities from a single seed?

Can the probabilities be imported from an external file?

Can probabilities be dependent on each other?

答:
It seems you are thinking about a prng with a state, that you can initialize and use exactly once to generate the age value. However, for this purpose, hash would be also good: it also produces a pseudo-random number with uniform distribution on the given output space. If there is any need to generate a sequence of random numbers from a single seed, then a random number engine would be more useful.

XML, JSON and other formats can be read in using 3rd party libraries in C++. However, if the difficulty level is at storing age ranges and probability, for portability and dependency management it can be better to implement the parser yourself.

If I am correct, the age distribution is occupation-dependent. Once you derive the correct distribution for the occupation (either explicitly defined in a settings file, like in point 2 or by calculating it using a formula), you can get the right age-distribution from a single pseudo random number generated by the hash function.

Body:
I have a bunch of classes that I'd like to instantiate using seeds. Such a class would only have one constructor; taking in a single argument, the seed. A very simple pseudo example could be:

class Person {
    int age;
    Person(uint32 seed){
        age = deriveAgeFromSeed(seed);
    }
}

If I instantiate a Person with a random given seed, e.g. 123456789, it should evaluate to a Person with a specific age, e.g 30. The same seed will always generate the same person (same age).

To achieve this specific example, I could use a regular random-number-generator and use my seed as its seed to generate a random number between e.g. 0-100 for age.
However, I may not want it to be linearly random. Maybe I'd want a 50% chance that the age is in the range of 30-40. I guess I could chain a bunch of "random" numbers operations with my logic, e.g. generating a number from 0 to 1 which would indicate which age-range should be used, and then generate a new number to decide what specific age within this given range. But this would be a very ugly chain of hard code, and very hard to make adjustments to later.

I'd rather want a way to bundle an "option probability set" with the application. For instance an XML file that would specify the probability for all variable. The file could be loaded into memory at launch to prevent having to read the same file every time a person is instantiated. Unrealistic example to give an idea of what I mean:

"Person":
    "age":
        0-30: 25%,
        30-40: 50%,
        40-100: 25%

The application would use this information to automagically set an age based on the seed, with these given "probability parameters".
Having such a file would drastically decrease the workload for future adjustments of parameters, and would even let me change parameters without having to rebuild the application. But is it viable?

In addition to this, there may be cases where a second parameter could be dependent on the first. An example could be enum Occupation, where certain occupations are more common for certain ages (e.g. 'fast food employee' being more common at younger ages and CEO more common the older they get).

This type of logic seems rather common for certain types of video games, e.g. RTS such as "Civilization", where the game seed would be used to create the map, place its resources and the player spawn locations. It appears to also be used for procedural sandbox games such as Minecraft, where there's a certain probability for biomes. The latter is probably more noise-based, but still, noise would only give an output between 0 and 1, and they somehow derive a certain biome probability from it.

(I will code in C++, but language doesn't matter for the question)

So

What is the optimal/best practice procedure to derive many values at preset probabilities from a single seed?

Can the probabilities be imported from an external file?

Can probabilities be dependent on each other?


问:
How to add show more and show less options for attributed text in Flutter App?
In my application I need to show options for Show more and Show less for the attributed text. If there is the simple Text then I could manage the things by using .subString function for first few characters and full text.

But here in my case I am using flutter_html lib. Here if I take data using .subString then attributed text getting disturbed which creates wrong output.

For consideration my text is as mentioned below:

The system requirements are\r\n        :
\r\n
An internet connection – broadband wired or wireless (3G or 4G/LTE)
\r\n
Speakers and a microphone (required in case of interactive sessions) – Built-in, USB plug-in, or wireless Bluetooth
\r\n
A webcam or HD webcam - built-in, USB plug-in (required in case of interactive sessions)
\r\n
CLICK HERE to view the System Requirements for Zoom.
\r\n

Consider the image as mentioned below:

Is there something else can be done here to achieve this feature without using .subString feature!!??

答:
Solution 1 :
You can try https://pub.dev/packages/readmore , this plugin.
A Flutter plugin that allow expand and collapse text.

Solution 2 :
Flutter: How to hide or show more text within certain length


问:
how to translate angular datePipe's dates with moment.js?
I  have this version of packages:

```<code>"@angular/cdk": "^11.2.13",
"@ngx-translate/core": "^13.0.0",
"@angular/material-moment-adapter": "^12.2.9",
"moment": "^2.29.1",
"@types/moment": "^2.13.0",
</code>```

I am using angular datePipe  | date: 'MMM d, y'   format,  which is mediumDate.   I want  to  translate  it  to other language.  For  example  Instead of Jun 15, 2015 , I want  to  be  'ივნ 15,2015".

shared.module.ts

```<code>export function culture() {
    const locale = localStorage.getItem('culture');
    return locale ? locale.substr(0, locale.indexOf('-')) : 'ka';
}
 providers: [
        { provide: MAT_DATE_LOCALE, useValue: culture() },
        { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
        { provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS }
    ]
</code>```

app.module.ts

```<code>moment.locale(culture());
</code>```

Also I use   angular material datepicker  and  it  translates.

答:
I added in the  shared  module

```<code>import ka from '@angular/common/locales/ka';
registerLocaleData(ka);
providers: [
   DatePipe,
]
</code>```

and  Add alseo  localized date pipe  which transform  dates according to currentLanguage.

there is  solution     linksolution

Body:
I  have this version of packages:

"@angular/cdk": "^11.2.13",
"@ngx-translate/core": "^13.0.0",
"@angular/material-moment-adapter": "^12.2.9",
"moment": "^2.29.1",
"@types/moment": "^2.13.0",

I am using angular datePipe  | date: 'MMM d, y'   format,  which is mediumDate.   I want  to  translate  it  to other language.  For  example  Instead of Jun 15, 2015 , I want  to  be  'ივნ 15,2015".

shared.module.ts

export function culture() {
    const locale = localStorage.getItem('culture');
    return locale ? locale.substr(0, locale.indexOf('-')) : 'ka';
}
 providers: [
        { provide: MAT_DATE_LOCALE, useValue: culture() },
        { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
        { provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS }
    ]

app.module.ts

moment.locale(culture());

Also I use   angular material datepicker  and  it  translates.

Body:
I added in the  shared  module

import ka from '@angular/common/locales/ka';
registerLocaleData(ka);
providers: [
   DatePipe,
]

and  Add alseo  localized date pipe  which transform  dates according to currentLanguage.

there is  solution     linksolution


问:
We made it reliable. What's next? Usability?
I'm working in a small development group. We are building and improving our product.

Half a year ago we couldn't think about higher characteristics, such as usability, because we had so many problems with our product. Many bugs, high technical debt, low performance and other problems kept us from being able to focus on usability.

With time we've improved our process substantially. What we've done:

Real Agile iterations

Continuous integration

Testing(unit-tests, functional Smoke tests, performance)

Code quality is 'good'

Painless deployment process

So we are now producing stable, reliable releases. The following quote (paraphrased) describes our current situation:

first - make it work; after that, make it reliable; after that, make it usable

We are geeks, so we can't 'make' a great UI by ourselves.
So what should we do? What direction can you recommend?
Maybe we should hire Usability experts part-time or full-time?
How can we explain the importance of Usability to our stakeholders?
How do we convince them that this is useful?

答:
What does it do for your users? What do they think about the usability?  Maybe it's not an ssue for them.

Make it more valueable to your users. Deliver more business value. Help your customers getter a better return on their investment. Do this by making it do more of what they need it to do, to do it better (more accurately, more quickly, more reliably more useably), or to do it at lower cost (less infrastructure needed to run it, reduced maintenance costs because you improved reliability), more flexibly (deals with their business changes)...

Lots of dimensions which do connect with the technical ones you refer to (usability reliabilty stability etc). But paying customers normally care about their business needs/features, not your technical ones that deliver them.

Go talk to your users (or potential users)

OwnerDisplayName: Fedyashev Nikita

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Gortok

OwnerDisplayName: Paul


问:
Can't remove navigation drawer header left padding?
I want to remove the left padding that the navigation drawer adds automatically. I tried adding

```<code>android:padding="0dp"
</code>```

and margins of 0dp to the elements but there seems to be a little bit of space on the left of the drawer header. Is there something I'm missing?

Here's the header code

```<code><androidx.appcompat.widget.Toolbar
        android:id="@+id/report_toolbar"
        android:layout_height="@dimen/toolbar_height"
        android:layout_width="match_parent"
        android:background="@color/accent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <ImageButton
                android:id="@+id/navigation_fllesh_button"
                android:layout_width="@dimen/side_button_size"
                android:layout_height="@dimen/side_button_size"
                android:background="@android:color/transparent"
                android:src="@drawable/ic_foreground_logo"
                android:contentDescription="@string/drawer_closing_button_description"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:tint="@color/white" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="20dp"
                android:fontFamily="@font/addingtoncf_bold"
                android:gravity="center"
                android:text="@string/app_title"
                android:textColor="@color/white"
                android:textSize="18sp"
                app:layout_constraintBottom_toBottomOf="@+id/navigation_fllesh_button"
                app:layout_constraintStart_toEndOf="@+id/navigation_fllesh_button"
                app:layout_constraintTop_toTopOf="@+id/navigation_fllesh_button" />
        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.appcompat.widget.Toolbar>
</code>```

and here is the extra padding:

This is the design view

And this is the blueprint view

答:
As you want to remove the toolbar margin from left try to remove it with the help of contentinsert padding to, by setting 0dp.

```<code>android:contentInsetLeft="0dp"
android:contentInsetStart="0dp"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
android:contentInsetRight="0dp"
android:contentInsetEnd="0dp"
app:contentInsetRight="0dp"
app:contentInsetEnd="0dp"
android:paddingLeft="0dp"
</code>```

If still the problem still there then set contentInsetStartWithNavigation to zero

```<code>app:contentInsetStartWithNavigation="0dp"
</code>```

Hope it will solve your issue.

Body:
I want to remove the left padding that the navigation drawer adds automatically. I tried adding

android:padding="0dp"

and margins of 0dp to the elements but there seems to be a little bit of space on the left of the drawer header. Is there something I'm missing?

Here's the header code

<androidx.appcompat.widget.Toolbar
        android:id="@+id/report_toolbar"
        android:layout_height="@dimen/toolbar_height"
        android:layout_width="match_parent"
        android:background="@color/accent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <ImageButton
                android:id="@+id/navigation_fllesh_button"
                android:layout_width="@dimen/side_button_size"
                android:layout_height="@dimen/side_button_size"
                android:background="@android:color/transparent"
                android:src="@drawable/ic_foreground_logo"
                android:contentDescription="@string/drawer_closing_button_description"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:tint="@color/white" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="20dp"
                android:fontFamily="@font/addingtoncf_bold"
                android:gravity="center"
                android:text="@string/app_title"
                android:textColor="@color/white"
                android:textSize="18sp"
                app:layout_constraintBottom_toBottomOf="@+id/navigation_fllesh_button"
                app:layout_constraintStart_toEndOf="@+id/navigation_fllesh_button"
                app:layout_constraintTop_toTopOf="@+id/navigation_fllesh_button" />
        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.appcompat.widget.Toolbar>

and here is the extra padding:

This is the design view

And this is the blueprint view

Body:
As you want to remove the toolbar margin from left try to remove it with the help of contentinsert padding to, by setting 0dp.

android:contentInsetLeft="0dp"
android:contentInsetStart="0dp"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
android:contentInsetRight="0dp"
android:contentInsetEnd="0dp"
app:contentInsetRight="0dp"
app:contentInsetEnd="0dp"
android:paddingLeft="0dp"

If still the problem still there then set contentInsetStartWithNavigation to zero

app:contentInsetStartWithNavigation="0dp"

Hope it will solve your issue.


问:
No HTTP resource was found that matches the request URI hen revoking grants
I have written a function to revoke grants issued for a boundlock as shown in the code snipped below:
For context, I first run a query to get all grants, and then use the ip
UserID to get the specific grant that I want to revoke:

```<code>  async revokeGrant (user) {
const token = await this.getAuthorizationCodeToken(this.refreshToken)
try {
  const { data: allGrants } = await axios.get(
    `${this.baseUrl}/owners/${this.operatorAccountId}/grants`,
    {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    }
  )
  const targetGrant = allGrants.find(grant => grant.contact.ipUserId === user.userId)
  // revoke grant after getting it from above
  const revokeResponse = await axios.post(
    `${this.baseUrl}/owners/${this.operatorAccountId}/grants/${targetGrant.id}/revoke`,
    {
      dryRun: true
    },
    {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    }
  )
  console.log('revokeResponse:', revokeResponse)
} catch (error) {
  throw errors.customError(
    error.response.data,
    platform.responseCodes.InternalServer,
    'Device Error',
    false
  )
}
</code>```

}

I however keep running into an error:

```<code>      Message: "No HTTP resource was found that matches the request URI 'https://tapkey-prod-main-rs.azurewebsites.net/api/v1/owners/*********/grants/*********/revoke'."
    }
  },
  isAxiosError: true,
  toJSON: [Function]
}
</code>```

答:
For revoking a grant the dryRun query parameter has to be added:
https://tapkey-prod-main-rs.azurewebsites.net/api/v1/owners/*********/grants/*********/revoke?dryRun=false

For more details please have a look at
https://developers.tapkey.io/openapi/tapkey_management_api_v1/#/Grants/Grants_RevokeById

Info:
The dryRun parameter is required. If omitted, the request will fail.

Please don't use tapkey-prod-main-rs.azurewebsites.net as baseUri as this is not a public hostname and might removed or changed without any notice.

Body:
I have written a function to revoke grants issued for a boundlock as shown in the code snipped below:
For context, I first run a query to get all grants, and then use the ip
UserID to get the specific grant that I want to revoke:

  async revokeGrant (user) {
const token = await this.getAuthorizationCodeToken(this.refreshToken)
try {
  const { data: allGrants } = await axios.get(
    `${this.baseUrl}/owners/${this.operatorAccountId}/grants`,
    {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    }
  )
  const targetGrant = allGrants.find(grant => grant.contact.ipUserId === user.userId)
  // revoke grant after getting it from above
  const revokeResponse = await axios.post(
    `${this.baseUrl}/owners/${this.operatorAccountId}/grants/${targetGrant.id}/revoke`,
    {
      dryRun: true
    },
    {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    }
  )
  console.log('revokeResponse:', revokeResponse)
} catch (error) {
  throw errors.customError(
    error.response.data,
    platform.responseCodes.InternalServer,
    'Device Error',
    false
  )
}

}

I however keep running into an error:

      Message: "No HTTP resource was found that matches the request URI 'https://tapkey-prod-main-rs.azurewebsites.net/api/v1/owners/*********/grants/*********/revoke'."
    }
  },
  isAxiosError: true,
  toJSON: [Function]
}


答:
Your code, document.getElementsByClassName('ads-here').style.display = "none";, is incorrect because getElementsByClassName returns an HTMLCollection, not an Element. You will have to loop through the result of document.getElementsByClassName('ads-here') and set their style.display to "none". Example:

for (const element of document.getElementsByClassName('ads-here')) {
    element.style.display = "none";
}
```

Title: How to execute some code based on ip address in javascript or jQuery?


问:
How to find url along with host
I need to know the current route along with host how can I find out?
I tried but could not find the accurate answer.

Can anyone help me?

答:
You can use

```<code>request.host  # for getting host
request.url # for getting complete url
</code>```

See ActionDispatch::Http::URL API for more details.

Title: How to find url along with host

Body:
You can use

request.host  # for getting host
request.url # for getting complete url

See ActionDispatch::Http::URL API for more details.


问:
StoreKit 2 subscription status empty on WatchOS
I have StoreKit 2 code that works on iOS 15, but fails in WatchOS 8.  I'm making a standalone WatchOS app that has a subscription.  I took the code that fails and created an iOS app, where it works fine.  I'm testing with the simulated Store in Xcode 13.  The purchase works fine, and I can see the transaction in the Xcode list of StoreKit Transactions.  When I run the app a second time, the iOS app gets the subscription status, but the WatchOS app gets back an empty status array.

```<code>await requestProducts()
guard let product = subscriptions.first else { print("No Subscriptions"); return }
guard let sub = product.subscription else { print("Not Subscription",product.id); return }
let statuses = try await sub.status
</code>```

requestProducts() gets the subscription products (subscriptions) just fine on both iOS and WatchOS.  On iOS, the async call to get the subscription status array (sub.status) works.  On WatchOS, it returns an empty array.  Any idea why, or how to fix it?

答: I created an issue in Apple's Feedback Assistant and they corrected it for the WatchOs 8.5. Right now is in beta, I tried it and it works perfectly. If you want to give it a try, download Xcode 13 Beta.</p>

Body:
I have StoreKit 2 code that works on iOS 15, but fails in WatchOS 8.  I'm making a standalone WatchOS app that has a subscription.  I took the code that fails and created an iOS app, where it works fine.  I'm testing with the simulated Store in Xcode 13.  The purchase works fine, and I can see the transaction in the Xcode list of StoreKit Transactions.  When I run the app a second time, the iOS app gets the subscription status, but the WatchOS app gets back an empty status array.

await requestProducts()
guard let product = subscriptions.first else { print("No Subscriptions"); return }
guard let sub = product.subscription else { print("Not Subscription",product.id); return }
let statuses = try await sub.status

requestProducts() gets the subscription products (subscriptions) just fine on both iOS and WatchOS.  On iOS, the async call to get the subscription status array (sub.status) works.  On WatchOS, it returns an empty array.  Any idea why, or how to fix it?


问:
Calculating time difference between events
I have Logon & Logoff events coming from winlogbeat.
I looking for a way to match the LogonID field between those events, and than calculate the timestamp time difference.
Could this be achieved without using logstash filters?

For example:
how can I combine this 3 queries and return the timestamp as well?
than maybe I can calculate the difference.

GET /winlogbeat-7.14.0-2022.02.03-000001/_search
{
  "query": {
    "match_all": {}
  },
 "aggs": {
    "bulks": {
  "terms": {
    "field": "winlog.event_data.TargetLogonId",
    "size": 10
  },
  "aggs": {
    "orders": {
      "top_hits": {
        "size": 10
          }
        }
      }
    }
  }
}
 GET /winlogbeat-7.14.0-2022.02.03-000001/_search
{
   "query":{
      "match" : {
         "winlog.event_id":"4624"
      }
   }
}
GET /winlogbeat-7.14.0-2022.02.03-000001/_search
{
   "query":{
      "match" : {
         "winlog.event_id":"4634"
      }
   }
}
```

答:
I will suggest to check this POST which have all the example like using query, using script_field, using scripted_metric aggregation, elapsed logstash filter etc.

Below is exmaple using scripted_metric:

{
  "size": 0,
  "aggs": {
    "d_ids": {
      "terms": {
        "field": "name.keyword",
        "size": 10
      },
      "aggs": {
        "duration": {
          "scripted_metric": {
            "map_script": "if (doc.type.value == \"stop\") { params._agg.end = doc.eventTime.value; } else { params._agg.start = doc.eventTime.value; }",
            "reduce_script": "long start = 0; long end = 0; for(h in params._aggs) { if(h.start != null) { start = h.start; } if (h.end != null) { end = h.end; } } return (end - start);"
          }
        }
      }
    }
  }
}
```


问:
My message in assembly when compiled does not display
I'm on Windows 11 in 64 bits and I wrote this code in assembly a64 but after being compiled and linked (with nasm and then ld) it just wait 3sec average and just stop :

```<code>bits 64

section .data
    message db 'Hello World !', 10

section .text
    global _start
    _start:
        mov rax, 1
        mov rdi, 1
        mov rsi, message
        mov rdx, 13+1
        syscall

        mov rax, 60
        mov rdi, 0
        syscall
</code>```

nasm command typed in powershell : nasm -f win64 file.asm -o file.o

then ld command : ld file.o -o file.exe

When I start this file in powershell it just wait 3 sec and stop. Same for cmd.

It's a test program for my compiler to see if it works and I don't know if I didn't write correctly the code or if those compiler or linker don't work on Win 11.

Note : also my processsor is an Intel

答:
Two possibilities:
1.
"The linux syscalls are not going to work on Windows".

Try it on Linux.

2.syscall instruction use MSR regsisters as target.Traditional eax syscall-number will not work.

Try replace "syscall" with "int 0x80"

Please provide more infomation

Body:
I'm on Windows 11 in 64 bits and I wrote this code in assembly a64 but after being compiled and linked (with nasm and then ld) it just wait 3sec average and just stop :

bits 64

section .data
    message db 'Hello World !', 10

section .text
    global _start
    _start:
        mov rax, 1
        mov rdi, 1
        mov rsi, message
        mov rdx, 13+1
        syscall

        mov rax, 60
        mov rdi, 0
        syscall

nasm command typed in powershell : nasm -f win64 file.asm -o file.o

then ld command : ld file.o -o file.exe

When I start this file in powershell it just wait 3 sec and stop. Same for cmd.

It's a test program for my compiler to see if it works and I don't know if I didn't write correctly the code or if those compiler or linker don't work on Win 11.

Note : also my processsor is an Intel


问:
How can I move an element inside a flex div to the right?
i'm trying to move these bars to the right next to the logout button.

This is the current style.

.p-menubar-button {
    display: none;
    cursor: pointer;
    align-items: center;
    justify-content: center;
}
```

I have tried to align-content: flex-end but it doesn't move it.

This is what I'm trying to achieve

答:
```<code>.p-menubar-button {
    display: none;
    cursor: pointer;
    align-items: center;
    justify-content: center;
    margin-left: 18cm;
}
</code>```

Body:
i'm trying to move these bars to the right next to the logout button.

This is the current style.

.p-menubar-button {
    display: none;
    cursor: pointer;
    align-items: center;
    justify-content: center;
}

I have tried to align-content: flex-end but it doesn't move it.

This is what I'm trying to achieve


问:
how can I find ram size of some mobile phones?
I'm going to create a memory consuming j2me mobile application. The problem is that I don't know average ram size of usual mobile phones and how much memory I can use?

Do you know how can I find ram size of some specific phone model (note that I don't have all of these models in my hand)? Or do you have any idea about keywords I should search for?

As an example searching for Sony Ericsson T700 Ram size didn't result to anything.

答:
So, you want to know what device have how much total memory?

I don't know if there's online service that allow you to query it.
However, if you are willing to do some processing, Enough Software (creator of J2MEPolish) have open source device database that contains total memory information.

Just go to http://devices.enough.de/interactivedb/searchdevices.faces and download current stable devices.xml file. You'll find 3 files. Look at devices.xml and you'll find something like this:

```<code><capability name="totalmemory" value="3550208" />
</code>```

There's also devices database called WURFL. However, I don't have time to check if their database contain TotalMemory information.

Hope that helped.

Body:
So, you want to know what device have how much total memory?

I don't know if there's online service that allow you to query it.
However, if you are willing to do some processing, Enough Software (creator of J2MEPolish) have open source device database that contains total memory information.

Just go to http://devices.enough.de/interactivedb/searchdevices.faces and download current stable devices.xml file. You'll find 3 files. Look at devices.xml and you'll find something like this:

<capability name="totalmemory" value="3550208" />

There's also devices database called WURFL. However, I don't have time to check if their database contain TotalMemory information.

Hope that helped.


问:
Add new value to existing value in C# Console app
I'm new to c# console and currently have a Console application which asks users to buy tickets, after selecting the tickets and amount, the app shows the total price and asks the user if they want to add more tickets, if the users enters y, they can add more tickets, how can I add the new total price with the existing total price?

The code works if I press N first time, but I'm not sure what to put to after pressing N the second, or third time.

Any help is appreciated!

答:
If I understood your problem correctly you just want to add a value to totalprice in every iteration.

This can be done in two different ways.

First you nedd to initialize totalprice with 0.

totalprice =0;
```
<p>Then everytime you want to add something to totalprice you either assign the value directly to it  with:</p>
```totalprice = totalprice + (subTotal * ADDITIONAL_TAX) + subTotal;
```
<p>Or the nicer solution. You use the += Operator. The += Operator is essentially a shortform for what I did above.</p>
```totalprice += (subTotal * ADDITIONAL_TAX) + subTotal;
```

Body:
If I understood your problem correctly you just want to add a value to totalprice in every iteration.

This can be done in two different ways.

First you nedd to initialize totalprice with 0.

totalprice =0;

Then everytime you want to add something to totalprice you either assign the value directly to it  with:

totalprice = totalprice + (subTotal * ADDITIONAL_TAX) + subTotal;

Or the nicer solution. You use the += Operator. The += Operator is essentially a shortform for what I did above.

totalprice += (subTotal * ADDITIONAL_TAX) + subTotal;


问:
Python Script has no effect on Apache Ant Build
I have an ant build file: build.xml, with an existing build target: Rebuild-ALL. that I run from ant eclipse plugin.

The build file contains paths referenced from another file: file.def.

I would like to create a new build target that builds from another path.
I started by doing the following:

Creating a python script that modifies the path in file.def.

I added this script to a target: Change-Paths.

I created a copy of the existing build target: Copy1-Rebuild-ALL

I added my Change-Paths target to the depends of the Copy-Rebuild-ALL.

I also created a second python script to revert the path change in file.def and repeated steps 2 to 4 to have another 2 targets: Revert-Paths and Copy2-Rebuild-ALL.

The problem is that the second build target still takes the path of the first build target even though I can see on my editor that the python script has successfully replaced the paths.

After executing the second target 3 consecutive times it works fine so is there maybe a refresh or a delay I can add to fix this ?

I tried using ant calls instead of depends but still the same issue occurs.

I am still new to ant and build files in general so let me know if there's a better way to do this.

Here is a an example to my build.xml file:

```<code><project name="Build" xmlns:if="ant:if" xmlns:unless="ant:unless" default="REBUILD_ALL" basedir="${ant.file}/../../../..">

<property file="${TOOLS.PATH}/Compiler/file.def" />

<property name="COMPILER"          value="${VENDOR.COMPILER}" />

<target name="Change-Paths">
    <exec executable="${python.exe}" dir="${basedir}" failonerror="true" inputstring="${TOOLS.PATH}/Compiler/file.def">
        <arg line="${SCRIPTS.PATH}/Change_Paths.py" />
    </exec>
</target>

<target name="Copy1-Rebuild-ALL" description="Build all files from the project to output executable files" depends="Change-Paths, BuildMakesParallel, LINK_ALL">
</target>

<target name="Revert-Paths">
    <exec executable="${python.exe}" dir="${basedir}" failonerror="true" inputstring="${TOOLS.PATH}/Compiler/file.def">
        <arg line="${SCRIPTS.PATH}/Revert_Paths.py" />
    </exec>
</target>

<target name="Copy2-Rebuild-ALL" description="Build all files from the project to output executable files" depends="Revert-Paths, BuildMakesParallel, LINK_ALL">
</target>

</project>
</code>```

Also here is an example to file.def:

```<code>VENDOR_PATH      = c:/VENDOR/toolchains/compiler_name/v1
VENDOR.COMPILER       =    ${VENDOR_PATH}/bin/compiler_name-gcc.exe
</code>```

答:
I permanently added the new path in file.def and added a new property in build.xml to hold this path as follows:

```<code>VENDOR_PATH_2      = c:/VENDOR/toolchains/compiler_name/v2
VENDOR.COMPILER_2       =    ${VENDOR_PATH_2}/bin/compiler_name-gcc.exe
</code>```

Now the python script will only replace the property name in the macro that compiles files in the build target and it works as expected.

Body:
I have an ant build file: build.xml, with an existing build target: Rebuild-ALL. that I run from ant eclipse plugin.

The build file contains paths referenced from another file: file.def.

I would like to create a new build target that builds from another path.
I started by doing the following:

Creating a python script that modifies the path in file.def.

I added this script to a target: Change-Paths.

I created a copy of the existing build target: Copy1-Rebuild-ALL

I added my Change-Paths target to the depends of the Copy-Rebuild-ALL.

I also created a second python script to revert the path change in file.def and repeated steps 2 to 4 to have another 2 targets: Revert-Paths and Copy2-Rebuild-ALL.

The problem is that the second build target still takes the path of the first build target even though I can see on my editor that the python script has successfully replaced the paths.

After executing the second target 3 consecutive times it works fine so is there maybe a refresh or a delay I can add to fix this ?

I tried using ant calls instead of depends but still the same issue occurs.

I am still new to ant and build files in general so let me know if there's a better way to do this.

Here is a an example to my build.xml file:

<project name="Build" xmlns:if="ant:if" xmlns:unless="ant:unless" default="REBUILD_ALL" basedir="${ant.file}/../../../..">

<property file="${TOOLS.PATH}/Compiler/file.def" />

<property name="COMPILER"          value="${VENDOR.COMPILER}" />

<target name="Change-Paths">
    <exec executable="${python.exe}" dir="${basedir}" failonerror="true" inputstring="${TOOLS.PATH}/Compiler/file.def">
        <arg line="${SCRIPTS.PATH}/Change_Paths.py" />
    </exec>
</target>

<target name="Copy1-Rebuild-ALL" description="Build all files from the project to output executable files" depends="Change-Paths, BuildMakesParallel, LINK_ALL">
</target>

<target name="Revert-Paths">
    <exec executable="${python.exe}" dir="${basedir}" failonerror="true" inputstring="${TOOLS.PATH}/Compiler/file.def">
        <arg line="${SCRIPTS.PATH}/Revert_Paths.py" />
    </exec>
</target>

<target name="Copy2-Rebuild-ALL" description="Build all files from the project to output executable files" depends="Revert-Paths, BuildMakesParallel, LINK_ALL">
</target>

</project>

Also here is an example to file.def:

VENDOR_PATH      = c:/VENDOR/toolchains/compiler_name/v1
VENDOR.COMPILER       =    ${VENDOR_PATH}/bin/compiler_name-gcc.exe

Body:
I permanently added the new path in file.def and added a new property in build.xml to hold this path as follows:

VENDOR_PATH_2      = c:/VENDOR/toolchains/compiler_name/v2
VENDOR.COMPILER_2       =    ${VENDOR_PATH_2}/bin/compiler_name-gcc.exe

Now the python script will only replace the property name in the macro that compiles files in the build target and it works as expected.


问:
VS 2010 SDK. Templates
If you try and create an MVC3 project, you’ll see that you have an ability to add Controller or View with rc. And context menu you get on Controller folder with rc will magically suggest to add Controller while on the Views you’ll be suggested to add View.

As I understand, to achieve this I need to bind somehow 4 things. Project template, Item template, T4 templates (used to generate Contoller class or View) and a wizard lieing between T4 and Intem template (within WizardExtension section in Item Template).

How to have all these goods MVC3 project has for a custom template? I couldn’t dig how to bind those 4 things. Maybe somewhere in msdn there is an article I missed (I looked at “Visual Studio Templates” but that did not help much in understanding how to get to my goal). Or maybe someone had a nice experience doing something similar.

P.s. I’m using VS 2010 SDK SP1 Experimental Instance

答:
The functionality you see in MVC 3 projects is implemented as follows:

MVC 3 projects are specially marked using an MVC 3 project type GUID (you can see it in a project's csproj file). The presence of this GUID triggers Visual Studio to load the MVC Tools VSPackage. The VSPackage is responsible for adding commands and other UI elements (e.g. the Add View button) that become active depending on what you select in your project. These commands invoke dialogs to gather user input which is then used to instantiate a T4 template host and invoke the template.

The VS item templates and template wizards only come into play when you try to add a view using the Add New Item dialog.

Overall creating a VSPackage is a pretty complicated subject. A good place to get started is here: http://msdn.microsoft.com/en-us/vstudio/ff677564.

Title: VS 2010 SDK. Templates


问:
Add CASE statement column to existing GBQ table
Pretend I have a GBQ table:

```<code>SELECT
'city_A' AS city,
15 AS score
UNION ALL
SELECT
'city_A' AS city,
17 AS score
UNION ALL
SELECT
'city_B' AS city,
8 AS score
</code>```

I want to add new column with CASE statement, like:

```<code>CASE
    WHEN 'city_A' THEN'LA'
    WHEN 'city_B' THEN 'PH'
    ELSE NULL END AS iso_code
</code>```

How to add/generate it ? With INSERT I only can insert blank column specifying all constraints, ain't I ?

答:
You want an update here.  Assuming your table already have an iso_code column, then use:

UPDATE yourTable
SET iso_code = CASE city WHEN 'city_a' THEN 'LA'
                         WHEN 'city_b' THEN 'PH' END
WHERE city IN ('city_a', 'city_b');
```

That being said, your iso_code column really feels like it could be a generated column, if BigQuery would support that.

Body:
Pretend I have a GBQ table:

SELECT
'city_A' AS city,
15 AS score
UNION ALL
SELECT
'city_A' AS city,
17 AS score
UNION ALL
SELECT
'city_B' AS city,
8 AS score

I want to add new column with CASE statement, like:

CASE
    WHEN 'city_A' THEN'LA'
    WHEN 'city_B' THEN 'PH'
    ELSE NULL END AS iso_code

How to add/generate it ? With INSERT I only can insert blank column specifying all constraints, ain't I ?

Body:
You want an update here.  Assuming your table already have an iso_code column, then use:

UPDATE yourTable
SET iso_code = CASE city WHEN 'city_a' THEN 'LA'
                         WHEN 'city_b' THEN 'PH' END
WHERE city IN ('city_a', 'city_b');

That being said, your iso_code column really feels like it could be a generated column, if BigQuery would support that.


问:
Expo, React Native Async Storage resets after hot reload?
Im developing my own little privat Expo, React Native app using the Expo SDK 32.0.0, and im currently building a auth flow where i get a JWT token through my graphql endpoint and then stores this in AsyncStorage.

I do a log in, everything works i get a token in the async storage, i get redirected as i should to the new stack, then i do a few changes in my code i save it and the app hot reloads, then it when it checks if i have a token it says its undefined and then passes my back to the sign in flow.

So my question is, does the async storage reset after hot reload or is there something im missing?

Retrival of token after it have been set.

componentDidMount = async () => {
    const StoredAuth = await AsyncStorage.getItem(Config.STORAGE_AUTH_KEY)
    this.props.navigation.navigate(StoredAuth ? 'App' : 'Auth');
  }
```

答:
Use expo-secure-store instead of async storage.

https://docs.expo.dev/versions/latest/sdk/securestore/


问:
Filter a array in javascript
```<code>[{"1":"A"},{"2":"A"},{"3":"B"},{"4":"A"},{"5":"C"},{"6":"B"},{"7":"B"}]
</code>```

This is a array where first element is id and second is user. I have to filter this array according to user like-
If user is 'A' then array will be [1,2,4]
If user is 'B' then array will be [3,7]

How to do this in javascript? Do i need to use map or filter method?

答:
My idea is, you could try to create a function to filter which user you want.
Here is my code example you can try:

let userData = [{"1":"A"},{"2":"A"},{"3":"B"},{"4":"A"},{"5":"C"},{"6":"B"},{"7":"B"}];

function filterByUser(user) {
    let dataResult = [];
    userData.forEach((data) => {
        if (Object.values(data)[0] == user){
            dataResult.push(Object.keys(data)[0]);
        }
    })
    return dataResult;
}

// If user is A will get [1,2,4]
console.log(filterByUser('A'))

// If user is B will get [3,6,7]
console.log(filterByUser('B'));```

Title: Filter a array in javascript

Body:
[{"1":"A"},{"2":"A"},{"3":"B"},{"4":"A"},{"5":"C"},{"6":"B"},{"7":"B"}]

This is a array where first element is id and second is user. I have to filter this array according to user like-
If user is 'A' then array will be [1,2,4]
If user is 'B' then array will be [3,7]

How to do this in javascript? Do i need to use map or filter method?


问:
django - create a model that lets you insert multiple values for the same field?
Ok I'm trying to do something which should be very simple in my mind but I am probably missing some SQL or django admin knowledge to get to it.
Say I have a simple model such as

```<code>class Book(models.Model):
    title = models.CharField(max_length = 50)
    review = models.TextField()
</code>```

and I want the 'review' field in the admin site to have a little plus sign to add more reviews to the same model instance for the template to iterate through them.

I know I could create a m2m field for the reviews and it would give me just that, but I would rather like that those extra reviews could be filled from the same page without popups (for my helpless users i would like to keep it as WSIWYG as possible, since those textfields will be tinyMCE powered), and I wonder if it's really necessary to create an extra model just for a textfield

答: Another option since Django 3.1. could be creating a JSON field and storing multiple values in a key value pair. Although it may not be suitable for all cases but for some that came to this topic it could work. Reference to Django docs https://docs.djangoproject.com/en/3.2/ref/models/fields/#jsonfield</p>

Body:
Ok I'm trying to do something which should be very simple in my mind but I am probably missing some SQL or django admin knowledge to get to it.
Say I have a simple model such as

class Book(models.Model):
    title = models.CharField(max_length = 50)
    review = models.TextField()

and I want the 'review' field in the admin site to have a little plus sign to add more reviews to the same model instance for the template to iterate through them.

I know I could create a m2m field for the reviews and it would give me just that, but I would rather like that those extra reviews could be filled from the same page without popups (for my helpless users i would like to keep it as WSIWYG as possible, since those textfields will be tinyMCE powered), and I wonder if it's really necessary to create an extra model just for a textfield


问:
How to switch external css file based on user input in rshiny?
I am looking to build a dark mode in my application. I realize we can achieve that using bs_theme(), but my application has many more settings in an external css file that do not get read when I use bs_theme().

I want to have 2 separate CSS files, one for light theme and one for dark theme. Based on the user input, the relevant theme file should be loaded in my Rshiny app. Any suggestion on how this could be done?

答:
Assuming your CSS files are named darkmode.css and lightmode.css, and are placed into the www subfolder, you can use renderUI like this:

```<code>library(shiny)

ui <- fluidPage(
  tags$head(
    uiOutput("css")
  ),
  radioButtons("select", "Select mode", c("dark", "light"))
)

server <- function(input, output){

  output[["css"]] <- renderUI({
    cssfile <- paste0(input[["select"]], "mode.css")
    tags$link(rel = "stylesheet", type = "text/css", href = cssfile)
  })

}

shinyApp(ui, server)
</code>```

Body:
Assuming your CSS files are named darkmode.css and lightmode.css, and are placed into the www subfolder, you can use renderUI like this:

library(shiny)

ui <- fluidPage(
  tags$head(
    uiOutput("css")
  ),
  radioButtons("select", "Select mode", c("dark", "light"))
)

server <- function(input, output){

  output[["css"]] <- renderUI({
    cssfile <- paste0(input[["select"]], "mode.css")
    tags$link(rel = "stylesheet", type = "text/css", href = cssfile)
  })

}

shinyApp(ui, server)


问:
NestJS - ValidationPipe in WebsocketGateway returns Internal Server Error
I'm trying to add some validation to my WebSocketGateway in NestJS. Here's the code:

// MessageDTO

import { IsNotEmpty, MinLength } from 'class-validator';

export class MessageDTO {
  @IsNotEmpty()
  username: string;

  @IsNotEmpty()
  @MinLength(10)
  text: string;
}
```

<pre class="lang-js prettyprint-override"><code>// Gateway

import { ValidationPipe, UsePipes } from '@nestjs/common';
import { MessageBody, SubscribeMessage, WebSocketGateway, WsResponse } from '@nestjs/websockets';
import { MessageService } from './message/message.service';
import { MessageDTO } from './message/message.dto';
import { Message } from './message/message.entity';

@WebSocketGateway()
export class AppGateway {
  constructor(private readonly messageService: MessageService) {}

  @UsePipes(new ValidationPipe())
  @SubscribeMessage('message')
  async handleMessage(@MessageBody() dto: MessageDTO): Promise<WsResponse<Message>> {
    const message = await this.messageService.saveMessage(dto);
    return { event: 'message', data: message };
  }
}
</code>```

Now, when I try to send a message that doesn't meet validation rules, it errors out, but the client always receives { status: 'error', message: 'Internal server error'}. Also, Nest logs the error to the console (which I belive should not happen...?):

thing_api | Error: Bad Request Exception
thing_api |     at ValidationPipe.exceptionFactory (/usr/src/app/node_modules/@nestjs/common/pipes/validation.pipe.js:78:20)
thing_api |     at ValidationPipe.transform (/usr/src/app/node_modules/@nestjs/common/pipes/validation.pipe.js:50:24)
thing_api |     at processTicksAndRejections (internal/process/task_queues.js:89:5)
thing_api |     at async resolveParamValue (/usr/src/app/node_modules/@nestjs/websockets/context/ws-context-creator.js:104:31)
thing_api |     at async Promise.all (index 0)
thing_api |     at async pipesFn (/usr/src/app/node_modules/@nestjs/websockets/context/ws-context-creator.js:106:13)
thing_api |     at async /usr/src/app/node_modules/@nestjs/websockets/context/ws-context-creator.js:41:17
thing_api |     at async AppGateway.<anonymous> (/usr/src/app/node_modules/@nestjs/websockets/context/ws-proxy.js:11:32)
thing_api |     at async WebSocketsController.pickResult (/usr/src/app/node_modules/@nestjs/websockets/web-sockets-controller.js:85:24)
```

However, if I use the same DTO and validation pipe in regular controller, it works like a charm - with malformed payload I get properly formatted error message. Can somebody point out what I'm doing wrong?

答:
ValidationPipe got exceptionFactory option so you can just pass a custom factory to it, like:

```<code>@UsePipes(new ValidationPipe({
    exceptionFactory(validationErrors = []) {
        if (this.isDetailedOutputDisabled) {
            return new WsException('Bad request');
        }
        const errors = this.flattenValidationErrors(validationErrors);

        return new WsException(errors);
    }
}))
</code>```

Or extend built-in ValidationPipe

```<code>import {Injectable, ValidationPipe} from '@nestjs/common';
import {WsException} from "@nestjs/websockets";

@Injectable()
export class WSValidationPipe extends ValidationPipe{

  createExceptionFactory() {
    return (validationErrors = []) => {
      if (this.isDetailedOutputDisabled) {
        return new WsException('Bad request');
      }
      const errors = this.flattenValidationErrors(validationErrors);

      return new WsException(errors);
    };
  }

}
</code>```

Body:
I'm trying to add some validation to my WebSocketGateway in NestJS. Here's the code:

// MessageDTO

import { IsNotEmpty, MinLength } from 'class-validator';

export class MessageDTO {
  @IsNotEmpty()
  username: string;

  @IsNotEmpty()
  @MinLength(10)
  text: string;
}

// Gateway

import { ValidationPipe, UsePipes } from '@nestjs/common';
import { MessageBody, SubscribeMessage, WebSocketGateway, WsResponse } from '@nestjs/websockets';
import { MessageService } from './message/message.service';
import { MessageDTO } from './message/message.dto';
import { Message } from './message/message.entity';

@WebSocketGateway()
export class AppGateway {
  constructor(private readonly messageService: MessageService) {}

  @UsePipes(new ValidationPipe())
  @SubscribeMessage('message')
  async handleMessage(@MessageBody() dto: MessageDTO): Promise<WsResponse<Message>> {
    const message = await this.messageService.saveMessage(dto);
    return { event: 'message', data: message };
  }
}

Now, when I try to send a message that doesn't meet validation rules, it errors out, but the client always receives { status: 'error', message: 'Internal server error'}. Also, Nest logs the error to the console (which I belive should not happen...?):

thing_api | Error: Bad Request Exception
thing_api |     at ValidationPipe.exceptionFactory (/usr/src/app/node_modules/@nestjs/common/pipes/validation.pipe.js:78:20)
thing_api |     at ValidationPipe.transform (/usr/src/app/node_modules/@nestjs/common/pipes/validation.pipe.js:50:24)
thing_api |     at processTicksAndRejections (internal/process/task_queues.js:89:5)
thing_api |     at async resolveParamValue (/usr/src/app/node_modules/@nestjs/websockets/context/ws-context-creator.js:104:31)
thing_api |     at async Promise.all (index 0)
thing_api |     at async pipesFn (/usr/src/app/node_modules/@nestjs/websockets/context/ws-context-creator.js:106:13)
thing_api |     at async /usr/src/app/node_modules/@nestjs/websockets/context/ws-context-creator.js:41:17
thing_api |     at async AppGateway.<anonymous> (/usr/src/app/node_modules/@nestjs/websockets/context/ws-proxy.js:11:32)
thing_api |     at async WebSocketsController.pickResult (/usr/src/app/node_modules/@nestjs/websockets/web-sockets-controller.js:85:24)

However, if I use the same DTO and validation pipe in regular controller, it works like a charm - with malformed payload I get properly formatted error message. Can somebody point out what I'm doing wrong?

Body:
ValidationPipe got exceptionFactory option so you can just pass a custom factory to it, like:

@UsePipes(new ValidationPipe({
    exceptionFactory(validationErrors = []) {
        if (this.isDetailedOutputDisabled) {
            return new WsException('Bad request');
        }
        const errors = this.flattenValidationErrors(validationErrors);

        return new WsException(errors);
    }
}))

Or extend built-in ValidationPipe

import {Injectable, ValidationPipe} from '@nestjs/common';
import {WsException} from "@nestjs/websockets";

@Injectable()
export class WSValidationPipe extends ValidationPipe{

  createExceptionFactory() {
    return (validationErrors = []) => {
      if (this.isDetailedOutputDisabled) {
        return new WsException('Bad request');
      }
      const errors = this.flattenValidationErrors(validationErrors);

      return new WsException(errors);
    };
  }

}