问:
How to call business object class from main method?
I have separated my code into business object, access layer as shown below:

```<code>void Main()
{

}

//====================================================================
// Business object
public class ExpenseBO
{
    public void MakeExpense(ExpensePayload payload)
    {
        var trA = new TrAccess();
        var acA = new AcAccess();

        var account = acA.MakeAccount(payload.Account);

        payload.Transaction.Account = account;
        trA.MakeTransaction(payload.Transaction);
    }
}

//----------------------------------------------------------------------------
public class TrAccess
{
    private const string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";

    public void MakeTransaction(T t)
    {
            using (var connection = new NpgsqlConnection(connString))
            {
                connection.Execute(@"INSERT INTO transaction (account_id, amount, date, note)
                                         SELECT a.account_id,@amount, @date, @note
                                         FROM account AS a
                                         WHERE a.account_name = @account_name", new { t.Amount, t.Date, t.Note, a.Account_Name });
            }
    }
}

public class AcAccess
{
    private const string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";

    public void MakeAccount(A a)
    {
        using (var connection = new NpgsqlConnection(connString))
        {
            connection.Execute(@"INSERT INTO account(account_name, type)
                             VALUES(@account_name, @type)", new { account.Account_Name, account.Type });
        }
    }
}

public class T
{
    public int Transaction_Id { get; set; }
    public int Account_Id { get; set; }
    public decimal Amount { get; set; }
    public string Note { get; set; }
    public DateTime Date { get; set; }
}

public class A
{
    public int Account_Id { get; set; }
    public string Account_Name { get; set; }
    public string Type { get; set; }
}

//--------------------------------------------
public class ExpensePayload
{
    public T Transaction { get; set; }
    public A Account { get; set; }
}
</code>```

Now I wanted to call the ExpenseBO class method MakeExpense from the main methods which will create two objects and with them calls TrAccess, AcAccess.

But there is an ExpensePayload class. If I wanted to call ExpenseBO class MakeExpense method in main method, how should I do that? How should I create a ExpensePayload class object and call it in main method?

答:
```<code>  var payl = new ExpensePayload {
     Transaction = // some T,
     Account = // Some A
  }

  var bo = new ExpenseBo();

  bo.MakeExpense(payl);

</code>```

Body:
I have separated my code into business object, access layer as shown below:

void Main()
{

}

//====================================================================
// Business object
public class ExpenseBO
{
    public void MakeExpense(ExpensePayload payload)
    {
        var trA = new TrAccess();
        var acA = new AcAccess();

        var account = acA.MakeAccount(payload.Account);

        payload.Transaction.Account = account;
        trA.MakeTransaction(payload.Transaction);
    }
}

//----------------------------------------------------------------------------
public class TrAccess
{
    private const string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";

    public void MakeTransaction(T t)
    {
            using (var connection = new NpgsqlConnection(connString))
            {
                connection.Execute(@"INSERT INTO transaction (account_id, amount, date, note)
                                         SELECT a.account_id,@amount, @date, @note
                                         FROM account AS a
                                         WHERE a.account_name = @account_name", new { t.Amount, t.Date, t.Note, a.Account_Name });
            }
    }
}

public class AcAccess
{
    private const string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";

    public void MakeAccount(A a)
    {
        using (var connection = new NpgsqlConnection(connString))
        {
            connection.Execute(@"INSERT INTO account(account_name, type)
                             VALUES(@account_name, @type)", new { account.Account_Name, account.Type });
        }
    }
}

public class T
{
    public int Transaction_Id { get; set; }
    public int Account_Id { get; set; }
    public decimal Amount { get; set; }
    public string Note { get; set; }
    public DateTime Date { get; set; }
}

public class A
{
    public int Account_Id { get; set; }
    public string Account_Name { get; set; }
    public string Type { get; set; }
}

//--------------------------------------------
public class ExpensePayload
{
    public T Transaction { get; set; }
    public A Account { get; set; }
}

Now I wanted to call the ExpenseBO class method MakeExpense from the main methods which will create two objects and with them calls TrAccess, AcAccess.

But there is an ExpensePayload class. If I wanted to call ExpenseBO class MakeExpense method in main method, how should I do that? How should I create a ExpensePayload class object and call it in main method?


来源: stackexchange

问:
How to use Next.js Link with multiple children?
How to use Link in Next.js with multiple
 inside this
? I have img tag for Link, paragraph for link , title for link.

Error: Multiple children were passed to  with href of
/article but only one child is supported
https://nextjs.org/docs/messages/link-multiple-children  Open your
browser's console to view the Component stack trace.

```<code><Link href="/article" title="">
      <div >
          <h4>{props.featurename}</h4>
          <a href="/author"><h3>{props.featuredesc}</h3></a>
      </div>
      <div className="img-entry">
          <Image src="/images/more-img.png" width={265} height={290} title="" alt="" />
      </div>
</Link>
</code>```

答:
Use fragments in order to group multiple element under one main child that won't be visible in the tree. (https://reactjs.org/docs/fragments.html#gatsby-focus-wrapper)</p>
```<code>      <Link ***href***="/article" title="">
       <>
        <div >
          <h4>{props.featurename}</h4>
          <a href="/author"><h3>{props.featuredesc}</h3></a>
        </div>
        <div className="img-entry">
          <Image src="/images/more-img.png" width={265} height={290} title="" alt="" />
        </div>
       </>
      </Link>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to use Link in Next.js with multiple
 inside this
? I have img tag for Link, paragraph for link , title for link.

Error: Multiple children were passed to  with href of
/article but only one child is supported
https://nextjs.org/docs/messages/link-multiple-children  Open your
browser's console to view the Component stack trace.

<Link href="/article" title="">

{props.featurename}

{props.featuredesc}

          <Image src="/images/more-img.png" width={265} height={290} title="" alt="" />

</Link>

Body:
Use fragments in order to group multiple element under one main child that won't be visible in the tree. (https://reactjs.org/docs/fragments.html#gatsby-focus-wrapper)

      <Link ***href***="/article" title="">
       <>
        <div >
          <h4>{props.featurename}</h4>
          <a href="/author"><h3>{props.featuredesc}</h3></a>
        </div>
        <div className="img-entry">
          <Image src="/images/more-img.png" width={265} height={290} title="" alt="" />
        </div>
       </>
      </Link>


问:
Count number of ongoing conversations in SQL
How to calculate the number of distinct conversations in the table?

table:

Caller
Receiver

A
B

B
D

C
A

A
C

C
B

D
B

B
A

B
D

in the table above, the conversations are between
A:B, A:C, B:C, B:D.

Therefore, the expected result is 4

答:
We can use the LEAST and GREATEST functions here:

SELECT COUNT(*)
FROM (
    SELECT DISTINCT LEAST(Caller, Receiver),
                    GREATEST(Caller, Receiver)
    FROM yourTable
) t;
```

In the above logic A -> B and B -> A would both be treated as A -> B, and would be counted only once.

Body:
We can use the LEAST and GREATEST functions here:

SELECT COUNT(*)
FROM (
    SELECT DISTINCT LEAST(Caller, Receiver),
                    GREATEST(Caller, Receiver)
    FROM yourTable
) t;

In the above logic A -> B and B -> A would both be treated as A -> B, and would be counted only once.


问:
Why is "a =(b>0)?1:0" better than "if-else" version in CUDA?
Could you tell me why

```<code>a =(b>0)?1:0
</code>```

is better than

```<code>if (b>0)a=1; else a =0;
</code>```

version in CUDA? Please give details. Many thanks.

Yik

答:
I find it easier to read. It's immediately obvious that the purpose of the whole statement is to set the value of a.

The intent is to assign a to one of two values, and the ternary conditional operator syntax lets you have only one a = in your statement.

I think a standard if/else all on one line is ugly (regardless of what it's used for).

ContentLicense: CC BY-SA 3.0

Body:
Could you tell me why

a =(b>0)?1:0

is better than

if (b>0)a=1; else a =0;

version in CUDA? Please give details. Many thanks.

Yik


问:
How to add a row to a Python Pandas dataframe that was generated using the .describe() function
Per the code below, I have created a df with a single column (labeled 'A') of numerical data.

I then use the pandas .describe() function to get summary statistics for the df.

I save the output from the .describe() function to a new dataframe, called df_stats.

I next calculate the percentage of time the data in the original df is positive and save this as 'Percent_Positive'.

I want to add a row to df_stats that is called 'percent_positive' and populates column A in this new row with the value calculated as 'Percent_Positive'.

However, when I do the steps described above per the code below, a new row is added to df_stats (which I want), but a new column is also added to df_stats (which I do not want).  This new column includes NaN values for all rows, other than the final (new) 'percent_positive' row, which includes the 'Percent_Positive' value I calculated previously.

Can someone please tell me how to populate df_stats with the Percent_Positive value without adding a new column to df_stats?  Thank you.

```<code># Import dependencies
import pandas as pd
import numpy as np

# Create df with randomly populated numbers.
df = pd.DataFrame(np.random.randint(-80,100,size=(100, 1)), columns=list('A'))

# Use the .describe function to calculate basic stats on the df.
df_stats = df.describe()

# Create new var to calculate the percentage of time a value in column A is positive.
Percent_Positive = df_stats.loc[df_stats['A'] > 0,'A'].count()/df_stats['A'].count()

# Add new row to df_stats called 'percent_positive' using the Percent_Positive var above.
df_stats = df_stats.append(pd.Series(Percent_Positive, name='percent_positive'))
display(df_stats)
</code>```

答:
Use:

```<code># Import dependencies
import pandas as pd
import numpy as np

# Create df with randomly populated numbers.
df = pd.DataFrame(np.random.randint(-80,100,size=(100, 1)), columns=list('A'))

# Use the .describe function to calculate basic stats on the df.
df_stats = df.describe()

# Create new var to calculate the percentage of time a value in column A is positive.
Percent_Positive = df_stats.loc[df_stats['A'] > 0,'A'].count()/df_stats['A'].count()

# A DF WITH THE SAME COLS.######################################
df_stats = df_stats.append(pd.DataFrame({'A':[Percent_Positive]}, index=['percent_positive']))
display(df_stats)
</code>```

The result:

Body:
Per the code below, I have created a df with a single column (labeled 'A') of numerical data.

I then use the pandas .describe() function to get summary statistics for the df.

I save the output from the .describe() function to a new dataframe, called df_stats.

I next calculate the percentage of time the data in the original df is positive and save this as 'Percent_Positive'.

I want to add a row to df_stats that is called 'percent_positive' and populates column A in this new row with the value calculated as 'Percent_Positive'.

However, when I do the steps described above per the code below, a new row is added to df_stats (which I want), but a new column is also added to df_stats (which I do not want).  This new column includes NaN values for all rows, other than the final (new) 'percent_positive' row, which includes the 'Percent_Positive' value I calculated previously.

Can someone please tell me how to populate df_stats with the Percent_Positive value without adding a new column to df_stats?  Thank you.

# Import dependencies
import pandas as pd
import numpy as np

# Create df with randomly populated numbers.
df = pd.DataFrame(np.random.randint(-80,100,size=(100, 1)), columns=list('A'))

# Use the .describe function to calculate basic stats on the df.
df_stats = df.describe()

# Create new var to calculate the percentage of time a value in column A is positive.
Percent_Positive = df_stats.loc[df_stats['A'] > 0,'A'].count()/df_stats['A'].count()

# Add new row to df_stats called 'percent_positive' using the Percent_Positive var above.
df_stats = df_stats.append(pd.Series(Percent_Positive, name='percent_positive'))
display(df_stats)

Body:
Use:

# Import dependencies
import pandas as pd
import numpy as np

# Create df with randomly populated numbers.
df = pd.DataFrame(np.random.randint(-80,100,size=(100, 1)), columns=list('A'))

# Use the .describe function to calculate basic stats on the df.
df_stats = df.describe()

# Create new var to calculate the percentage of time a value in column A is positive.
Percent_Positive = df_stats.loc[df_stats['A'] > 0,'A'].count()/df_stats['A'].count()

# A DF WITH THE SAME COLS.######################################
df_stats = df_stats.append(pd.DataFrame({'A':[Percent_Positive]}, index=['percent_positive']))
display(df_stats)

The result:


问:
Convert a txt document to a list to a list starting with [[, instead of ['[
I have a .txt document with this type of text:

[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]

(which represents a sentence and the Parts of Speech tags for each word)

I want to have a list of list in python, like this:

[[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]]

But I obtain this:

['[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]\n']

The code I'm using is:

```<code>import io
f=io.open("test.txt", mode="r", encoding="utf-8-sig")
f_list = list(f)
</code>```

How can I avoid the ['[ .... ]\n']  ?

Thank you!

答:
io.open() reads the file as a list of strings so you'll need to evaluate each line of the .txt file to get a list of lists instead of your list of strings.

Here's how you can accomplish that:

```<code>temp = ['[("Vazhdo","verb"),("të","particle"),("ecësh","verb"),("!","excl.")]\n']
f_list = []
for i in temp:
  f_list.append(eval(i.strip()))

print(f_list)

#[[('Vazhdo', 'verb'), ('të', 'particle'), ('ecësh', 'verb'), ('!', 'excl.')]]

#OR

f_list = [eval(lst.strip()) for lst in f_list]
</code>```

Body:
I have a .txt document with this type of text:

[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]

(which represents a sentence and the Parts of Speech tags for each word)

I want to have a list of list in python, like this:

[[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]]

But I obtain this:

['[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]\n']

The code I'm using is:

import io
f=io.open("test.txt", mode="r", encoding="utf-8-sig")
f_list = list(f)

How can I avoid the ['[ .... ]\n']  ?

Thank you!

Body:
io.open() reads the file as a list of strings so you'll need to evaluate each line of the .txt file to get a list of lists instead of your list of strings.

Here's how you can accomplish that:

temp = ['[("Vazhdo","verb"),("të","particle"),("ecësh","verb"),("!","excl.")]\n']
f_list = []
for i in temp:
  f_list.append(eval(i.strip()))

print(f_list)

#[[('Vazhdo', 'verb'), ('të', 'particle'), ('ecësh', 'verb'), ('!', 'excl.')]]

#OR

f_list = [eval(lst.strip()) for lst in f_list]


问:
focus:outline-none not working Tailwind CSS with Laravel
I am using Tailwind CSS for my Laravel application, and want to remove the focus border on the input boxes. According to the documentation, focus:outline-none should achieve this, although it is not working for me and the border still appears on focus.

It looks like I am targeting the wrong thing, as if I do focus:outline-black, I can see a black outline as well as the standard blue one on focus.

focus:border-none also does not fix the problem.

Any ideas?

<input class="text-input" placeholder="Your Name" />

.text-input {
    @apply focus:outline:none;
}
```
<p><strong>tailwind.config.js</strong></p>
<pre class="lang-js prettyprint-override"><code>const defaultTheme = require('tailwindcss/defaultTheme');
const colors = require('tailwindcss/colors');

module.exports = {
    mode: 'jit',
    purge: [
        './vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php',
        './vendor/laravel/jetstream/**/*.blade.php',
        './storage/framework/views/*.php',
        './resources/views/**/*.blade.php',
    ],

    theme: {
        extend: {
            fontFamily: {
                sans: ['Nunito', ...defaultTheme.fontFamily.sans],
            },
        },
        colors: {
            black: colors.black,
            white: colors.white,
            gray: colors.trueGray,
            indigo: colors.indigo,
            red: colors.rose,
            yellow: colors.amber,
            blue: colors.blue,
        },
    },

    plugins: [require('@tailwindcss/forms'), require('@tailwindcss/typography')],
};
</code>```

webpack.mix.js

const mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel applications. By default, we are compiling the CSS
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/js/app.js', 'public/js')
    .postCss('resources/css/app.css', 'public/css', [
        require('postcss-import'),
        require('tailwindcss'),
    ]);

if (mix.inProduction()) {
    mix.version();
}
```

答: The proper way: border-none focus:ring-0 You don't need to bother making a border transparent if it doesn't exist.

Body:
I am using Tailwind CSS for my Laravel application, and want to remove the focus border on the input boxes. According to the documentation, focus:outline-none should achieve this, although it is not working for me and the border still appears on focus.

It looks like I am targeting the wrong thing, as if I do focus:outline-black, I can see a black outline as well as the standard blue one on focus.

focus:border-none also does not fix the problem.

Any ideas?

<input class="text-input" placeholder="Your Name" />

.text-input {
    @apply focus:outline:none;
}

tailwind.config.js

const defaultTheme = require('tailwindcss/defaultTheme');
const colors = require('tailwindcss/colors');

module.exports = {
    mode: 'jit',
    purge: [
        './vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php',
        './vendor/laravel/jetstream/**/*.blade.php',
        './storage/framework/views/*.php',
        './resources/views/**/*.blade.php',
    ],

    theme: {
        extend: {
            fontFamily: {
                sans: ['Nunito', ...defaultTheme.fontFamily.sans],
            },
        },
        colors: {
            black: colors.black,
            white: colors.white,
            gray: colors.trueGray,
            indigo: colors.indigo,
            red: colors.rose,
            yellow: colors.amber,
            blue: colors.blue,
        },
    },

    plugins: [require('@tailwindcss/forms'), require('@tailwindcss/typography')],
};

webpack.mix.js

const mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel applications. By default, we are compiling the CSS
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/js/app.js', 'public/js')
    .postCss('resources/css/app.css', 'public/css', [
        require('postcss-import'),
        require('tailwindcss'),
    ]);

if (mix.inProduction()) {
    mix.version();
}


问:
Subfolders in static Azure hostings
I want to use an Azure blob file storage to host a static website.

This works fine, if the html-page is located in the root folder of the $web-storage.

But if I put the webpage into a subfolder, the relative links (e.g. to css files) don't work anymore - since they are interpreted as root-based links

```<code><link href="css/bootstrap.css" rel="stylesheet">
</code>```

index.html is located in "subfolder1"

But instead of

```<code>https://blablabla.web.core.windows.net/subfolder1/css
</code>```

it is resolved to

```<code>https://blablabla.web.core.windows.net/css
</code>```

Is this an error of Azure or a misunderstanding/error in my html?

答:
You can setup a base tag to get absolute URLs to work. So, adding this to under html > head should do the trick

    <base href="/subfolder1/" />
    ...

  ...

```

Title: Subfolders in static Azure hostings

Body:
I want to use an Azure blob file storage to host a static website.

This works fine, if the html-page is located in the root folder of the $web-storage.

But if I put the webpage into a subfolder, the relative links (e.g. to css files) don't work anymore - since they are interpreted as root-based links

<link href="css/bootstrap.css" rel="stylesheet">

index.html is located in "subfolder1"

But instead of

https://blablabla.web.core.windows.net/subfolder1/css

it is resolved to

https://blablabla.web.core.windows.net/css

Is this an error of Azure or a misunderstanding/error in my html?

Body:
You can setup a base tag to get absolute URLs to work. So, adding this to under html > head should do the trick

<html>
  <head>
    <base href="/subfolder1/" />
    ...
  </head>
  ...
</html>


问:
Could not load type 'Microsoft.Azure.WebJobs.Host.Scale.ConcurrencyManager' from assembly 'Microsoft.Azure.WebJobs.Host
The application is in Azure Functions,

The error that we are getting from container Pod logs is "Could not load type 'Microsoft.Azure.WebJobs.Host.Scale.ConcurrencyManager' from assembly 'Microsoft.Azure.WebJobs.Host, Version=3.0.26.0".

In our application version all of the dll ver is 3.0.30.0

In the "dll" folder of debug is having the version with 3.0.30.0

And in this version 3.0.30.0, it has the class "Microsoft.Azure.WebJobs.Host.Scale.ConcurrencyManager"

Not sure, where this "assembly 'Microsoft.Azure.WebJobs.Host, Version=3.0.26.0" is coming from.

答:
I had the same issue as below log.

Could not load type 'Microsoft.Azure.WebJobs.Host.Scale.ConcurrencyManager' from assembly 'Microsoft.Azure.WebJobs.Host, Version=3.0.25.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

It was due to my base image for azure functions was old. using the newer base image with below tag(mcr.microsoft.com/azure-functions/dotnet:3.4.2) has fixed my issue.

```<code>FROM mcr.microsoft.com/azure-functions/dotnet:3.4.2 AS base
WORKDIR /home/site/wwwroot
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:3.1.416 AS build
WORKDIR /src
</code>```

Body:
I had the same issue as below log.

Could not load type 'Microsoft.Azure.WebJobs.Host.Scale.ConcurrencyManager' from assembly 'Microsoft.Azure.WebJobs.Host, Version=3.0.25.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

It was due to my base image for azure functions was old. using the newer base image with below tag(mcr.microsoft.com/azure-functions/dotnet:3.4.2) has fixed my issue.

FROM mcr.microsoft.com/azure-functions/dotnet:3.4.2 AS base
WORKDIR /home/site/wwwroot
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:3.1.416 AS build
WORKDIR /src


问:
TypeScript set a type or interface to be any member of an enum
I wanted to know what was the best way to set a type value to any member of an enum.

example

enum daysOfWeekEnum{
    mon = 'Monday',
    tue = 'Tuesday',
    wed = 'Wednesday',
    thu = 'Thursday',
    fri = 'Friday',
    sat = 'Saturday',
    sun = 'Sunday'
}
//any day of week
type dayOfWeek = daysOfWeekEnum

//effective assign the values in this way
type day = 'Monday' | 'Tuesday' | 'Wednesday' ```

答:
The enum is a type itself that can represent any value out of the set of declared values.</p>
```<code>enum daysOfWeekEnum {
    mon = 'Monday',
    tue = 'Tuesday',
    wed = 'Wednesday',
    thu = 'Thursday',
    fri = 'Friday',
    sat = 'Saturday',
    sun = 'Sunday'
}

let day: daysOfWeekEnum = daysOfWeekEnum.mon;

function log(value: daysOfWeekEnum) {
    console.log(value);
}

log(day); // ok -- prints "Monday"
log("Monday"); // ok -- prints "Monday"
log("asdfa"); // not ok - typescript error, "asdfa" is not a daysOfWeekEnum value
</code>```

Body:
The enum is a type itself that can represent any value out of the set of declared values.

enum daysOfWeekEnum {
    mon = 'Monday',
    tue = 'Tuesday',
    wed = 'Wednesday',
    thu = 'Thursday',
    fri = 'Friday',
    sat = 'Saturday',
    sun = 'Sunday'
}

let day: daysOfWeekEnum = daysOfWeekEnum.mon;

function log(value: daysOfWeekEnum) {
    console.log(value);
}

log(day); // ok -- prints "Monday"
log("Monday"); // ok -- prints "Monday"
log("asdfa"); // not ok - typescript error, "asdfa" is not a daysOfWeekEnum value


问:
Celery not running (Permission Denied)
I'm not running a Django Project, this is just a simple python project and I want to demonize the celery. Initially I was running it in the shell. Celery sometimes hangs in between(known issue). Hence I need to restart it again and again. Therefore, I need to daemonize it, so that I can run a script that restarts the celery on its own via a cronjob.

I've looked onto various threads on SO, but with no luck.

I've created a user and group , both named as  celery by following commands:-

```<code>sudo groupadd celery
sudo useradd -g celery celery
</code>```

I created this file as: /etc/default/celeryd

```<code>CELERYD_NODES="w1"

CELERY_BIN="/usr/local/bin/celery"

CELERY_APP="tasks"

CELERYD_CHDIR="/home/cube26/Desktop/cube26/c26-quicklook"

CELERYD_OPTS="--time-limit=300 --concurrency=8  -Q BBC,BGR,FASTCOMPANY"

CELERY_CONFIG_MODULE="celeryconfig" #I dont know what this is for?

CELERYD_LOG_FILE="/var/log/celery/%n.log"
CELERYD_PID_FILE="/var/run/celery/%n.pid"

CELERY_CREATE_DIRS=1

CELERYD_USER="celery"
CELERYD_GROUP="celery"
</code>```

Then downloaded this file and kept it inside  /etc/init.d/celeryd.

Then chmod +x /etc/init.d/celeryd to make it executable.

Thats all I did.

and I'm still getting an error saying IOError: [Errno 13] Permission denied: '/var/log/celery/w1.log'

What wrong am I doing? Please help me rectify it.

答:
Tell celery where to put the pid file:

```<code>celery -A config --pidfile=${CELERYD_PID_FILE}
</code>```

where CELERYD_PID_FILE is /var/www/my_site/celery.pid for example.

Title: Celery not running (Permission Denied)

Body:
I'm not running a Django Project, this is just a simple python project and I want to demonize the celery. Initially I was running it in the shell. Celery sometimes hangs in between(known issue). Hence I need to restart it again and again. Therefore, I need to daemonize it, so that I can run a script that restarts the celery on its own via a cronjob.

I've looked onto various threads on SO, but with no luck.

I've created a user and group , both named as  celery by following commands:-

sudo groupadd celery
sudo useradd -g celery celery

I created this file as: /etc/default/celeryd

CELERYD_NODES="w1"

CELERY_BIN="/usr/local/bin/celery"

CELERY_APP="tasks"

CELERYD_CHDIR="/home/cube26/Desktop/cube26/c26-quicklook"

CELERYD_OPTS="--time-limit=300 --concurrency=8  -Q BBC,BGR,FASTCOMPANY"

CELERY_CONFIG_MODULE="celeryconfig" #I dont know what this is for?

CELERYD_LOG_FILE="/var/log/celery/%n.log"
CELERYD_PID_FILE="/var/run/celery/%n.pid"

CELERY_CREATE_DIRS=1

CELERYD_USER="celery"
CELERYD_GROUP="celery"

Then downloaded this file and kept it inside  /etc/init.d/celeryd.

Then chmod +x /etc/init.d/celeryd to make it executable.

Thats all I did.

and I'm still getting an error saying IOError: [Errno 13] Permission denied: '/var/log/celery/w1.log'

What wrong am I doing? Please help me rectify it.

Body:
Tell celery where to put the pid file:

celery -A config --pidfile=${CELERYD_PID_FILE}

where CELERYD_PID_FILE is /var/www/my_site/celery.pid for example.


问:
Difference between the following code C/C++ code
The first one is :

```<code>if(n--)
{
 //do something
}
</code>```

The second is :

```<code>if(n)
{
//do something
n--;
}
</code>```

I'm not able to understand the difference between these two pieces of code.
Both are giving different outputs.

答:
The first one always subtracts 1 from n no matter what, when the condition of the if statement gets evaluated.

The second one will only subtract 1 from n if n was non-zero at the beginning of the code block, because the n-- is inside the first block of the if statement, and that block only runs if the condition is non-zero.

Both pieces of code are similar in that they will only execute the "do something" if n was non-zero at beginning.

Body:
The first one is :

if(n--)
{
 //do something
}

The second is :

if(n)
{
//do something
n--;
}

I'm not able to understand the difference between these two pieces of code.
Both are giving different outputs.


答:
stats is a DF you need to append another DF to it...

```<code>df2 = pandas.DataFrame({"value":[5]},index=['New Key'])
pandas.concat([stats,df2]))
</code>```

gives

```<code>         value
count     20.00000
mean     124.70000
std       65.36545
min       26.00000
25%       78.25000
50%      120.50000
75%      161.00000
max      252.00000
New Key    5.00000
</code>```

Title: How to add a row to a Python Pandas dataframe that was generated using the .describe() function

Body:
stats is a DF you need to append another DF to it...

df2 = pandas.DataFrame({"value":[5]},index=['New Key'])
pandas.concat([stats,df2]))

gives

         value
count     20.00000
mean     124.70000
std       65.36545
min       26.00000
25%       78.25000
50%      120.50000
75%      161.00000
max      252.00000
New Key    5.00000


问:
Travis CI runs only on Pull Requests and in Expected for Branch
I have two builds at the same time when doing PR.

According to docs, that could be turned off via web interface

I turned that off (want to have only PR build) and also added only to .travis.yml, but still have two builds, but now branch builds just in expecting stage. In web UI Travis - no more builds for branch created.

```<code>branches:
  only:
  - master

language: python
os: linux
dist: xenial

jobs:
  include:
  - name: pytest
    python:
      - 3.7
    install:
      - pip install -U pip
      - pip install -U pytest
      - pip install -U PyYAML
      - pip install -U Cerberus
    script:
      - pytest -vvs
</code>```

答:
You can filter your jobs using conditional checks like:

```<code>    - stage: build
      name: "build pull request"
      if: type IN (pull_request)
      install:
            echo 'Building pull request';
    ...
</code>```

Each step inside this stage will only execute on PR builds.

Body:
I have two builds at the same time when doing PR.

According to docs, that could be turned off via web interface

I turned that off (want to have only PR build) and also added only to .travis.yml, but still have two builds, but now branch builds just in expecting stage. In web UI Travis - no more builds for branch created.

branches:
  only:
  - master

language: python
os: linux
dist: xenial

jobs:
  include:
  - name: pytest
    python:
      - 3.7
    install:
      - pip install -U pip
      - pip install -U pytest
      - pip install -U PyYAML
      - pip install -U Cerberus
    script:
      - pytest -vvs

Body:
You can filter your jobs using conditional checks like:

    - stage: build
      name: "build pull request"
      if: type IN (pull_request)
      install:
            echo 'Building pull request';
    ...

Each step inside this stage will only execute on PR builds.


问:
How do I scrape all the information of this website?
I have a trouble with requests that I can't get requests from the website: https://www.realestate.com.au/neighbourhoods/adelaide-5000-sa

```<code>import requests
url = "https://www.realestate.com.au/neighbourhoods/adelaide-5000-sa"

r = requests(url)

print(r.text)
</code>```

The result:

```<code><html>
    <head>
        <title>realestate.com.au - 403 Error - Permission Denied</title>
    </head>
    <body>
        <hr color="#e4002b">
        <br/>
           <img src="//s1.rui.au.reastatic.net/rui-static/img/rea-logo-v3.png" alt="realestate.com.au Australia lives here" width=200px>
        <font face="Helvetica">
            <h1>  403 - Permission Denied</h1>
            <p>
                You do not have permission to retrieve the URL or link you requested,
            <br/><br/>
                If you think this was a mistake please call <b>1300 134 174</b> or e-mail <b>customercare@realestate.com.au</b>
            <br/>
                and quote the reference number <b> #18.8feaab71.1644380191.7ed3a87</b>
        </font>
        </p>
    </body>
</html>
</code>```

I also add headers for this: requests.get(url)

```<code>headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.124 Safari/537.36",
}

r = requests.get(url, headers=headers)

print(r.text)
</code>```

But the result is also not as expected.

The result:

```<code><!DOCTYPE html><html><head></head><body><script src="/149e9513-01fa-4fb0-aad4-566afd725d1b/2d206a39-8ed7-437e-a3be-862e0f06eea3/ips.js?KP2_UIDz=0DETW9mNWboJXNVKMmWs4ugsDT3iOBMjnnifyH1JVr4sCw2xb90A1wDQxxHIc8J3YRp8zuAsESWfDZZR9ytyVuGUqYpXWZOln6ZcXMAzvdFUWVAjOaofLTbO8Gvj7T5pvjab68eFE1oJDwaBndMBQuK2w"></script></body></html>
</code>```

What should I do?

答:
This requires the cookie in your header along with the user-agent.

Using the browser developer tools, get the cookie and put it into your request. It will work fine. However, make sure your user-agent matches too. The site checks the user-agent against the one given the cookie.

```<code>import requests

headers = {
        'Cookie': '*** your cookie here ***',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.124 Safari/537.36'}

response = requests.get(url, headers = headers)

print(response.text)
print(response.status_code)
</code>```

Gave me this:

```<code><!DOCTYPE html><!--[if IE 8]><html class="ie ie8"></html><![endif]--><!--[if IE 9]><html class="ie ie9"></html><![endif]--><html><head>
<script type="text/javascript">
  try {
    if (Object.defineProperty !== undefined) {
      Object.defineProperty(document, 'referrer', {
        value: "",
        writable: false
      });
    }
  } catch (err) {}
</script>

<script>window.NREUM||(NREUM={});NREUM.info={"beacon":"bam-cell.nr-data.net","errorBeacon":"bam-cell.nr-data.net","licenseKey":"1d1110a9fb","applicationID":"33095795","transactionName":"dlxWFkpaXQgHQhZqUVtSTBBZGmIRAEVLW2hHXF4LVFBwFBIffnxsFRxWB1FSWQYNRUtRV1pXS00CVFUAEFVKSg==","queueTime":1,"applicationTime":345,"agent":""}</script>
...
</code>```

Body:
I have a trouble with requests that I can't get requests from the website: https://www.realestate.com.au/neighbourhoods/adelaide-5000-sa

import requests
url = "https://www.realestate.com.au/neighbourhoods/adelaide-5000-sa"

r = requests(url)

print(r.text)

The result:

        <title>realestate.com.au - 403 Error - Permission Denied</title>

  403 - Permission Denied

                You do not have permission to retrieve the URL or link you requested,

                If you think this was a mistake please call 1300 134 174 or e-mail customercare@realestate.com.au

                and quote the reference number  #18.8feaab71.1644380191.7ed3a87

I also add headers for this: requests.get(url)

headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.124 Safari/537.36",
}

r = requests.get(url, headers=headers)

print(r.text)

But the result is also not as expected.

The result:

<!DOCTYPE html>

What should I do?

Body:
This requires the cookie in your header along with the user-agent.

Using the browser developer tools, get the cookie and put it into your request. It will work fine. However, make sure your user-agent matches too. The site checks the user-agent against the one given the cookie.

import requests

headers = {
        'Cookie': '*** your cookie here ***',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.124 Safari/537.36'}

response = requests.get(url, headers = headers)

print(response.text)
print(response.status_code)

Gave me this:

<!DOCTYPE html><!--[if IE 8]><html class="ie ie8"></html><![endif]--><!--[if IE 9]><html class="ie ie9"></html><![endif]--><html><head>
<script type="text/javascript">
  try {
    if (Object.defineProperty !== undefined) {
      Object.defineProperty(document, 'referrer', {
        value: "",
        writable: false
      });
    }
  } catch (err) {}
</script>

<script>window.NREUM||(NREUM={});NREUM.info={"beacon":"bam-cell.nr-data.net","errorBeacon":"bam-cell.nr-data.net","licenseKey":"1d1110a9fb","applicationID":"33095795","transactionName":"dlxWFkpaXQgHQhZqUVtSTBBZGmIRAEVLW2hHXF4LVFBwFBIffnxsFRxWB1FSWQYNRUtRV1pXS00CVFUAEFVKSg==","queueTime":1,"applicationTime":345,"agent":""}</script>
...


问:
Find numeric sequence in list and then change a value in R?
Similar questions have been asked here and here. But they don't specifically help my issue.

I have a large list of numerical vectors. What I'm trying to do is check if the sequence 1, 1, 1 appears anywhere in my list. And if it does appear, change it to 1, 1, 3.

For example, if I have a list that looks like this:

```<code>myList <- list(c(1,1,1,2,3,5),
               c(1,1,2),
               c(1,2,3,4),
               c(1,1,1,5,8))
</code>```

We can see that the sequence 1, 1, 1 appears in myList[[1]] and myList[[4]]. Im trying to check each element of myList, find that sequence and then change the 3rd instance of the number 1 to a number 3. In this example, my desired output would look like:

```<code>[[1]]
[1] 1 1 3 2 3 5

[[2]]
[1] 1 1 2

[[3]]
[1] 1 2 3 4

[[4]]
[1] 1 1 3 5 8
</code>```

Any suggestions as to how I could achieve this?

答:
Here's a bit of a hack: not efficient, but it works:

# the c(1,1,1) here is what you're looking to find ...
needle <- paste0("\\b", paste(c(1, 1, 1), collapse = ","), "\\b")
# ... and c(1,1,3) what you want to change it to
changeto <- paste(c(1, 1, 3), collapse = ",")

myList2 <- lapply(
  strsplit(sapply(myList, function(L) gsub(needle, changeto, paste(L, collapse = ","))), ","),
  as.integer)
str(myList2)
# List of 4
#  $ : int [1:6] 1 1 3 2 3 5
#  $ : int [1:3] 1 1 2
#  $ : int [1:4] 1 2 3 4
#  $ : int [1:5] 1 1 3 5 8
```

I say it's a bit of a hack because it first collapses the vector of numbers into a comma-separated string, then gsubs the pattern as one would single strings, then splits and re-integerizes it. Not the most efficient, but it works.

Body:
Similar questions have been asked here and here. But they don't specifically help my issue.

I have a large list of numerical vectors. What I'm trying to do is check if the sequence 1, 1, 1 appears anywhere in my list. And if it does appear, change it to 1, 1, 3.

For example, if I have a list that looks like this:

myList <- list(c(1,1,1,2,3,5),
               c(1,1,2),
               c(1,2,3,4),
               c(1,1,1,5,8))

We can see that the sequence 1, 1, 1 appears in myList[[1]] and myList[[4]]. Im trying to check each element of myList, find that sequence and then change the 3rd instance of the number 1 to a number 3. In this example, my desired output would look like:

[[1]]
[1] 1 1 3 2 3 5

[[2]]
[1] 1 1 2

[[3]]
[1] 1 2 3 4

[[4]]
[1] 1 1 3 5 8

Any suggestions as to how I could achieve this?

Body:
Here's a bit of a hack: not efficient, but it works:

# the c(1,1,1) here is what you're looking to find ...
needle <- paste0("\\b", paste(c(1, 1, 1), collapse = ","), "\\b")
# ... and c(1,1,3) what you want to change it to
changeto <- paste(c(1, 1, 3), collapse = ",")

myList2 <- lapply(
  strsplit(sapply(myList, function(L) gsub(needle, changeto, paste(L, collapse = ","))), ","),
  as.integer)
str(myList2)
# List of 4
#  $ : int [1:6] 1 1 3 2 3 5
#  $ : int [1:3] 1 1 2
#  $ : int [1:4] 1 2 3 4
#  $ : int [1:5] 1 1 3 5 8

I say it's a bit of a hack because it first collapses the vector of numbers into a comma-separated string, then gsubs the pattern as one would single strings, then splits and re-integerizes it. Not the most efficient, but it works.


问:
WCF and problem with JSON
Gentelmens,

I'm working with WCF services and I would like to see result as JSON.
But I don't have any ideas how to do it. I have marked my method as

```<code>[WebGet(ResponseFormat = WebMessageFormat.Json)]
</code>```

but this doesn't help me. In "Wcf test client" I see result as xml.

I have tried to add behaviour(WebHttp with Json) to endpoint but I have error:

```<code>The endpoint at 'http://localhost:8732/Design_Time_Addresses/PlayingWithWCF2/Service1/' does not have a Binding
with the None MessageVersion.  'System.ServiceModel.Description.WebHttpBehavior' is only intended for use
with WebHttpBinding or similar bindings.
</code>```

DataContract:

```<code>  [DataContract]
  public class Foo
  {
    [DataMember]
    public string Name { get; set; }
  }
</code>```

Interface:

```<code>  [ServiceContract]
  public interface IFooService
  {
    [OperationContract]
    List<Foo> GetList();
  }
</code>```

Service:

```<code>  [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  public class FooSerivce : IFooService
  {
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    public List<Foo> GetList()
    {
      return new List<Foo> {new Foo {Name = "Name1"}, new Foo {Name = "Name2"}};
    }
  }
</code>```

Web.config:

```<code><system.serviceModel>
    <services>
      <service name="PlayingWithWCF2.FooSerivce">
        <endpoint address="" behaviorConfiguration="" binding="wsHttpBinding"
         contract="PlayingWithWCF2.IFooService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/PlayingWithWCF2/Service1/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</code>```

Could you give me several advices how I can solve this problem?

P.S. Sorry if question is stupid but I'm newbie in WCF

答:
To return JSON you must use REST service which is not supported by WCF test client. You have defined your service to support REST but you didn't configure it to expose REST endpoint. You need this configuration:</p>

```<code>  <system.serviceModel>
    <services>
      <service name="PlayingWithWCF2.FooSerivce">
        <endpoint address="webHttp" binding="webHttpBinding" contract="PlayingWithWCF2.IFooService" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/PlayingWithWCF2/Service1/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webHttp">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>
</code>```

Title: WCF and problem with JSON

Body:
Gentelmens,

I'm working with WCF services and I would like to see result as JSON.
But I don't have any ideas how to do it. I have marked my method as

[WebGet(ResponseFormat = WebMessageFormat.Json)]

but this doesn't help me. In "Wcf test client" I see result as xml.

I have tried to add behaviour(WebHttp with Json) to endpoint but I have error:

The endpoint at 'http://localhost:8732/Design_Time_Addresses/PlayingWithWCF2/Service1/' does not have a Binding
with the None MessageVersion.  'System.ServiceModel.Description.WebHttpBehavior' is only intended for use
with WebHttpBinding or similar bindings.

DataContract:

  [DataContract]
  public class Foo
  {
    [DataMember]
    public string Name { get; set; }
  }

Interface:

  [ServiceContract]
  public interface IFooService
  {
    [OperationContract]
    List<Foo> GetList();
  }

Service:

  [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  public class FooSerivce : IFooService
  {
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    public List<Foo> GetList()
    {
      return new List<Foo> {new Foo {Name = "Name1"}, new Foo {Name = "Name2"}};
    }
  }

Web.config:

<system.serviceModel>
    <services>
      <service name="PlayingWithWCF2.FooSerivce">
        <endpoint address="" behaviorConfiguration="" binding="wsHttpBinding"
         contract="PlayingWithWCF2.IFooService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/PlayingWithWCF2/Service1/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

Could you give me several advices how I can solve this problem?

P.S. Sorry if question is stupid but I'm newbie in WCF

Body:
To return JSON you must use REST service which is not supported by WCF test client. You have defined your service to support REST but you didn't configure it to expose REST endpoint. You need this configuration:

  <system.serviceModel>
    <services>
      <service name="PlayingWithWCF2.FooSerivce">
        <endpoint address="webHttp" binding="webHttpBinding" contract="PlayingWithWCF2.IFooService" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/PlayingWithWCF2/Service1/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webHttp">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>


问:
RNEncryptedStorage is undefined in react-native-web
I'm developing ios and web app. For storing credentials using encrypted storage, and in web I'm using local storage for now.
But at the time of compiling web app throws error.

```<code>rnw_blogpost.bundle.js:5540 Uncaught Error: RNEncryptedStorage is
undefined at eval (EncryptedStorage.js:1:862) at
Object../node_modules/react-native-encrypted-storage/lib/module/EncryptedStorage.js (rnw_blogpost.bundle.js:1766:1) at __webpack_require__
(rnw_blogpost.bundle.js:5537:33) at fn
(rnw_blogpost.bundle.js:5736:21) at eval (index.js:1:389) at
Object../node_modules/react-native-encrypted-storage/lib/module/index.js
(rnw_blogpost.bundle.js:1776:1) at __webpack_require__
(rnw_blogpost.bundle.js:5537:33) at fn
(rnw_blogpost.bundle.js:5736:21) at eval (encrypted-storage.ts:1:565)
at Object../src/util/encrypted-storage.ts
(rnw_blogpost.bundle.js:4098:1)
</code>```

This is due to https://github.com/emeraldsanto/react-native-encrypted-storage/blob/master/src/EncryptedStorage.ts#L7

Is there any way, that in web I can handle it.

答: Looks to me like this might be a keychain permissions issue – the error in the source code doesn't show what is happening, but it looks like the system isn't able to import RNEncryptedStorage at all. Other possibility is that it may just be a missing dependency – have you tried pod install?

Body:
I'm developing ios and web app. For storing credentials using encrypted storage, and in web I'm using local storage for now.
But at the time of compiling web app throws error.

rnw_blogpost.bundle.js:5540 Uncaught Error: RNEncryptedStorage is
undefined at eval (EncryptedStorage.js:1:862) at
Object../node_modules/react-native-encrypted-storage/lib/module/EncryptedStorage.js (rnw_blogpost.bundle.js:1766:1) at __webpack_require__
(rnw_blogpost.bundle.js:5537:33) at fn
(rnw_blogpost.bundle.js:5736:21) at eval (index.js:1:389) at
Object../node_modules/react-native-encrypted-storage/lib/module/index.js
(rnw_blogpost.bundle.js:1776:1) at __webpack_require__
(rnw_blogpost.bundle.js:5537:33) at fn
(rnw_blogpost.bundle.js:5736:21) at eval (encrypted-storage.ts:1:565)
at Object../src/util/encrypted-storage.ts
(rnw_blogpost.bundle.js:4098:1)

This is due to https://github.com/emeraldsanto/react-native-encrypted-storage/blob/master/src/EncryptedStorage.ts#L7

Is there any way, that in web I can handle it.


问:
How to have an anchor tag inside another
I have read other questions (1, 2) asked on this site and how it is said that it is not possible to have an anchor inside another anchor, however I recently saw a website that is achieving this and I want to know how it's done.

You can see in the following website link where there are cards and each card is a link (whole thing wrapped in an anchor tag), but there are also other links inside the card.

https://opensea.io/collection/clonex

Looking at the HTML, you can see that there are actually two anchor tags (one nested inside the other). So this is not some JavaScript hack.

When I try the same HTML, the browser destructures my anchor tags. Anyone knows how this website manages to do this?

答:
You can achieve same functionality by using click event on the card and show cursor as pointer:

Demo Codesandbox

goodCard.addEventListener('click', (e) => window.open(`https://www.google.com/`));

footLink.addEventListener('click', (e) => e.stopPropagation());```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.card {
  padding-bottom: 20px;
  width: fit-content;
  font-size: 100px;
  background-color: rgb(251, 233, 199);
  position: relative;

  cursor: pointer;
}

.foot {
  position: absolute;
  bottom: 0;
  background-color: lightblue;
  width: 100%;
  font-size: initial;
}</code>```

    Good Card

```

For the demo I've used window.open(). If you are using some framework then you need to do it as the framework expects e.g. in react do this.

If you are curious about how to get anchors inside an anchor, then you can do it using javascript. See the demo link provided above. As everyone has already stated it's a bad idea. Don't do it.

Body:
You can achieve same functionality by using click event on the card and show cursor as pointer:

Demo Codesandbox

goodCard.addEventListener('click', (e) => window.open(`https://www.google.com/`));

footLink.addEventListener('click', (e) => e.stopPropagation());

.card {
  padding-bottom: 20px;
  width: fit-content;
  font-size: 100px;
  background-color: rgb(251, 233, 199);
  position: relative;

  cursor: pointer;
}

.foot {
  position: absolute;
  bottom: 0;
  background-color: lightblue;
  width: 100%;
  font-size: initial;
}

<div id='goodCard' class='card'>

  <a id='footLink' href="http://www.gmail.com" target="_blank">
    <footer class="foot">Good Card</footer>
  </a>
</div>

For the demo I've used window.open(). If you are using some framework then you need to do it as the framework expects e.g. in react do this.

If you are curious about how to get anchors inside an anchor, then you can do it using javascript. See the demo link provided above. As everyone has already stated it's a bad idea. Don't do it.


问:
Odoo13-CE: Error message: The requested operation ("read" to "account" (account.account)) was rejected due to following rules: Account multi-company
Module Invoicing: I wanted to set Fiscal Localization Package and got the following error message:

```<code>The requested operation ("read" to "account" (account.account)) was rejected due to the following rules:
- Account multi-company
</code>```

Note: This could be a multi-company problem

```<code>(Records: 2000 domestic partner receivables without own debtor account (id=68), User: Test (id=27))
</code>```

How can I fix it?

答: Please check in User: Test (id=27), it seems like the Test user does not have access to a specific company, you should check the allowed company in user form view.</p>

Body:
Module Invoicing: I wanted to set Fiscal Localization Package and got the following error message:

The requested operation ("read" to "account" (account.account)) was rejected due to the following rules:
- Account multi-company

Note: This could be a multi-company problem

(Records: 2000 domestic partner receivables without own debtor account (id=68), User: Test (id=27))

How can I fix it?


问:
Delete deployment package for lambda version
I had made a lambda function in the past which I want to change. At the time of making it there were no layers, so I was forced to use a deployment package. I have published this version under an alias, and would like to modify the $latest version .

However, in the $latest version, which is editable, the only code entry types available are zip and S3, the code editor is not there. How can I remove the deployed package so I can use a layer with some libraries, and write the code into the editor.

答: Just create a zip file of your code only and upload it using 'upload a zip file'. This will replace your existing package with a smaller code file that can me edited via online editor. NOTE: only zip your lambda_function.py file and nothing else. Rest you can upload via layers as you said.</p>


问:
java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7
I'm not able to run a simple spark job in Scala IDE (Maven spark project) installed on Windows 7

Spark core dependency has been added.

```<code>val conf = new SparkConf().setAppName("DemoDF").setMaster("local")
val sc = new SparkContext(conf)
val logData = sc.textFile("File.txt")
logData.count()
</code>```

Error:

```<code>16/02/26 18:29:33 INFO SparkContext: Created broadcast 0 from textFile at FrameDemo.scala:13
16/02/26 18:29:34 ERROR Shell: Failed to locate the winutils binary in the hadoop binary path
java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries.
    at org.apache.hadoop.util.Shell.getQualifiedBinPath(Shell.java:278)
    at org.apache.hadoop.util.Shell.getWinUtilsPath(Shell.java:300)
    at org.apache.hadoop.util.Shell.<clinit>(Shell.java:293)
    at org.apache.hadoop.util.StringUtils.<clinit>(StringUtils.java:76)
    at org.apache.hadoop.mapred.FileInputFormat.setInputPaths(FileInputFormat.java:362)
    at <br>org.apache.spark.SparkContext$$anonfun$hadoopFile$1$$anonfun$33.apply(SparkContext.scala:1015)
    at org.apache.spark.SparkContext$$anonfun$hadoopFile$1$$anonfun$33.apply(SparkContext.scala:1015)
    at <br>org.apache.spark.rdd.HadoopRDD$$anonfun$getJobConf$6.apply(HadoopRDD.scala:176)
    at <br>org.apache.spark.rdd.HadoopRDD$$anonfun$getJobConf$6.apply(HadoopRDD.scala:176)<br>
    at scala.Option.map(Option.scala:145)<br>
    at org.apache.spark.rdd.HadoopRDD.getJobConf(HadoopRDD.scala:176)<br>
    at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:195)<br>
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239)<br>
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237)<br>
    at scala.Option.getOrElse(Option.scala:120)<br>
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:237)<br>
    at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)<br>
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239)<br>
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237)<br>
    at scala.Option.getOrElse(Option.scala:120)<br>
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:237)<br>
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1929)<br>
    at org.apache.spark.rdd.RDD.count(RDD.scala:1143)<br>
    at com.org.SparkDF.FrameDemo$.main(FrameDemo.scala:14)<br>
    at com.org.SparkDF.FrameDemo.main(FrameDemo.scala)<br>
</code>```

答:
Download winutils.exe and hadoop.dll in your windows machine.

create folder C:\hadoop\bin

Copy winutils.exe and hadoop.dll in newly created hadoop folder

Setup environment variable
HADOOP_HOME=C:\hadoop

Body:
I'm not able to run a simple spark job in Scala IDE (Maven spark project) installed on Windows 7

Spark core dependency has been added.

val conf = new SparkConf().setAppName("DemoDF").setMaster("local")
val sc = new SparkContext(conf)
val logData = sc.textFile("File.txt")
logData.count()

Error:

16/02/26 18:29:33 INFO SparkContext: Created broadcast 0 from textFile at FrameDemo.scala:13
16/02/26 18:29:34 ERROR Shell: Failed to locate the winutils binary in the hadoop binary path
java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries.
    at org.apache.hadoop.util.Shell.getQualifiedBinPath(Shell.java:278)
    at org.apache.hadoop.util.Shell.getWinUtilsPath(Shell.java:300)
    at org.apache.hadoop.util.Shell.<clinit>(Shell.java:293)
    at org.apache.hadoop.util.StringUtils.<clinit>(StringUtils.java:76)
    at org.apache.hadoop.mapred.FileInputFormat.setInputPaths(FileInputFormat.java:362)
    at
org.apache.spark.SparkContext$$anonfun$hadoopFile$1$$anonfun$33.apply(SparkContext.scala:1015)
    at org.apache.spark.SparkContext$$anonfun$hadoopFile$1$$anonfun$33.apply(SparkContext.scala:1015)
    at
org.apache.spark.rdd.HadoopRDD$$anonfun$getJobConf$6.apply(HadoopRDD.scala:176)
    at
org.apache.spark.rdd.HadoopRDD$$anonfun$getJobConf$6.apply(HadoopRDD.scala:176)

    at scala.Option.map(Option.scala:145)

    at org.apache.spark.rdd.HadoopRDD.getJobConf(HadoopRDD.scala:176)

    at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:195)

    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239)

    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237)

    at scala.Option.getOrElse(Option.scala:120)

    at org.apache.spark.rdd.RDD.partitions(RDD.scala:237)

    at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)

    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239)

    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237)

    at scala.Option.getOrElse(Option.scala:120)

    at org.apache.spark.rdd.RDD.partitions(RDD.scala:237)

    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1929)

    at org.apache.spark.rdd.RDD.count(RDD.scala:1143)

    at com.org.SparkDF.FrameDemo$.main(FrameDemo.scala:14)

    at com.org.SparkDF.FrameDemo.main(FrameDemo.scala)


问:
Not able to create src and public folder using npx create-react-app my-app
I tried all things means all commands are still is not able to create react app please help me to solve this problem.</p>

答: update your node version. Try uninstalling then reinstall</p>


问:
Git-windows case sensitive file names not handled properly
We have the git bare repository in unix that has files with same name that differs only in cases.

Example:

```<code>GRANT.sql
grant.sql
</code>```

When we clone the bare repository from unix in to a windows box, git status detects the file as modified. The working tree is loaded only with grant.sql, but git status compares grant.sql and GRANT.sql and shows the file as modified in the working tree.

I tried using the core.ignorecase false but the result is the same.

Is there any way to fix this issue?

答:
Another simple approach which can avoid git read-tree --reset -u HEAD

```<code>1. Clone without checking out
  `git clone --no-checkout`

2. Configure sparse checkout

3. Check out required branch
`git checkout -b branch_name remotes/origin/branch_name`
</code>```

ContentLicense: CC BY-SA 2.5

Body:
We have the git bare repository in unix that has files with same name that differs only in cases.

Example:

GRANT.sql
grant.sql

When we clone the bare repository from unix in to a windows box, git status detects the file as modified. The working tree is loaded only with grant.sql, but git status compares grant.sql and GRANT.sql and shows the file as modified in the working tree.

I tried using the core.ignorecase false but the result is the same.

Is there any way to fix this issue?

Body:
Another simple approach which can avoid git read-tree --reset -u HEAD

1. Clone without checking out
  `git clone --no-checkout`

2. Configure sparse checkout

3. Check out required branch
`git checkout -b branch_name remotes/origin/branch_name`


问:
Update UI after sending POST request on Angular 13
I have a method to post data and another one to fetch data, each one on it's current button and function. What I'm trying to achieve is to update the posts array when clicking on Send Post.
My aproach was to call onFetchPosts in the same function in which I created them, each function works as a unit, but when I tried to call fetch on create, it just wont work

```<code>Html File Using Bootstrap 4 and angular template driven forms

    ```

      <form #postForm="ngForm" (ngSubmit)="onCreatePost(postForm.value)">

          Title
          <input
            type="text"
            class="form-control"
            id="title"
            required
            ngModel
            name="title"
          />

          Content
          <textarea
            class="form-control"
            id="content"
            required
            ngModel
            name="content"
          ></textarea>

        <button
          class="btn btn-primary"
          type="submit"
          [disabled]="!postForm.valid"
        >
          Send Post
        </button>
      </form>

      <button class="btn btn-primary" (click)="onFetchPosts()">
        Fetch Posts
      </button>
      |
      <button
        class="btn btn-danger"
        [disabled]="loadedPosts.length < 1"
        (click)="onClearPosts()"
      >
        Clear Posts
      </button>

      <p *ngIf="loadedPosts.length < 1 && !isFetching">No posts available!

= 1 && !isFetching">

{{ post.title }}

{{ post.content }}

 ```

Ts File, calling the functions made in the service.ts file

    ``` import { Component, OnInit } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Post } from './post.model';
    import { PostsService } from './posts.service';

    @Component({
     selector: 'app-post',
     templateUrl: './post.component.html',
     styleUrls: ['./post.component.scss']
     })
    export class PostComponent implements OnInit {
   loadedPosts: Post[] = [];
   isFetching = false;

   constructor(private http: HttpClient, private postsService: PostsService) { }

   ngOnInit(): void {
    this.isFetching = true;
    this.postsService.fetchPosts().subscribe(posts => {
      this.isFetching = false;
      this.loadedPosts = posts;
    });
   }

   // Here I'm trying to call fetchPosts after I create one, but the UI won't get updated
   onCreatePost(postData: { title: string; content: string }) {
   this.isFetching = true;
    this.postsService.createAndStorePost(postData.title, postData.content)
   this.postsService.fetchPosts().subscribe(posts => {
      this.isFetching = false;
      this.loadedPosts = posts;
     });
   }

  onFetchPosts() {
    // Send Http request
    this.isFetching = true;
    this.postsService.fetchPosts().subscribe(posts => {
      this.isFetching = false;
      this.loadedPosts = posts;
     });
     }

    onClearPosts() {
    // Send Http request
    this.postsService.deletePosts().subscribe(() => {
      this.loadedPosts = [];
    });
    }
    } ```

Service.ts, creating functions to create, fetch and delete posts

``` import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { map } from "rxjs/operators";

import { Post } from "./post.model";

@Injectable({providedIn: 'root'})
export class PostsService {

    constructor(private http: HttpClient) {}
    createAndStorePost(title: string, content: string) {
        const postData: Post = {title: title, content: content};
        this.http
        .post<{ name: string }>(
          'https://to my backend at.firebaseio.com/posts.json',
          postData
        )
        .subscribe(responseData => {
          console.log(responseData);
        });
    }

    fetchPosts() {
        return this.http
            .get<{ [key: string]: Post }>(
                'https://to my backend at.firebaseio.com/posts.json'
                )
            .pipe(
                map(responseData => {
                    const postsArray: Post[] = [];
                    for (const key in responseData) {
                    if (responseData.hasOwnProperty(key)) {
                        postsArray.push({ ...responseData[key], id: key });
                    }
                }
                return postsArray;
            })
        );
    }

    deletePosts() {
        return this.http.delete('https://to my backend at.firebaseio.com/posts.json')
    }
} ```
</code>```

答:
You dont need to subscribe in service. Instead do this

```<code>createAndStorePost(title: string, content: string) {
    const postData: Post = { title: title, content: content };
    return this.http
        .post<{ name: string }>(
            'https://to my backend at.firebaseio.com/posts.json',
            postData
        );
}
</code>```

And then in you component

```<code>onCreatePost(postData: { title: string; content: string }) {
    this.isFetching = true;
    this.postsService.createAndStorePost(postData.title, postData.content).subscribe(()=>{
        this.isFetching = false;
        this.onFetchPosts();
    });
}
</code>```

Body:
I have a method to post data and another one to fetch data, each one on it's current button and function. What I'm trying to achieve is to update the posts array when clicking on Send Post.
My aproach was to call onFetchPosts in the same function in which I created them, each function works as a unit, but when I tried to call fetch on create, it just wont work

Html File Using Bootstrap 4 and angular template driven forms

    ``` <div class="container">
    <div class="row">
    <div class="col-xs-12 col-md-6 col-md-offset-3">
      <form #postForm="ngForm" (ngSubmit)="onCreatePost(postForm.value)">
        <div class="form-group">
          <label for="title">Title</label>
          <input
            type="text"
            class="form-control"
            id="title"
            required
            ngModel
            name="title"
          />
        </div>
        <div class="form-group">
          <label for="content">Content</label>
          <textarea
            class="form-control"
            id="content"
            required
            ngModel
            name="content"
          ></textarea>
        </div>
        <button
          class="btn btn-primary"
          type="submit"
          [disabled]="!postForm.valid"
        >
          Send Post
        </button>
      </form>
      </div>
     </div>
     <hr />
     <div class="row">
     <div class="col-xs-12 col-md-6 col-md-offset-3">
      <button class="btn btn-primary" (click)="onFetchPosts()">
        Fetch Posts
      </button>
      |
      <button
        class="btn btn-danger"
        [disabled]="loadedPosts.length < 1"
        (click)="onClearPosts()"
      >
        Clear Posts
      </button>
      </div>
      </div>
      <div class="row">
      <div class="col-xs-12 col-md-6 col-md-offset-3">
      <p *ngIf="loadedPosts.length < 1 && !isFetching">No posts available!</p>
      <ul class="list-group" *ngIf="loadedPosts.length >= 1 && !isFetching">
        <li class="list-group-item" *ngFor="let post of loadedPosts">
          <h3>{{ post.title }}</h3>
          <p>{{ post.content }}</p>
        </li>
      </ul>
      <div class="loading-spinner" *ngIf="isFetching">
        <div class="sk-chase">
          <div class="sk-chase-dot"></div>
          <div class="sk-chase-dot"></div>
          <div class="sk-chase-dot"></div>
          <div class="sk-chase-dot"></div>
          <div class="sk-chase-dot"></div>
          <div class="sk-chase-dot"></div>
        </div>
      </div>
      </div>
      </div>
      </div> ```

Ts File, calling the functions made in the service.ts file

    ``` import { Component, OnInit } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Post } from './post.model';
    import { PostsService } from './posts.service';

    @Component({
     selector: 'app-post',
     templateUrl: './post.component.html',
     styleUrls: ['./post.component.scss']
     })
    export class PostComponent implements OnInit {
   loadedPosts: Post[] = [];
   isFetching = false;

   constructor(private http: HttpClient, private postsService: PostsService) { }

   ngOnInit(): void {
    this.isFetching = true;
    this.postsService.fetchPosts().subscribe(posts => {
      this.isFetching = false;
      this.loadedPosts = posts;
    });
   }

   // Here I'm trying to call fetchPosts after I create one, but the UI won't get updated
   onCreatePost(postData: { title: string; content: string }) {
   this.isFetching = true;
    this.postsService.createAndStorePost(postData.title, postData.content)
   this.postsService.fetchPosts().subscribe(posts => {
      this.isFetching = false;
      this.loadedPosts = posts;
     });
   }

  onFetchPosts() {
    // Send Http request
    this.isFetching = true;
    this.postsService.fetchPosts().subscribe(posts => {
      this.isFetching = false;
      this.loadedPosts = posts;
     });
     }

    onClearPosts() {
    // Send Http request
    this.postsService.deletePosts().subscribe(() => {
      this.loadedPosts = [];
    });
    }
    } ```

Service.ts, creating functions to create, fetch and delete posts

``` import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { map } from "rxjs/operators";

import { Post } from "./post.model";

@Injectable({providedIn: 'root'})
export class PostsService {

    constructor(private http: HttpClient) {}
    createAndStorePost(title: string, content: string) {
        const postData: Post = {title: title, content: content};
        this.http
        .post<{ name: string }>(
          'https://to my backend at.firebaseio.com/posts.json',
          postData
        )
        .subscribe(responseData => {
          console.log(responseData);
        });
    }

    fetchPosts() {
        return this.http
            .get<{ [key: string]: Post }>(
                'https://to my backend at.firebaseio.com/posts.json'
                )
            .pipe(
                map(responseData => {
                    const postsArray: Post[] = [];
                    for (const key in responseData) {
                    if (responseData.hasOwnProperty(key)) {
                        postsArray.push({ ...responseData[key], id: key });
                    }
                }
                return postsArray;
            })
        );
    }

    deletePosts() {
        return this.http.delete('https://to my backend at.firebaseio.com/posts.json')
    }
} ```

Body:
You dont need to subscribe in service. Instead do this

createAndStorePost(title: string, content: string) {
    const postData: Post = { title: title, content: content };
    return this.http
        .post<{ name: string }>(
            'https://to my backend at.firebaseio.com/posts.json',
            postData
        );
}

And then in you component

onCreatePost(postData: { title: string; content: string }) {
    this.isFetching = true;
    this.postsService.createAndStorePost(postData.title, postData.content).subscribe(()=>{
        this.isFetching = false;
        this.onFetchPosts();
    });
}


问:
React Hooks fade out effect on modal from onMouseLeave
This should be an easy one for most. The modal window after being opened from the button (thats triggered by onMouseEnter) needs an effect to fade out once the onMouseLeave is triggered. the modal "green square" should not move its position  at all but just fade out once the onMouseLeave or setOpenFalse it triggered. And they styles are in tailwind css. Thanks in advance ☠

the sandbox is here - https://codesandbox.io/s/modal-transition-clicked-1egnp?file=/src/styles.css:0-191

```<code>import React from "react";
import classNames from "classnames";
import { useState, Fragment } from "react";
import { useBoolean } from "./hooks/useBoolean";
import "./styles.css";

export const Actions = ({ defaultSelected = "like" }) => {
  const [selected, setSelected] = useState(defaultSelected);
  const [isOpen, setOpenTrue, setOpenFalse] = useBoolean();

  return (
    <div className="relative rounded">
      <button
        onMouseEnter={setOpenTrue}
        onMouseLeave={setOpenFalse}
        className={classNames("flex items-center gap-2 rounded px-2 py-1", {
          "": isOpen
        })}
      >
        {selected && <Fragment>open modal</Fragment>}
        {isOpen && (
          <div className="absolute mt-20 left-0 flex justify-center items start h-12">
            <div className="bg-green-700 w-24 h-36 shadow grid grid-flow-col  px-2 py-1 gap-2 animate-mount"></div>
          </div>
        )}
      </button>
    </div>
  );
};

export default Actions;

.animate-mount {
  animation: mount 0.4s linear;
}

@keyframes mount {
  0% {
    opacity: 0;
    transform: translateY(50%);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

</code>```

答:
It's a bit micromanage-y, but you could add two more states to track when the button element has been entered and exited.

Set the modal open and set entered on mouse enter, and on mouse leave set entered false, set exited true, and then set a timeout to subsequently set open and exited false.

Create an .animate-unmount animation that animates only the opacity.

The unmounting animation and setTimeout should be roughly the same duration.

styles.css

```<code>.animate-mount {
  animation: mount 0.4s linear;
}

@keyframes mount {
  0% {
    opacity: 0;
    transform: translateY(50%);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-unmount {
  animation: unmount 0.5s ease-in-out;
}

@keyframes unmount {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
</code>```

Reactions.js

```<code>export const Actions = ({ defaultSelected = "like" }) => {
  const [selected, setSelected] = useState(defaultSelected);
  const [isOpen, setOpenTrue, setOpenFalse] = useBoolean();
  const [isEntered, setEnteredTrue, setEnteredFalse] = useBoolean();
  const [isExited, setExitedTrue, setExitedFalse] = useBoolean();

  return (
    <div className="relative rounded">
      <button
        onMouseEnter={() => {
          setOpenTrue();
          setEnteredTrue();
        }}
        onMouseLeave={() => {
          setEnteredFalse();
          setExitedTrue();
          setTimeout(() => {
            setOpenFalse();
            setExitedFalse();
          }, 500);
        }}
        className={classNames("flex items-center gap-2 rounded px-2 py-1", {
          "": isOpen
        })}
      >
        {selected && <Fragment>open modal</Fragment>}
        {isOpen && (
          <div className="absolute mt-20 left-0 flex justify-center items start h-12">
            <div
              className={classNames(
                "bg-green-700 w-24 h-36 shadow grid grid-flow-col  px-2 py-1 gap-2",
                {
                  "animate-mount": isEntered,
                  "animate-unmount": isExited
                }
              )}
            ></div>
          </div>
        )}
      </button>
    </div>
  );
};
</code>```

Body:
This should be an easy one for most. The modal window after being opened from the button (thats triggered by onMouseEnter) needs an effect to fade out once the onMouseLeave is triggered. the modal "green square" should not move its position  at all but just fade out once the onMouseLeave or setOpenFalse it triggered. And they styles are in tailwind css. Thanks in advance ☠

the sandbox is here - https://codesandbox.io/s/modal-transition-clicked-1egnp?file=/src/styles.css:0-191

import React from "react";
import classNames from "classnames";
import { useState, Fragment } from "react";
import { useBoolean } from "./hooks/useBoolean";
import "./styles.css";

export const Actions = ({ defaultSelected = "like" }) => {
  const [selected, setSelected] = useState(defaultSelected);
  const [isOpen, setOpenTrue, setOpenFalse] = useBoolean();

  return (

      <button
        onMouseEnter={setOpenTrue}
        onMouseLeave={setOpenFalse}
        className={classNames("flex items-center gap-2 rounded px-2 py-1", {
          "": isOpen
        })}
      >
        {selected && <Fragment>open modal</Fragment>}
        {isOpen && (

        )}
      </button>

  );
};

export default Actions;

.animate-mount {
  animation: mount 0.4s linear;
}

@keyframes mount {
  0% {
    opacity: 0;
    transform: translateY(50%);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

Body:
It's a bit micromanage-y, but you could add two more states to track when the button element has been entered and exited.

Set the modal open and set entered on mouse enter, and on mouse leave set entered false, set exited true, and then set a timeout to subsequently set open and exited false.

Create an .animate-unmount animation that animates only the opacity.

The unmounting animation and setTimeout should be roughly the same duration.

styles.css

.animate-mount {
  animation: mount 0.4s linear;
}

@keyframes mount {
  0% {
    opacity: 0;
    transform: translateY(50%);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-unmount {
  animation: unmount 0.5s ease-in-out;
}

@keyframes unmount {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

Reactions.js

export const Actions = ({ defaultSelected = "like" }) => {
  const [selected, setSelected] = useState(defaultSelected);
  const [isOpen, setOpenTrue, setOpenFalse] = useBoolean();
  const [isEntered, setEnteredTrue, setEnteredFalse] = useBoolean();
  const [isExited, setExitedTrue, setExitedFalse] = useBoolean();

  return (
    <div className="relative rounded">
      <button
        onMouseEnter={() => {
          setOpenTrue();
          setEnteredTrue();
        }}
        onMouseLeave={() => {
          setEnteredFalse();
          setExitedTrue();
          setTimeout(() => {
            setOpenFalse();
            setExitedFalse();
          }, 500);
        }}
        className={classNames("flex items-center gap-2 rounded px-2 py-1", {
          "": isOpen
        })}
      >
        {selected && <Fragment>open modal</Fragment>}
        {isOpen && (
          <div className="absolute mt-20 left-0 flex justify-center items start h-12">
            <div
              className={classNames(
                "bg-green-700 w-24 h-36 shadow grid grid-flow-col  px-2 py-1 gap-2",
                {
                  "animate-mount": isEntered,
                  "animate-unmount": isExited
                }
              )}
            ></div>
          </div>
        )}
      </button>
    </div>
  );
};


问:
Run different stages/pipelines for different azure devops triggers
I've recently started working with azure pipelines (experience with GitHub actions). I am trying to run stages based with different triggers, for example:

For all pushes to my repo I want to run my linter

For all PRs I want to run my tests

For all merges to master I want to run my deployment pipeline

From what I read from the documentation of azure pipelines, this isn’t possible. If I understand correctly, I can only define 1 trigger value on the top of my azure-pipelines.yml value. Is this really true? Or am I overseeing something? Within github actions I know this can be solved be creating different workflows (lint-workflow, test-workflow etc) with each a separate trigger).

答:
In Azure DevOps, the Trigger field is used to trigger the whole pipeline. So you can only define 1 trigger value on the top of yaml file. Refer to this doc: Triggers

Based on your requirement, you need to control the running of the stages.

I suggest that you can add Conditions in each of your stages. Refer to this doc about Condition.

Here is an sample:

```<code>trigger:
- '*'

pool:
  vmImage: windows-latest

stages:
  - stage: linter_stage
    condition: eq(variables['Build.Reason'], 'IndividualCI')
    jobs:
      - job: A
        steps:
          xxx

  - stage: test_stage
    condition: eq(variables['Build.Reason'], 'PullRequest')
    jobs:
      - job: B
        steps:
          xxx
  - stage: deployment_stage
    condition:  and(eq(variables['Build.Reason'], 'IndividualCI'), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
    jobs:
      - job: C
        steps:
          xxx
</code>```

Explanation：

At the top of the YAML you need to define Trigger as * to make sure any changes will trigger the pipeline.

You can use the build.reason and Build.SourceBranch variable  to determine if stages need to be run

Here is the doc about the predefined variable.

Result:

Body:
In Azure DevOps, the Trigger field is used to trigger the whole pipeline. So you can only define 1 trigger value on the top of yaml file. Refer to this doc: Triggers

Based on your requirement, you need to control the running of the stages.

I suggest that you can add Conditions in each of your stages. Refer to this doc about Condition.

Here is an sample:

trigger:
- '*'

pool:
  vmImage: windows-latest

stages:
  - stage: linter_stage
    condition: eq(variables['Build.Reason'], 'IndividualCI')
    jobs:
      - job: A
        steps:
          xxx

  - stage: test_stage
    condition: eq(variables['Build.Reason'], 'PullRequest')
    jobs:
      - job: B
        steps:
          xxx
  - stage: deployment_stage
    condition:  and(eq(variables['Build.Reason'], 'IndividualCI'), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
    jobs:
      - job: C
        steps:
          xxx

Explanation：

At the top of the YAML you need to define Trigger as * to make sure any changes will trigger the pipeline.

You can use the build.reason and Build.SourceBranch variable  to determine if stages need to be run

Here is the doc about the predefined variable.

Result:


问:
how to echo doctype, set in application.ini, in zend framework view
In my Zend Framework application I want to echo the doctype in my view layout with:

```<code><?= $this->doctype() . "\n"; ?>
</code>```

I have the following lines in my application.ini:

```<code>resources.view[] =
resources.view.doctype = "HTML5"
resources.view.charset = "UTF-8"
</code>```

which gives me:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
</code>```

apparently the settings in the application.ini are ignored and instead the default doctype is used.

Is there a way to echo the doctype in my view / layout without using the bootstrap (I know that works but I do not want to have my settings scattered over application.ini and bootstrap)?

答:
you need to configure your view in bootstrap.php

```<code>protected function _initView()
{
    // Initialize view
    $view = new Zend_View();
    $view->doctype('XHTML1_TRANSITIONAL');
    $view->setEncoding('UTF-8');//per , htmlentities($str, ENT_QUOTES, "UTF-8");

    $view->headTitle('ABC');

    // Add it to the ViewRenderer
    $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
    $viewRenderer->setView($view);
    // Return it, so that it can be stored by the bootstrap
    return $view;
}
</code>```

then use in the layout or some view

```<code>echo $this->doctype();
</code>```

Body:
In my Zend Framework application I want to echo the doctype in my view layout with:

<?= $this->doctype() . "\n"; ?>

I have the following lines in my application.ini:

resources.view[] =
resources.view.doctype = "HTML5"
resources.view.charset = "UTF-8"

which gives me:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

apparently the settings in the application.ini are ignored and instead the default doctype is used.

Is there a way to echo the doctype in my view / layout without using the bootstrap (I know that works but I do not want to have my settings scattered over application.ini and bootstrap)?

Body:
you need to configure your view in bootstrap.php

protected function _initView()
{
    // Initialize view
    $view = new Zend_View();
    $view->doctype('XHTML1_TRANSITIONAL');
    $view->setEncoding('UTF-8');//per , htmlentities($str, ENT_QUOTES, "UTF-8");

    $view->headTitle('ABC');

    // Add it to the ViewRenderer
    $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
    $viewRenderer->setView($view);
    // Return it, so that it can be stored by the bootstrap
    return $view;
}

then use in the layout or some view

echo $this->doctype();


问:
How to load an xaml file/workflow in UIPath when a value is selected from a dropdown then a button is clicked
I have installed UIPath.Form.Activities and used Create Form activity. I then created a form with a dropdown and a submit button. On the dropdown, there are two values: Process 1 and Process 2 as below:

Each process has a separate workflow on my project. I would like to run each process (xaml file) based on the selected item on the dropdown list after I clicked the submit/run button. Anyone know how to? Thanks

答:
You can use a string argument SelectedProcess in the FormFieldCollection of the form activity and map it to a workflow variable.

Map this SelectedProcess with your select dropdown.

On submitting the form, you'll get the selected process named in the workflow variable you would have created.


问:
Liquid syntax error: Tag was not properly terminated with regexp: /\%\}/
I have a an if condition in my liquid template like this

```<code>Username: {{user.email}}
{% if extras['password_to_be_sent'] %}
Password: {{extras['password_to_be_sent']}}
{% endif %}
Trial expiration: {{user.trial_expiration}}
</code>```

However this is generating a line break when the if condition does not evaluate to true

so the above generated output like this

```<code>Username: Abc

Trail Expiration: 2019-11-10
</code>```

I want to remove the additional line break when the if condition does not evaluate to true

i tried adding - as suggested here https://shopify.github.io/liquid/basics/whitespace/

so updated code to

```<code>Username: {{user.email}}
{%- if extras['password_to_be_sent'] -%}
Password: {{extras['password_to_be_sent']}}
{%- endif -%}
Trial expiration: {{user.trial_expiration}}
</code>```

but this is giving an exception Liquid::SyntaxError (Liquid syntax error: Tag '{%- if extras['password_to_be_sent'] -%}' was not properly terminated with regexp: /\%\}/)

Additionally, I am saving the template code in database, if that helps.

Any help in this would be appreciated. Thanks.

Body:
I have a an if condition in my liquid template like this

Username: {{user.email}}
{% if extras['password_to_be_sent'] %}
Password: {{extras['password_to_be_sent']}}
{% endif %}
Trial expiration: {{user.trial_expiration}}

However this is generating a line break when the if condition does not evaluate to true

so the above generated output like this

Username: Abc

Trail Expiration: 2019-11-10

I want to remove the additional line break when the if condition does not evaluate to true

i tried adding - as suggested here https://shopify.github.io/liquid/basics/whitespace/

so updated code to

Username: {{user.email}}
{%- if extras['password_to_be_sent'] -%}
Password: {{extras['password_to_be_sent']}}
{%- endif -%}
Trial expiration: {{user.trial_expiration}}

but this is giving an exception Liquid::SyntaxError (Liquid syntax error: Tag '{%- if extras['password_to_be_sent'] -%}' was not properly terminated with regexp: /\%\}/)

Additionally, I am saving the template code in database, if that helps.

Any help in this would be appreciated. Thanks.

Body:
When I change line 134 from

int dis[4][2]={{0,1},{0,-1},{1,0},{-1,0}};

to

int dis[4][2]={ {0,1},{0,-1},{1,0},{-1,0}};

It fixed !


问:
Categorizing Sales by Team
The question is: "In one record for each squad, show the team, its US (area = ‘-US’) sales for 2018 and its UK (area = ‘UK’) sales for 2018. "

Would this not work?

```<code>SELECT squad, SUM(CASE WHEN area = “US” THEN sales_2018 ELSE 0 END) AS “US”, SUM(CASE WHEN area = “UK” then sales_2018 ELSE 0 END) AS “UK”
FROM squad A
Inner join Sales b on a.account = b.account
GROUP BY squad
</code>```

Tables involved:

答:
From what i understand you can use pivot to achieve your result.

```<code>select squad,[US],[UK] from(
select sq.squad,sq.Area,sa.sales_2018 from Sales sa inner join Squad sq on sa.account=sq.account
) tbl
pivot(
sum(sales_2018) for Area in ([US],[UK])
) pvtTable
</code>```

The result of inner query returns

squad
Area
sales_2018

IT
US
1300.00

IT
UK
3300.00

Finance
US
3400.00

Finance
UK
2500.00

After applying Pivot

squad
US
UK

IT
3400.00
2500.00

Finance
1300.00
3300.00

Title: Categorizing Sales by Team

Body:
The question is: "In one record for each squad, show the team, its US (area = ‘-US’) sales for 2018 and its UK (area = ‘UK’) sales for 2018. "

Would this not work?

SELECT squad, SUM(CASE WHEN area = “US” THEN sales_2018 ELSE 0 END) AS “US”, SUM(CASE WHEN area = “UK” then sales_2018 ELSE 0 END) AS “UK”
FROM squad A
Inner join Sales b on a.account = b.account
GROUP BY squad

Tables involved:

Body:
From what i understand you can use pivot to achieve your result.

select squad,[US],[UK] from(
select sq.squad,sq.Area,sa.sales_2018 from Sales sa inner join Squad sq on sa.account=sq.account
) tbl
pivot(
sum(sales_2018) for Area in ([US],[UK])
) pvtTable

The result of inner query returns

squad
Area
sales_2018

IT
US
1300.00

IT
UK
3300.00

Finance
US
3400.00

Finance
UK
2500.00

After applying Pivot

squad
US
UK

IT
3400.00
2500.00

Finance
1300.00
3300.00


问:
Difference between the following code C/C++ code
The first one is :

```<code>if(n--)
{
 //do something
}
</code>```

The second is :

```<code>if(n)
{
//do something
n--;
}
</code>```

I'm not able to understand the difference between these two pieces of code.
Both are giving different outputs.

答:
The first one, n is the value substracted during "do something",
the second one, n is the previous value during "do something".</p>

Body:
The first one is :

if(n--)
{
 //do something
}

The second is :

if(n)
{
//do something
n--;
}

I'm not able to understand the difference between these two pieces of code.
Both are giving different outputs.


问:
How to disable auctex fontification, without losing color highlighting?
I like maximum syntax highlighting of AucTeX, but I don't like AucTeX messing with fonts. For example, if I use italics, it shows italicized letters in my emacs buffer, and shows subscripts and superscripts in small letters (slightly above or below the line). I prefer to use a fixed width font regardless of the latex environment I am in.

I tried changing the settings for the variable font-latex-deactivated-keyword-classes, but then the syntax coloring also disappears.

Could someone suggest a way to fix this?

Thanks.

答: See this page in the manual and the section Deactivating defaults of built-in keyword classes.


问:
Is there a way to use Laravel's mutator on a non-existing column?
The method below is not being called since the 'other_name' attribute does not exist as a column in the table. How can I get the method to be called even if the column does not exist?</p>
```<code>public function setOtherNameAttribute($value)
{
    $this->attributes['name'] = $value;
}
</code>```

答:
This is entirely possible.
I'm using the same strategy to convert plain text passwords to hashed passwords in the model</p>
```<code>protected $fillable = ['name', 'email', 'password'];

public function setPasswordAttribute ($value) {
    $this->password_hash = Hash::make($value);
}

public function getAuthPassword() {
    return $this->password_hash;
}
</code>```

Body:
The method below is not being called since the 'other_name' attribute does not exist as a column in the table. How can I get the method to be called even if the column does not exist?

public function setOtherNameAttribute($value)
{
    $this->attributes['name'] = $value;
}

Body:
This is entirely possible.
I'm using the same strategy to convert plain text passwords to hashed passwords in the model

protected $fillable = ['name', 'email', 'password'];

public function setPasswordAttribute ($value) {
    $this->password_hash = Hash::make($value);
}

public function getAuthPassword() {
    return $this->password_hash;
}


问:
I can't connect to Metamask mobile browser using web3.js
I am trying to connect a Dapp to Metamask. My code works, but not on mobile (using Metamasks built-in browser). This is the code:

```<code><script type="text/javascript">
    if (window.ethereum) {
    handleEthereum();
  } else {
    window.addEventListener('ethereum#initialized', handleEthereum, {
      once: true,
    });

    // If the event is not dispatched by the end of the timeout,
    // the user probably doesn't have MetaMask installed.
    setTimeout(handleEthereum, 3000); // 3 seconds
  }

  function handleEthereum() {
    const { ethereum } = window;
    if (ethereum && ethereum.isMetaMask) {
      console.log('Ethereum successfully detected!');
    } else {
      console.log('Please install MetaMask!');
    }
  }

</script>
</code>```

I tried waiting 15 seconds instead of 3, but it didn't work anyways. I am using Webflow, and adding JavaScript custom code to it. I don't know if that could be the problem.

答:
I did it in the following way

```<code>const base64image = 'imagen';
    ethereum.request({
      method: 'wallet_watchAsset',
      params: {
        type: 'ERC20',
        options: {
          address: wallet,
          symbol: simbolo,
          decimals: 18,
          image: base64image,
        },
      },
    });
</code>```

This part was for the browser, for the mobile I have not been able to solve it.

Body:
I am trying to connect a Dapp to Metamask. My code works, but not on mobile (using Metamasks built-in browser). This is the code:

I tried waiting 15 seconds instead of 3, but it didn't work anyways. I am using Webflow, and adding JavaScript custom code to it. I don't know if that could be the problem.

Body:
I did it in the following way

const base64image = 'imagen';
    ethereum.request({
      method: 'wallet_watchAsset',
      params: {
        type: 'ERC20',
        options: {
          address: wallet,
          symbol: simbolo,
          decimals: 18,
          image: base64image,
        },
      },
    });

This part was for the browser, for the mobile I have not been able to solve it.