问:
How to Invert column values in pandas - pythonic way?
I have a dataframe like as shown below

```<code>cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                    'Label':[1,1,1,0,0]})
</code>```

My objective is to

a) replace 0s as 1s AND 1s as 0s in Label column

I was trying something like the below

```<code>cdf.assign(invert_label=cdf.Label.loc[::-1].reset_index(drop=True)) #not work
cdf['invert_label'] = np.where(cdf['Label']==0, '1', '0')
</code>```

'
but this doesn't work. It reverses the order

I expect my output to be like as shown below

```<code>    Id  Label
0   1   0
1   2   0
2   3   0
3   4   1
4   5   1
</code>```

答:
You can compare 0, so for 0 get Trues and for not 0 get Falses, then converting to integers for mapping True, False to 1, 0:

```<code>print (cdf['Label'].eq(0))
0    False
1    False
2    False
3     True
4     True
Name: Label, dtype: bool

cdf['invert_label'] = cdf['Label'].eq(0).astype(int)

print (cdf)
   Id  Label  invert_label
0   1      1             0
1   2      1             0
2   3      1             0
3   4      0             1
4   5      0             1
</code>```

Another idea is use mapping:

```<code>cdf['invert_label'] = cdf['Label'].map({1:0, 0:1})

print (cdf)
   Id  Label  invert_label
0   1      1             0
1   2      1             0
2   3      1             0
3   4      0             1
4   5      0             1
</code>```

Body:
I have a dataframe like as shown below

cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                    'Label':[1,1,1,0,0]})

My objective is to

a) replace 0s as 1s AND 1s as 0s in Label column

I was trying something like the below

cdf.assign(invert_label=cdf.Label.loc[::-1].reset_index(drop=True)) #not work
cdf['invert_label'] = np.where(cdf['Label']==0, '1', '0')

'
but this doesn't work. It reverses the order

I expect my output to be like as shown below

    Id  Label
0   1   0
1   2   0
2   3   0
3   4   1
4   5   1

Body:
You can compare 0, so for 0 get Trues and for not 0 get Falses, then converting to integers for mapping True, False to 1, 0:

print (cdf['Label'].eq(0))
0    False
1    False
2    False
3     True
4     True
Name: Label, dtype: bool

cdf['invert_label'] = cdf['Label'].eq(0).astype(int)

print (cdf)
   Id  Label  invert_label
0   1      1             0
1   2      1             0
2   3      1             0
3   4      0             1
4   5      0             1

Another idea is use mapping:

cdf['invert_label'] = cdf['Label'].map({1:0, 0:1})

print (cdf)
   Id  Label  invert_label
0   1      1             0
1   2      1             0
2   3      1             0
3   4      0             1
4   5      0             1


来源: stackexchange

问:
Azure-automation: Cannot bind parameter 'Context'
I am trying to create new directories in Azure datalake using azure automation powershell workflow.
The code that i have is like this:

```<code>    $ctx = New-AzStorageContext -ConnectionString $connectionstring

    New-AzDataLakeGen2Item -Context $ctx -FileSystem $filesystemName -Path $dirname -Directory
</code>```

the error message that I get:

```<code>New-AzDataLakeGen2Item : Cannot bind parameter 'Context'. Cannot convert the "Microsoft.WindowsAzure.Commands.Storage.AzureStorageContext" value of type "Deserialized.Microsoft.WindowsAzure.Commands.Storage.AzureStorageContext" to type "Microsoft.Azure.Commands.Common.Authentication.Abstractions.IStorageContext
</code>```

I dont know how to solve this error? any help is greatly appreciated.

答:
In our local environment, We have created a Powershell runbook running with PowerShell Version 5.1.

Using the same above shared cmdlets, we are able to create a new directory in the Azure Data lake storage account. We have used  System managed identity to connect to subscription resources from the automation account.

Here is the Powershell script that we have used in Automation Account:

```<code> Disable-AzContextAutosave -Scope Process  # Ensures you do not inherit an AzContext in your runbook
 $AzureContext = (Connect-AzAccount -Identity).context # Connect to Azure with system-assigned managed identity
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext  # set and store context

Import-module -name Az.Storage

$ctx=New-AzStorageContext -StorageAccountName "<strgaccountName>" -StorageAccountKey "<storageaccountKey>"
New-AzDataLakeGen2Item -Context $ctx -FileSystem "testfiler" -Path "dir1/dir2" -Directory
</code>```

Here is the Sample output for reference:

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create new directories in Azure datalake using azure automation powershell workflow.
The code that i have is like this:

    $ctx = New-AzStorageContext -ConnectionString $connectionstring

    New-AzDataLakeGen2Item -Context $ctx -FileSystem $filesystemName -Path $dirname -Directory

the error message that I get:

New-AzDataLakeGen2Item : Cannot bind parameter 'Context'. Cannot convert the "Microsoft.WindowsAzure.Commands.Storage.AzureStorageContext" value of type "Deserialized.Microsoft.WindowsAzure.Commands.Storage.AzureStorageContext" to type "Microsoft.Azure.Commands.Common.Authentication.Abstractions.IStorageContext

I dont know how to solve this error? any help is greatly appreciated.

Body:
In our local environment, We have created a Powershell runbook running with PowerShell Version 5.1.

Using the same above shared cmdlets, we are able to create a new directory in the Azure Data lake storage account. We have used  System managed identity to connect to subscription resources from the automation account.

Here is the Powershell script that we have used in Automation Account:

 Disable-AzContextAutosave -Scope Process  # Ensures you do not inherit an AzContext in your runbook
 $AzureContext = (Connect-AzAccount -Identity).context # Connect to Azure with system-assigned managed identity
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext  # set and store context

Import-module -name Az.Storage

$ctx=New-AzStorageContext -StorageAccountName "<strgaccountName>" -StorageAccountKey "<storageaccountKey>"
New-AzDataLakeGen2Item -Context $ctx -FileSystem "testfiler" -Path "dir1/dir2" -Directory

Here is the Sample output for reference:


问:
How do I set expression for a parmater in sql server reporting services?
Hi All,

How do i set expression for a parameter in sql server reporting services r2?

Is it even possible?

The expression button is not even there.

Thanks.

答:
I solved this through the web application, In the web application I use the report-viewer control to gain accesses to the parameters.
With the parameters at hand I have complete control on what should be displayed (exression
It's a workaround but it works.</p>

ContentLicense: CC BY-SA 3.0


问:
How create dataframe from list of dictionary of multi level json
So I have a json file that have multiple level,by using pandas I can read the first level and put it in a dataframe,but the problem is as you can see in the dataframe Column Comments and hastags the second level is inside a column have format of list of dictionary,is there any solution for make the second level dictionary into dataframe. I try to use for loop and json_normalize but it always throw an error. Any suggestion? My code is like this

```<code>import pandas as pd
df2 = pd.read_json("data.json")

cid = []
for x in df2["comments"]:
    cid.append(x.get('cid'))

data = pd.DataFrame({'cid':cid})

</code>```

If i use the code it throw an error since I try access list by string not index.

```<code>AttributeError: 'list' object has no attribute 'get'
</code>```

Even I change it into integer it got dictionary inside a column.How to change the dict inside the column or is there another easier way to do this? Dictionary in column

```<code>for x in df2["comments"]:
    cid.append(x[0])
data = pd.DataFrame({'cid':cid})
for y in data:
    print(y.get('cid'))
</code>```

Example of first row of the data frame

```<code>[{'cid': '7000061798167266075', 'createTime': 1629828926, 'text': 'Done ', 'diggCount': 1, 'replyCommentTotal': 0, 'uid': '6529379534374092801', 'uniqueId': 'alikayanti'}, {'cid': '6999869922566783771', 'createTime': 1629784228, 'text': 'haloo min, yg udah ikutan di misi sebelumnya boleh ikutan lagi gaa?', 'diggCount': 1, 'replyCommentTotal': 1, 'uid': '6842932775562642433', 'uniqueId': 'fia_654'}, {'cid': '7000248857603588891', 'createTime': 1629872457, 'text': 'bell bottoms maksudnya apa kak?\napakah benar artinya bel bawah?', 'diggCount': 0, 'replyCommentTotal': 2, 'uid': '6960940768727417857', 'uniqueId': 'keterimadiptn1'}, {'cid': '7000322023545455387', 'createTime': 1629889491, 'text': 'syudah', 'diggCount': 0, 'replyCommentTotal': 0, 'uid': '6806645499672839170', 'uniqueId': 'miftahulhaqqu'}, {'cid': '7001271117180977947', 'createTime': 1630110475, 'text': 'kak, perpanjang dong waktu posting videonya :)', 'diggCount': 1, 'replyCommentTotal': 0, 'uid': '6921267441846830082', 'uniqueId': 'elisabetkst'}]
</code>```

答:
Maybe this solves your problem:

Defined the following function which unnests any json:

```<code>import json
import pandas as pd

def flatten_nested_json_df(df):
    df = df.reset_index()
    s = (df.applymap(type) == list).all()
    list_columns = s[s].index.tolist()

    s = (df.applymap(type) == dict).all()
    dict_columns = s[s].index.tolist()

    while len(list_columns) > 0 or len(dict_columns) > 0:
        new_columns = []

        for col in dict_columns:
            horiz_exploded = pd.json_normalize(df[col]).add_prefix(f'{col}.')
            horiz_exploded.index = df.index
            df = pd.concat([df, horiz_exploded], axis=1).drop(columns=[col])
            new_columns.extend(horiz_exploded.columns) # inplace

        for col in list_columns:
            #print(f"exploding: {col}")
            df = df.drop(columns=[col]).join(df[col].explode().to_frame())
            new_columns.append(col)

        s = (df[new_columns].applymap(type) == list).all()
        list_columns = s[s].index.tolist()

        s = (df[new_columns].applymap(type) == dict).all()
        dict_columns = s[s].index.tolist()
    return df

</code>```

and do this:

```<code>results = pd.json_normalize(data)
df = pd.DataFrame(results)

outdf = flatten_nested_json_df(df)

</code>```

which returns:

```<code>index                  cid  createTime  \
0      0  7000061798167266075  1629828926
1      1  6999869922566783771  1629784228
2      2  7000248857603588891  1629872457
3      3  7000322023545455387  1629889491
4      4  7001271117180977947  1630110475

                                                text  diggCount  \
0                                             Done           1
1  haloo min, yg udah ikutan di misi sebelumnya b...          1
2  bell bottoms maksudnya apa kak?\napakah benar ...          0
3                                            syudah          0
4     kak, perpanjang dong waktu posting videonya :)          1

   replyCommentTotal                  uid        uniqueId
0                  0  6529379534374092801      alikayanti
1                  1  6842932775562642433         fia_654
2                  2  6960940768727417857  keterimadiptn1
3                  0  6806645499672839170   miftahulhaqqu
4                  0  6921267441846830082     elisabetkst
</code>```

Body:
So I have a json file that have multiple level,by using pandas I can read the first level and put it in a dataframe,but the problem is as you can see in the dataframe Column Comments and hastags the second level is inside a column have format of list of dictionary,is there any solution for make the second level dictionary into dataframe. I try to use for loop and json_normalize but it always throw an error. Any suggestion? My code is like this

import pandas as pd
df2 = pd.read_json("data.json")

cid = []
for x in df2["comments"]:
    cid.append(x.get('cid'))

data = pd.DataFrame({'cid':cid})

If i use the code it throw an error since I try access list by string not index.

AttributeError: 'list' object has no attribute 'get'

Even I change it into integer it got dictionary inside a column.How to change the dict inside the column or is there another easier way to do this? Dictionary in column

for x in df2["comments"]:
    cid.append(x[0])
data = pd.DataFrame({'cid':cid})
for y in data:
    print(y.get('cid'))

Example of first row of the data frame

[{'cid': '7000061798167266075', 'createTime': 1629828926, 'text': 'Done ', 'diggCount': 1, 'replyCommentTotal': 0, 'uid': '6529379534374092801', 'uniqueId': 'alikayanti'}, {'cid': '6999869922566783771', 'createTime': 1629784228, 'text': 'haloo min, yg udah ikutan di misi sebelumnya boleh ikutan lagi gaa?', 'diggCount': 1, 'replyCommentTotal': 1, 'uid': '6842932775562642433', 'uniqueId': 'fia_654'}, {'cid': '7000248857603588891', 'createTime': 1629872457, 'text': 'bell bottoms maksudnya apa kak?\napakah benar artinya bel bawah?', 'diggCount': 0, 'replyCommentTotal': 2, 'uid': '6960940768727417857', 'uniqueId': 'keterimadiptn1'}, {'cid': '7000322023545455387', 'createTime': 1629889491, 'text': 'syudah', 'diggCount': 0, 'replyCommentTotal': 0, 'uid': '6806645499672839170', 'uniqueId': 'miftahulhaqqu'}, {'cid': '7001271117180977947', 'createTime': 1630110475, 'text': 'kak, perpanjang dong waktu posting videonya :)', 'diggCount': 1, 'replyCommentTotal': 0, 'uid': '6921267441846830082', 'uniqueId': 'elisabetkst'}]

Body:
Maybe this solves your problem:

Defined the following function which unnests any json:

import json
import pandas as pd

def flatten_nested_json_df(df):
    df = df.reset_index()
    s = (df.applymap(type) == list).all()
    list_columns = s[s].index.tolist()

    s = (df.applymap(type) == dict).all()
    dict_columns = s[s].index.tolist()

    while len(list_columns) > 0 or len(dict_columns) > 0:
        new_columns = []

        for col in dict_columns:
            horiz_exploded = pd.json_normalize(df[col]).add_prefix(f'{col}.')
            horiz_exploded.index = df.index
            df = pd.concat([df, horiz_exploded], axis=1).drop(columns=[col])
            new_columns.extend(horiz_exploded.columns) # inplace

        for col in list_columns:
            #print(f"exploding: {col}")
            df = df.drop(columns=[col]).join(df[col].explode().to_frame())
            new_columns.append(col)

        s = (df[new_columns].applymap(type) == list).all()
        list_columns = s[s].index.tolist()

        s = (df[new_columns].applymap(type) == dict).all()
        dict_columns = s[s].index.tolist()
    return df

and do this:

results = pd.json_normalize(data)
df = pd.DataFrame(results)

outdf = flatten_nested_json_df(df)

which returns:

index                  cid  createTime  \
0      0  7000061798167266075  1629828926
1      1  6999869922566783771  1629784228
2      2  7000248857603588891  1629872457
3      3  7000322023545455387  1629889491
4      4  7001271117180977947  1630110475

                                                text  diggCount  \
0                                             Done           1
1  haloo min, yg udah ikutan di misi sebelumnya b...          1
2  bell bottoms maksudnya apa kak?\napakah benar ...          0
3                                            syudah          0
4     kak, perpanjang dong waktu posting videonya :)          1

   replyCommentTotal                  uid        uniqueId
0                  0  6529379534374092801      alikayanti
1                  1  6842932775562642433         fia_654
2                  2  6960940768727417857  keterimadiptn1
3                  0  6806645499672839170   miftahulhaqqu
4                  0  6921267441846830082     elisabetkst


问:
Laravel: Returning the namespaced owner of a polymorphic relation
I can find a number of discussions regarding this but no clear solution. Here are two links, although I will cover everything in my own question here.

Github Issues

Laravel.io discussion

Simple Explanation

This is a simple explanation of my problem for anyone already familiar with Laravel's polymorphic relationships.

When using $morphClass, the contents of $morphClass which is saved in the database as the morph  "type" is used for the classname when trying to find the owner of a polymorphic relation. This results in an error since the whole point of $morphClass is that it is not a fully namespaced name of the class.

How do you define the classname that the polymorphic relationship should use?

More Detailed Explanation

This is a more detailed explanation explaining exactly what i'm trying to do and why i'm trying to do it with examples.

When using Polymorphic relationships in Laravel whatever is saved as the "morph_type" type in the database is assumed to be the class.

So in this example:

```<code>class Photo extends Eloquent {

    public function imageable()
    {
        return $this->morphTo();
    }

}

class Staff extends Eloquent {

    public function photos()
    {
        return $this->morphOne('Photo', 'imageable');
    }

}

class Order extends Eloquent {

    public function photos()
    {
        return $this->morphOne('Photo', 'imageable');
    }

}
</code>```

The database would look like this:

```<code>staff

 - id - integer
 - name - string

orders

 - id - integer
 - price - integer

photos

 - id - integer
 - path - string
 - imageable_id - integer
 - imageable_type - string
</code>```

Now the first row of photos might look like this:

id,path,imageable_id,imageable_type

1,image.png,1,Staff

Now I can either access the Photo from a Staff model or a Staff member from a Photo model.

```<code>//Find a staff member and dump their photos
$staff = Staff::find(1);

var_dump($staff->photos);

//Find a photo and dump the related staff member
$photo = Photo::find(1);

var_dump($photo->imageable);
</code>```

So far so good. However when I namespace them I run into a problem.

```<code>namespace App/Store;
class Order {}

namespace App/Users;
class Staff {}

namespace App/Photos;
class Photo {}
</code>```

Now what's saved in my database is this:

id,path,imageable_id,imageable_type

1,image.png,1,App/Users/Staff

But I don't want that. That's a terrible idea to have full namespaced class names saved in the database like that!

Fortunately Laravel has an option to set a $morphClass variable. Like so:

```<code>class Staff extends Eloquent {

    protected $morphClass = 'staff';

    public function photos()
    {
        return $this->morphOne('Photo', 'imageable');
    }

}
</code>```

Now the row in my database will look like this, which is awesome!

id,path,imageable_id,imageable_type

1,image.png,1,staff

And getting the photos of a staff member works absolutely fine.

```<code>//Find a staff member and dump their photos
$staff = Staff::find(1);

//This works!
var_dump($staff->photos);
</code>```

However the polymorphic magic of finding the owner of a photo doesn't work:

```<code>//Find a photo and dump the related staff member
$photo = Photo::find(1);

//This doesn't work!
var_dump($photo->imageable);

//Error: Class 'staff' not found
</code>```

Presumably there must be a way to inform the polymorphic relationship of what classname to use when using $morphClass but I cannot find any reference to how this should work in the docs, in the source code or via Google.

Any help?

答:
A simple solution will be to alias the value in imageable_type column in the db to the full class namespace as:</p>
```<code>// app/config/app.php
'aliases' => [
...
'Order' => 'Some\Namespace\Order',
'Staff' => 'Maybe\Another\Namespace\Staff',
...
]
</code>```

Body:
I can find a number of discussions regarding this but no clear solution. Here are two links, although I will cover everything in my own question here.

Github Issues

Laravel.io discussion

Simple Explanation

This is a simple explanation of my problem for anyone already familiar with Laravel's polymorphic relationships.

When using $morphClass, the contents of $morphClass which is saved in the database as the morph  "type" is used for the classname when trying to find the owner of a polymorphic relation. This results in an error since the whole point of $morphClass is that it is not a fully namespaced name of the class.

How do you define the classname that the polymorphic relationship should use?

More Detailed Explanation

This is a more detailed explanation explaining exactly what i'm trying to do and why i'm trying to do it with examples.

When using Polymorphic relationships in Laravel whatever is saved as the "morph_type" type in the database is assumed to be the class.

So in this example:

class Photo extends Eloquent {

    public function imageable()
    {
        return $this->morphTo();
    }

}

class Staff extends Eloquent {

    public function photos()
    {
        return $this->morphOne('Photo', 'imageable');
    }

}

class Order extends Eloquent {

    public function photos()
    {
        return $this->morphOne('Photo', 'imageable');
    }

}

The database would look like this:

staff

 - id - integer
 - name - string

orders

 - id - integer
 - price - integer

photos

 - id - integer
 - path - string
 - imageable_id - integer
 - imageable_type - string

Now the first row of photos might look like this:

id,path,imageable_id,imageable_type

1,image.png,1,Staff

Now I can either access the Photo from a Staff model or a Staff member from a Photo model.

//Find a staff member and dump their photos
$staff = Staff::find(1);

var_dump($staff->photos);

//Find a photo and dump the related staff member
$photo = Photo::find(1);

var_dump($photo->imageable);

So far so good. However when I namespace them I run into a problem.

namespace App/Store;
class Order {}

namespace App/Users;
class Staff {}

namespace App/Photos;
class Photo {}

Now what's saved in my database is this:

id,path,imageable_id,imageable_type

1,image.png,1,App/Users/Staff

But I don't want that. That's a terrible idea to have full namespaced class names saved in the database like that!

Fortunately Laravel has an option to set a $morphClass variable. Like so:

class Staff extends Eloquent {

    protected $morphClass = 'staff';

    public function photos()
    {
        return $this->morphOne('Photo', 'imageable');
    }

}

Now the row in my database will look like this, which is awesome!

id,path,imageable_id,imageable_type

1,image.png,1,staff

And getting the photos of a staff member works absolutely fine.

//Find a staff member and dump their photos
$staff = Staff::find(1);

//This works!
var_dump($staff->photos);

However the polymorphic magic of finding the owner of a photo doesn't work:

//Find a photo and dump the related staff member
$photo = Photo::find(1);

//This doesn't work!
var_dump($photo->imageable);

//Error: Class 'staff' not found

Presumably there must be a way to inform the polymorphic relationship of what classname to use when using $morphClass but I cannot find any reference to how this should work in the docs, in the source code or via Google.

Any help?

Body:
A simple solution will be to alias the value in imageable_type column in the db to the full class namespace as:

// app/config/app.php
'aliases' => [
...
'Order' => 'Some\Namespace\Order',
'Staff' => 'Maybe\Another\Namespace\Staff',
...
]


问:
Enable systemd service in Yocto
I am trying to enable a systemd service automatically after successful boot of my STM32MP1 based Avnger96 board. I am using Yocto Project as build system with Ubuntu 20.04. My image recipe to enable systemd service is example-systemd.bb:

```<code>.
.
inherit systemd

SRC_URI = "file://example.sh \
           file://example.service \
          "

S = "${WORKDIR}"

SYSTEMD_AUTO_ENABLE_${PN} = "enable"
SYSTEMD_PACKAGES = "${PN}"

SYSTEMD_SERVICE_${PN} = "example.service"

do_install_append() {

    install -d 644 ${D}${sysconfdir}/init.d
    install -m 0755 ${WORKDIR}/example.sh ${D}${sysconfdir}/init.d

    install -d ${D}${systemd_system_unitdir}
    install -m 0644 ${WORKDIR}/example.service ${D}${systemd_system_unitdir}
}

FILES_${PN} += "${sysconfdir}/init.d"
FILES_${PN} += "${systemd_system_unitdir}/example.service"

REQUIRED_DISTRO_FEATURES= " systemd"
</code>```

And included in my main image in local.conf with IMAGE_INSTALL_append = " example-systemd"

After building the image, bitbake -e (YOUR_IMAGE) | grep ^DISTRO_FEATURES= shows systemd.

But in my rootfs I can't find systemd/system directory with above service file. And also when I run systemctl status example I get the error -sh: systemctl: command not found.

Update

After including DISTRO_FEATURES_append= " systemd" in the example-service.bb, in the rootfs etc/systemd/system/multi-user.target.wants/ is created and it contains example.service file. But doing cat example.service results in cat: example.service: No such file or directory. Is this expected?

Can anyone please let me know how to run this service with systemd and how to check if service is installed and executed from linux user space?

And also I have one more doubt: Can both Systemd and Sysvinit exist together and some services are run by systemd and others by sysvinit?

Your help will be much appreciated.

Thanks in advance.

P.S: Please let me know if any info is missing here

答:
```<code>DISTRO_FEATURES_append = " systemd"
</code>```

Title: Enable systemd service in Yocto

Body:
I am trying to enable a systemd service automatically after successful boot of my STM32MP1 based Avnger96 board. I am using Yocto Project as build system with Ubuntu 20.04. My image recipe to enable systemd service is example-systemd.bb:

.
.
inherit systemd

SRC_URI = "file://example.sh \
           file://example.service \
          "

S = "${WORKDIR}"

SYSTEMD_AUTO_ENABLE_${PN} = "enable"
SYSTEMD_PACKAGES = "${PN}"

SYSTEMD_SERVICE_${PN} = "example.service"

do_install_append() {

    install -d 644 ${D}${sysconfdir}/init.d
    install -m 0755 ${WORKDIR}/example.sh ${D}${sysconfdir}/init.d

    install -d ${D}${systemd_system_unitdir}
    install -m 0644 ${WORKDIR}/example.service ${D}${systemd_system_unitdir}
}

FILES_${PN} += "${sysconfdir}/init.d"
FILES_${PN} += "${systemd_system_unitdir}/example.service"

REQUIRED_DISTRO_FEATURES= " systemd"

And included in my main image in local.conf with IMAGE_INSTALL_append = " example-systemd"

After building the image, bitbake -e (YOUR_IMAGE) | grep ^DISTRO_FEATURES= shows systemd.

But in my rootfs I can't find systemd/system directory with above service file. And also when I run systemctl status example I get the error -sh: systemctl: command not found.

Update

After including DISTRO_FEATURES_append= " systemd" in the example-service.bb, in the rootfs etc/systemd/system/multi-user.target.wants/ is created and it contains example.service file. But doing cat example.service results in cat: example.service: No such file or directory. Is this expected?

Can anyone please let me know how to run this service with systemd and how to check if service is installed and executed from linux user space?

And also I have one more doubt: Can both Systemd and Sysvinit exist together and some services are run by systemd and others by sysvinit?

Your help will be much appreciated.

Thanks in advance.

P.S: Please let me know if any info is missing here

Body: DISTRO_FEATURES_append = " systemd"


问:
Laravel : method is not supported for this route
the error is : The GET method is not supported for this route. Supported methods: POST.
although the website works on localhost but on the server doesnt work ?? any solutions

```<code>
 protected function methodNotAllowed(array $others, $method)
    {
        throw new MethodNotAllowedHttpException(
            $others,
            sprintf(
                'The %s method is not supported for this route. Supported methods: %s.',
                $method,
                implode(', ', $others)
            )
        );
    }

</code>```

layout

```<code>@extends('install.layout')

@section('content')
<div class="panel panel-default">
  <div class="panel-heading text-center">Login Details</div>
    <div class="panel-body">
       <div class="col-md-12">
            @if ($errors->any())
                <div class="alert alert-danger alert-dismissible">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
                    @foreach ($errors->all() as $error)
                       <p>{{ $error }}</p>
                    @endforeach
                </div>
            @endif
            <form action="{{ url('install/store_user') }}" method="post" autocomplete="off">
                {{ csrf_field() }}
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" class="form-control" name="name" value="{{ old('name') }}" required>
                </div>

                <div class="form-group">
                    <label>Email</label>
                    <input type="email" class="form-control" name="email" value="{{ old('email') }}" required>
                </div>

                <div class="form-group">
                    <label>Password</label>
                    <input type="password" class="form-control" name="password" required>
                </div>
                <button type="submit" class="btn btn-install">Next</button>
            </form>
       </div>
    </div>
</div>
@endsection

</code>```

########################################################################################################################################################
Web Route

```<code><?php
Route::post('install/store_user', 'Install\InstallController@store_user');
?>
</code>```

installController

```<code>    public function store_user(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:191',
            'email' => 'required|string|email|max:191|unique:users',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
                return redirect()->back()
                            ->withErrors($validator)
                            ->withInput();
        }

        $name = $request->name;
        $email = $request->email;
        $password = Hash::make($request->password);

        Installer::createUser($name, $email, $password);

        return redirect('install/system_settings');
    }

</code>```

答: In your form you may give post method but in route you may assign get method. Please cross check it.</p>

Body:
the error is : The GET method is not supported for this route. Supported methods: POST.
although the website works on localhost but on the server doesnt work ?? any solutions

 protected function methodNotAllowed(array $others, $method)
    {
        throw new MethodNotAllowedHttpException(
            $others,
            sprintf(
                'The %s method is not supported for this route. Supported methods: %s.',
                $method,
                implode(', ', $others)
            )
        );
    }

layout

@extends('install.layout')

@section('content')

Login Details

            @if ($errors->any())

                    ×
                    @foreach ($errors->all() as $error)

{{ $error }}

                    @endforeach

            @endif
            <form action="{{ url('install/store_user') }}" method="post" autocomplete="off">
                {{ csrf_field() }}

                    Name
                    <input type="text" class="form-control" name="name" value="{{ old('name') }}" required>

                    Email
                    <input type="email" class="form-control" name="email" value="{{ old('email') }}" required>

                    Password
                    <input type="password" class="form-control" name="password" required>

                <button type="submit" class="btn btn-install">Next</button>
            </form>

@endsection

########################################################################################################################################################
Web Route

<?php
Route::post('install/store_user', 'Install\InstallController@store_user');
?>

installController

    public function store_user(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:191',
            'email' => 'required|string|email|max:191|unique:users',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
                return redirect()->back()
                            ->withErrors($validator)
                            ->withInput();
        }

        $name = $request->name;
        $email = $request->email;
        $password = Hash::make($request->password);

        Installer::createUser($name, $email, $password);

        return redirect('install/system_settings');
    }


问:
Google Cloud Function not deploying on GCP Cloud functions - Function failed on loading user code
I have my python code that works fine on my machine. However, when deploying it on GCP with the correct requirements it is not deploying as it should.
I have resolved all error and now i am just left with the below error

I've not seen this error and cant seem to solve it - has anyone else seen this error?

答:
As mentioned in a similar thread :

Serverless environments such as App Engine, Cloud Functions and Cloud Run, run in a sandbox, similar to gVisor. This sandbox protects the system from
malicious calls and blocks some low level instruction. This one to get the CPU capabilities should be discarded.
I got the same when I ran Tensorflow Serving on Cloud Run.

This error has been discussed in the answer:

The warning is just telling you that OpenBLAS, which is a dependency of Pandas, is not able to determine some settings of Cloud Function environments,
most likely due to Cloud Function runs on virtualized environments. I suggest that you just ignore the warning as it is not an issue in Cloud Function.

For more information, you can refer to a well explained answer on the similar issue.


问:
MissingMethodException : UnityEngine.GameObject.setActive
I have added the below script to the NPC. on clicking on to the NPC the MessageBox (Panel in Canvas) should appear. But the MessageBox.setActive() part is not working. Below is the code.

```<code>import UnityEngine.UI;

var TextBoxOnCheck : int = 0;
var MessageBox : GameObject;
var TextBox : GameObject;
var TextMessage : String;
var QuestBox : GameObject;
var QuestText : GameObject;
var QuestName : String;

function OnMouseDown(){
    if (TextBoxOnCheck == 0) {
        TextBoxOnCheck = 1;
        MessageBox.setActive(true);
        TextBox.GetComponent.<Text>().text = TextMessage;
        QuestName = "Active Quest: 'Recover the loot'";
        QuestText.GetComponent.<Text>().text = QuestName;
    } else {
        TextBoxOnCheck = 0;
        MessageBox.setActive(false);
        TextMessage = "Villager: Get going then.";
    }
}
</code>```

Error:

Rest of the code like changing QuestText to QuestName when clicking on NPC is working fine.

答:
Typo, s should be capitalized, turn it into .SetActive() instead of .setActive()

https://docs.unity3d.com/ScriptReference/GameObject.SetActive.html

Body:
I have added the below script to the NPC. on clicking on to the NPC the MessageBox (Panel in Canvas) should appear. But the MessageBox.setActive() part is not working. Below is the code.

import UnityEngine.UI;

var TextBoxOnCheck : int = 0;
var MessageBox : GameObject;
var TextBox : GameObject;
var TextMessage : String;
var QuestBox : GameObject;
var QuestText : GameObject;
var QuestName : String;

function OnMouseDown(){
    if (TextBoxOnCheck == 0) {
        TextBoxOnCheck = 1;
        MessageBox.setActive(true);
        TextBox.GetComponent.<Text>().text = TextMessage;
        QuestName = "Active Quest: 'Recover the loot'";
        QuestText.GetComponent.<Text>().text = QuestName;
    } else {
        TextBoxOnCheck = 0;
        MessageBox.setActive(false);
        TextMessage = "Villager: Get going then.";
    }
}

Error:

Rest of the code like changing QuestText to QuestName when clicking on NPC is working fine.


问:
how to choose an id that has only one row?
i have this table:

id
item

1
a

1
b

2
c

3
d

3
g

3
f

4
ggg

4
gf

i want that the query will show:
only 1 id (randomly from the options)
that has only 2 or less items
(that means- to show 1 id from the ids: 1,2 or 4)

答:
Use:

```<code>select id
from test_tbl
group by id
having count(item) <=2
order by rand() limit 1;
</code>```

Rsult:

```<code>id
2
</code>```

Demo

HAVING

RAND()

Body:
Use:

select id
from test_tbl
group by id
having count(item) <=2
order by rand() limit 1;

Rsult:

id
2

Demo

HAVING

RAND()


问:
Oracle query to find any special character in first position or end position of the field value
I have a table in Oracle database with special characters attached at first and last position in the field value. I want to eliminate those special characters while querying the table. I have used INSTR function but I had to apply for each and every special character using CASE expression.
Is there a way to eliminate any special characters that is attached only at first and last positions in one shot?

The query I am using as is below:
CASE WHEN
INSTR(emp_address,'"')=1 THEN REPLACE((emp_address,'"', '').
.
.
.

答:
You can use regular expressions to replace the leading and trailing character of a string if they match the regular expression pattern. For example, if your definition of a "special character" is anything that is not an alpha-numeric character then you can use the regular expression:

^ the start-of-the-string then

[^[:alnum:]] any single character that does not match the POSIX alpha-numeric character group

| or

[^[:alnum:]] any single character that does not match the POSIX alpha-numeric character group then

$ the end-of-the-string.

Like this:

SELECT emp_address,
       REGEXP_REPLACE(
         emp_address,
         '^[^[:alnum:]]|[^[:alnum:]]$'
       ) AS simplified_emp_address
FROM   table_name
```
<p>Which, for the sample data:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE table_name (emp_address) AS
SELECT 'test' FROM DUAL UNION ALL
SELECT '"test2"' FROM DUAL UNION ALL
SELECT 'Not "this" one' FROM DUAL;
</code>```

Outputs:

EMP_ADDRESS
SIMPLIFIED_EMP_ADDRESS

test
test

"test2"
test2

Not "this" one
Not "this" one

If you have a more complicated definition of a special character then change the regular expression appropriately.

db<>fiddle here

Body:
You can use regular expressions to replace the leading and trailing character of a string if they match the regular expression pattern. For example, if your definition of a "special character" is anything that is not an alpha-numeric character then you can use the regular expression:

^ the start-of-the-string then

[^[:alnum:]] any single character that does not match the POSIX alpha-numeric character group

| or

[^[:alnum:]] any single character that does not match the POSIX alpha-numeric character group then

$ the end-of-the-string.

Like this:

SELECT emp_address,
       REGEXP_REPLACE(
         emp_address,
         '^[^[:alnum:]]|[^[:alnum:]]$'
       ) AS simplified_emp_address
FROM   table_name

Which, for the sample data:

CREATE TABLE table_name (emp_address) AS
SELECT 'test' FROM DUAL UNION ALL
SELECT '"test2"' FROM DUAL UNION ALL
SELECT 'Not "this" one' FROM DUAL;

Outputs:

EMP_ADDRESS
SIMPLIFIED_EMP_ADDRESS

test
test

"test2"
test2

Not "this" one
Not "this" one

If you have a more complicated definition of a special character then change the regular expression appropriately.

db<>fiddle here


问:
Iteration through a list using Selenium
I'm trying to iterate a limited number of  elements from html, which are actually lists generated from webdriver.

I've tried doing this:

```<code>for i in range(9):
    print(driver.find_element(By.CSS_SELECTOR, "thead > tr th:nth-child("+[i]+") > span").text)
</code>```

And I received the following error:

print(driver.find_element(By.CSS_SELECTOR, "tbody > tr
td:nth-child("+[i]+") > span").text) TypeError: can only concatenate
str (not "list") to str

Here is the html snippet:

Date	Open	High	Low	Close*	Adj Close**	Volume

```

It's all from this page: https://finance.yahoo.com/quote/BTC-EUR/history

答:
As suggested in the Update section of this answer to extract the text only from the first  which is a decendent of the first  and you are restricting the Locator Strategy as:

```<code>driver.find_element(By.CSS_SELECTOR, "thead > tr th:nth-child(1) > span")
</code>```

This usecase

To iterate through all the  elements from html of the website you can use List Comprehension and you can use the following Locator Strategy:

```<code>driver.get('https://finance.yahoo.com/quote/BTC-EUR/history')
print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "thead > tr th > span")))])
</code>```

Console Output:

```<code>['Date', 'Open', 'High', 'Low', 'Close*', 'Adj Close**', 'Volume', 'Symbol', 'Last Price', 'Change', '% Change']
</code>```

To retrict the number of elements within the List to 9 elements you can use:

```<code>driver.get('https://finance.yahoo.com/quote/BTC-EUR/history')
print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "thead > tr th > span")))][:9])
</code>```

Title: Iteration through a list using Selenium

Body:
I'm trying to iterate a limited number of  elements from html, which are actually lists generated from webdriver.

I've tried doing this:

for i in range(9):
    print(driver.find_element(By.CSS_SELECTOR, "thead > tr th:nth-child("+[i]+") > span").text)

And I received the following error:

print(driver.find_element(By.CSS_SELECTOR, "tbody > tr
td:nth-child("+[i]+") > span").text) TypeError: can only concatenate
str (not "list") to str

Here is the html snippet:

Date	Open	High	Low	Close*	Adj Close**	Volume

It's all from this page: https://finance.yahoo.com/quote/BTC-EUR/history

Body:
As suggested in the Update section of this answer to extract the text only from the first <span> which is a decendent of the first <th> and you are restricting the Locator Strategy as:

driver.find_element(By.CSS_SELECTOR, "thead > tr th:nth-child(1) > span")

This usecase

To iterate through all the <span> elements from html of the website you can use List Comprehension and you can use the following Locator Strategy:

driver.get('https://finance.yahoo.com/quote/BTC-EUR/history')
print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "thead > tr th > span")))])

Console Output:

['Date', 'Open', 'High', 'Low', 'Close*', 'Adj Close**', 'Volume', 'Symbol', 'Last Price', 'Change', '% Change']

To retrict the number of elements within the List to 9 elements you can use:

driver.get('https://finance.yahoo.com/quote/BTC-EUR/history')
print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "thead > tr th > span")))][:9])


问:
VS Code Omnipascal on xUbuntu 20.0.4 and FPC 3.2.0 compile error
I have a fresh installation of xubuntu vers. 20.0.4
I have installed Visual Studio Code vers. 1.64.0
I have installed: fpc-laz_3.2.0-1_amd64.deb
fpc-src_3.2.0-1_amd64.deb
lazarus-project_2.0.10-0_amd64.deb
All installed correctly
I opened a project in the Lazarus IDE called Project1, Compiled and ran the project
The form was generated correctly.
I installed the Omnipascal vers 0.19.0 extension in VS Code
In Omnipascal settings in VS Code i have set

Omnipascal to build scripts

Default development environment: FreePascal

Free Pascal Source Path: /usr/share/fpcsrc/3.2.0

Lazbuild Path: /usr/share/lazarus/2.0.10/ide/
I have configured a build task

```<code>{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "echo",
            "type": "shell",
            "command": "fpc",
            "args": [
                "${file}"
            ],
            "problemMatcher": [],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}
</code>```

When I open either the lpi project file or the unit1 pas file
I get errors

```<code>Free Pascal Compiler version 3.2.0 [2020/07/07] for x86_64
Copyright (c) 1993-2020 by Florian Klaempfl and others
Target OS: Linux for x86-64
Compiling /media/ian/vsts/laz/project1.lpr
project1.lpr(9,3) Fatal: Can't find unit Interfaces used by project1
Fatal: Compilation aborted
Error: /usr/bin/ppcx64 returned an error exitcode
The terminal process "/usr/bin/bash '-c', 'fpc /media/ian/vsts/laz/project1.lpr'" failed to launch (exit code: 1).
</code>```

It looks like the interfaces.ppu and forms.ppu are not been found
I searched for the files and added ther paths to:
Omnipascal : Searchpath

To no avail

Question 1. Is this error a Visual Studio Error or a Free pascal compiler error
Question 2. The Omnipascal installation instructions for Linux setting
Lazbuild Path: requires a path to Lazbuild.exe. There is no such file in my          installation. is this a Typo.

Any help will be greatfully received

答:
Lazarus adds configuration parameters (most notably, where lazarus files like "interfaces" are found) to the build.

While I don't vscode nor ominpascal, from your commandline I gather your omni solution does not.

Go into lazarus, load project, goto project -> project options -> show option to learn what is passed to the compiler. (note, some might be redundant and already in fpc.cfg).

Body:
I have a fresh installation of xubuntu vers. 20.0.4
I have installed Visual Studio Code vers. 1.64.0
I have installed: fpc-laz_3.2.0-1_amd64.deb
fpc-src_3.2.0-1_amd64.deb
lazarus-project_2.0.10-0_amd64.deb
All installed correctly
I opened a project in the Lazarus IDE called Project1, Compiled and ran the project
The form was generated correctly.
I installed the Omnipascal vers 0.19.0 extension in VS Code
In Omnipascal settings in VS Code i have set

Omnipascal to build scripts

Default development environment: FreePascal

Free Pascal Source Path: /usr/share/fpcsrc/3.2.0

Lazbuild Path: /usr/share/lazarus/2.0.10/ide/
I have configured a build task

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "echo",
            "type": "shell",
            "command": "fpc",
            "args": [
                "${file}"
            ],
            "problemMatcher": [],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

When I open either the lpi project file or the unit1 pas file
I get errors

Free Pascal Compiler version 3.2.0 [2020/07/07] for x86_64
Copyright (c) 1993-2020 by Florian Klaempfl and others
Target OS: Linux for x86-64
Compiling /media/ian/vsts/laz/project1.lpr
project1.lpr(9,3) Fatal: Can't find unit Interfaces used by project1
Fatal: Compilation aborted
Error: /usr/bin/ppcx64 returned an error exitcode
The terminal process "/usr/bin/bash '-c', 'fpc /media/ian/vsts/laz/project1.lpr'" failed to launch (exit code: 1).

It looks like the interfaces.ppu and forms.ppu are not been found
I searched for the files and added ther paths to:
Omnipascal : Searchpath

To no avail

Question 1. Is this error a Visual Studio Error or a Free pascal compiler error
Question 2. The Omnipascal installation instructions for Linux setting
Lazbuild Path: requires a path to Lazbuild.exe. There is no such file in my          installation. is this a Typo.

Any help will be greatfully received


问:
How to create Background Services in iPhone like Android?
I want to create a function which work in background in iPhone.
I want to set Notification for any change in NSUSerDefault Value.
I saw many Services running in Background  of Android.
How can I Make background Service this in iPhone of some application ??</p>

答: iOS apps are only allowed to run in the background for a few well-defined reasons, such as implementing VoIP and playing audio. Monitoring preferences isn't one of the permitted reasons. That's okay, though, because each app runs in its own sandbox and is unable to affect the environments of other apps, and other app will be able to change your app's preferences.</p>


问:
(Swift)How to dectect a "fieldEditor" resignFirstResponder() (Mac/Cocoa)
What I intend to do is validate four NSTextFields, I will try to make sure that all of them are filled correctly, and completely.

textField and alert

As the picture shows: if a user types anything in the 1st NSTextField, types something wrong or leaves it blank in the 2nd NSTextField, press Enter or click outside the boundary, it should show an alert, and try to stop the user from resigning from the 2nd NSTextField, and he should confirm his input in 2nd NSTextField.

What I have tried and the problems I faced:

Use textFieldShouldEndEditing(_:)

When I type something. Wrong, show an alert and return false. It runs well.

But if I type nothing, textFieldShouldEndEditing(_:) will not invoke. (Because it won't be triggered without typing)

```<code> func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
    if control.stringValue != validInput{
       showAlert()
       return false
    }else{
       return true
    }
}// plz ignore the delegation
</code>```

CustomNSTextField & resignFirstResponder()

When the user clicked NSTextField, NSTextField would becomeFirstResponder(), followed by ResignFirstResponder() because the FieldEditor would enter. So it is invalid to monitor resignFirstResponder().

Use textFieldShouldEndEditing(_:)

When I type something wrong or type nothing, press Enter or click outside the boundary, show an alert, but it is difficult to stop the following functions: for example, if I click the button "open", it may show an alert and an openFile dialog in the meantime.

What may solve my problems：

Whether there is a trick that invokes textFieldDidBeginEditing (_:) when NSTextField resignFirstResponder() ?

Whether there is a function that monitors the window's current fieldEditor resignFirstResponder(), and it can return false while I want the user to confirm his input.

答:
I found it NOT as difficult as I thought to write a custom fieldEditor. Follow the tutorial here. I post the essential part of my code here for anyone who is facing similar problems.</p>
```<code>class CustomFieldCell: NSTextFieldCell {
    static var durationFieldEditor: CustomFieldEditor = {
        let customFieldEditor = CustomFieldEditor()
        return fieldEditor
    }()

    override func fieldEditor(for controlView: NSView) -> NSTextView? {
        return Self.customFieldEditor
    }
}

class CustomFieldEditor: NSTextView {

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        commonInit()
    }

    override init(frame frameRect: NSRect, textContainer container: NSTextContainer?) {
        super.init(frame: frameRect, textContainer: container)
        commonInit()
    }

    override func becomeFirstResponder() -> Bool {
        // condition
        return super.becomeFirstResponder()
    }

    override func resignFirstResponder() -> Bool {
        // condition
        return super.resignFirstResponder()
    }

    private func commonInit() {
        isFieldEditor = true
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

Body:
What I intend to do is validate four NSTextFields, I will try to make sure that all of them are filled correctly, and completely.

textField and alert

As the picture shows: if a user types anything in the 1st NSTextField, types something wrong or leaves it blank in the 2nd NSTextField, press Enter or click outside the boundary, it should show an alert, and try to stop the user from resigning from the 2nd NSTextField, and he should confirm his input in 2nd NSTextField.

What I have tried and the problems I faced:

Use textFieldShouldEndEditing(_:)

When I type something. Wrong, show an alert and return false. It runs well.

But if I type nothing, textFieldShouldEndEditing(_:) will not invoke. (Because it won't be triggered without typing)

 func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
    if control.stringValue != validInput{
       showAlert()
       return false
    }else{
       return true
    }
}// plz ignore the delegation

CustomNSTextField & resignFirstResponder()

When the user clicked NSTextField, NSTextField would becomeFirstResponder(), followed by ResignFirstResponder() because the FieldEditor would enter. So it is invalid to monitor resignFirstResponder().

Use textFieldShouldEndEditing(_:)

When I type something wrong or type nothing, press Enter or click outside the boundary, show an alert, but it is difficult to stop the following functions: for example, if I click the button "open", it may show an alert and an openFile dialog in the meantime.

What may solve my problems：

Whether there is a trick that invokes textFieldDidBeginEditing (_:) when NSTextField resignFirstResponder() ?

Whether there is a function that monitors the window's current fieldEditor resignFirstResponder(), and it can return false while I want the user to confirm his input.

Body:
I found it NOT as difficult as I thought to write a custom fieldEditor. Follow the tutorial here. I post the essential part of my code here for anyone who is facing similar problems.

class CustomFieldCell: NSTextFieldCell {
    static var durationFieldEditor: CustomFieldEditor = {
        let customFieldEditor = CustomFieldEditor()
        return fieldEditor
    }()

    override func fieldEditor(for controlView: NSView) -> NSTextView? {
        return Self.customFieldEditor
    }
}

class CustomFieldEditor: NSTextView {

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        commonInit()
    }

    override init(frame frameRect: NSRect, textContainer container: NSTextContainer?) {
        super.init(frame: frameRect, textContainer: container)
        commonInit()
    }

    override func becomeFirstResponder() -> Bool {
        // condition
        return super.becomeFirstResponder()
    }

    override func resignFirstResponder() -> Bool {
        // condition
        return super.resignFirstResponder()
    }

    private func commonInit() {
        isFieldEditor = true
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


问:
Copying LookupId into all rows in SSIS
I have two tables, one is LookUpTable where I have an id for AttendanceType = Remote. And I have another table where there is a column called AttendanceType.

I want to fetch the id from LookupTable and copy in all rows of another table into the column AttendanceType in SSIS package?

答:
You can use a MERGE JOIN query depending on your RDBMS.
You can also use the MERGE JOIN component and the SSIS OLE DB Destination. The data coming out of the sources must be sorted. To tell SSIS that the data is sorted, right-click on your source component. Click on show advanced editor then on input and output properties. Then pass the IsSorted box to True.
Then, you must indicate to SSIS which column acts as SortKey, ie on which column to sort the data.

Title: Copying LookupId into all rows in SSIS


问:
How to display Splash screen in reactjs
I have two codes for Splash.jsx and one for homepage.jsx. All I want is to display the Splash screen once the Homepage is not in use, but I have no idea how to integrate the splash screen with the Homepage and set the timer, so the splash screen is displayed once I don't use Homepage. It would be great to help me out with showing the splash screen once the Homepage is not in use.
Homepage.jsx

```<code>import React from 'react';

import Card from '../Card/Card'
import img2 from '../../Assets/AutoLoan.png'
import img3 from '../../Assets/KYC.png'
import img4 from '../../Assets/VIsa.png'
import './Homepage.css'

import {
  Swiper,
  SwiperSlide
}
from 'swiper/react';
import 'swiper/css';
import { Navigation } from 'swiper';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/scrollbar';
import { Link } from 'react-router-dom';

 const Homepage= () => {
   return (
     <div>

     <div className="background">

         <div className="welcome__heading">
                <h1>Welcome!!</h1>
              </div>
              <div className= "customer__support">
           <h2>We are here for customer service.</h2>
            </div >
            <div className="swiper_container">
               <Swiper
                modules={[Navigation]}
                navigation
              spaceBetween={10}
              slidesPerView={3}
              onSwiper={(swiper) => console.log(swiper)}
                onSlideChange={() => console.log('slide change')}
                loop={true}
              >
           <SwiperSlide>
             <Link to="AutoLoan">
               <Card imgsrc={img2} alt="AutoLoan" title="Auto Loan" />
             </Link>
           </SwiperSlide>
           <SwiperSlide>
             <Link to="KYC">
               <Card imgsrc={img3} alt="KYC" title="KYC Form" />
             </Link>
           </SwiperSlide>
           <SwiperSlide>
             <Link to="Debit">
               <Card imgsrc={img4} alt="Visa" title="Visa Debit Card" />
             </Link>
           </SwiperSlide>
            </Swiper>
            </div>
            <div ClassName="button">

                <Link to = "Location">
                <button className = "btn1">
                  <i className = "fa fa-map"></i>
              </button>
              </Link>
              <Link to = "Calculator">

              <button className = "btn2">
               <i className = "fa fa-calculator"></i>
              </button>
         </Link>
         </div>
       </div>
       </div>

          );

}

export default Homepage
</code>```

Splash.jsx

```<code>import React from 'react';
import './Splash.css'
import img2 from '../../Assets/Header.png'
import img8 from '../../Assets/hand.svg'

const Splash = () => {

    return (
        <div>
            <div className="bg2">
            <div className="header__body">
            <div className="header__left">
                <div className="header__left__image">
                    <img src = {img2} alt="Header"/>
                </div>
                <h1 >Laxmi Bank</h1>
               </div>
            <div className="header__right">
            <h1 >23℃/11:00AM</h1>
                    </div>

        </div>

            </div>
            <div className="splash">
                <h1>TAP HERE</h1>

            <div className= "blink">
                <img src = {img8} alt = "taphand" />

             </div>
        </div>
        </div>
    );
};

export default Splash;
</code>```

The splash screen should appear after 2 sec of not using Homepage, and once we tap on the splash screen the Homepage should appear again and once it is idle the splash screen should appear and vice versa. and I have no idea how to set the timer and control this component. So, it would be good if someone would help me out.

答: You can use react-idle-timer package. A working solution exists here</p>

Title: How to display Splash screen in reactjs

Body:
I have two codes for Splash.jsx and one for homepage.jsx. All I want is to display the Splash screen once the Homepage is not in use, but I have no idea how to integrate the splash screen with the Homepage and set the timer, so the splash screen is displayed once I don't use Homepage. It would be great to help me out with showing the splash screen once the Homepage is not in use.
Homepage.jsx

import React from 'react';

import Card from '../Card/Card'
import img2 from '../../Assets/AutoLoan.png'
import img3 from '../../Assets/KYC.png'
import img4 from '../../Assets/VIsa.png'
import './Homepage.css'

import {
  Swiper,
  SwiperSlide
}
from 'swiper/react';
import 'swiper/css';
import { Navigation } from 'swiper';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/scrollbar';
import { Link } from 'react-router-dom';

 const Homepage= () => {
   return (

Welcome!!

We are here for customer service.

               <Swiper
                modules={[Navigation]}
                navigation
              spaceBetween={10}
              slidesPerView={3}
              onSwiper={(swiper) => console.log(swiper)}
                onSlideChange={() => console.log('slide change')}
                loop={true}
              >
           <SwiperSlide>
             <Link to="AutoLoan">
               <Card imgsrc={img2} alt="AutoLoan" title="Auto Loan" />
             </Link>
           </SwiperSlide>
           <SwiperSlide>
             <Link to="KYC">
               <Card imgsrc={img3} alt="KYC" title="KYC Form" />
             </Link>
           </SwiperSlide>
           <SwiperSlide>
             <Link to="Debit">
               <Card imgsrc={img4} alt="Visa" title="Visa Debit Card" />
             </Link>
           </SwiperSlide>
            </Swiper>

                <Link to = "Location">
                <button className = "btn1">

              </button>
              </Link>
              <Link to = "Calculator">

              <button className = "btn2">

              </button>
         </Link>

          );

}

export default Homepage

Splash.jsx

import React from 'react';
import './Splash.css'
import img2 from '../../Assets/Header.png'
import img8 from '../../Assets/hand.svg'

const Splash = () => {

    return (

Laxmi Bank

23℃/11:00AM

TAP HERE

    );
};

export default Splash;

The splash screen should appear after 2 sec of not using Homepage, and once we tap on the splash screen the Homepage should appear again and once it is idle the splash screen should appear and vice versa. and I have no idea how to set the timer and control this component. So, it would be good if someone would help me out.


问:
Validate form without submitting
I want to validate the form without submitting. I do not intend to refresh the page. I'm trying this way but it's not validating.

<form method="POST" class="row g-3">

    TIPO DE ALERTA *
    <select class="form-select chosen-select" name="Tipo" id="Tipo" required>
    <option selected>Selecione opções</option>
    <option value="1">Teste</option>
    <option value="2">Teste1</option>
    </select>

    Assunto *
    <input type="text" class="form-control" id="Assunto" name="Assunto" required>

    <button type="button" class="btn-wide btn btn-success" style="float: right; margin-right: 5%; margin-top: 1%;" onclick="insert_form();"> Enviar </button>

</form>```

I can validate the form with js, but that way I have to put the button with type="submit", but I don't want it to refresh the page

答:
You can use events like onchange or onkeyup to detect changes and run your validation

I wrote an example for the text input, whenever the user presses a button it runs the validate function

function validate(value) {
console.log("addvalidation code here", value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form method="POST" class="row g-3">

  <div class="col-md-4">
    <label for="Tipo" class="form-label">TIPO DE ALERTA <span style="color: red;">*</span></label>
    <select class="form-select chosen-select" name="Tipo" id="Tipo" required>
    <option selected>Selecione opções</option>
    <option value="1">Teste</option>
    <option value="2">Teste1</option>
    </select>
  </div>
  <div class="col-md-6">
    <label for="Assunto" class="form-label">Assunto <span style="color: red;">*</span></label>
    <input type="text" class="form-control" id="Assunto" name="Assunto" onkeyup="validate(this.value)" required>
  </div>
  <div class="col-12">
    <button type="button" class="btn-wide btn btn-success" style="float: right; margin-right: 5%; margin-top: 1%;" onclick="insert_form();"> Enviar <i class="metismenu-icon pe-7s-paper-plane"></i></button>
  </div>
</form></code>```

Title: Validate form without submitting

Body:
I want to validate the form without submitting. I do not intend to refresh the page. I'm trying this way but it's not validating.

<form method="POST" class="row g-3">

    TIPO DE ALERTA *
    <select class="form-select chosen-select" name="Tipo" id="Tipo" required>
    <option selected>Selecione opções</option>
    <option value="1">Teste</option>
    <option value="2">Teste1</option>
    </select>

    Assunto *
    <input type="text" class="form-control" id="Assunto" name="Assunto" required>

    <button type="button" class="btn-wide btn btn-success" style="float: right; margin-right: 5%; margin-top: 1%;" onclick="insert_form();"> Enviar </button>

</form>

I can validate the form with js, but that way I have to put the button with type="submit", but I don't want it to refresh the page

Body:
You can use events like onchange or onkeyup to detect changes and run your validation

I wrote an example for the text input, whenever the user presses a button it runs the validate function

function validate(value) {
console.log("addvalidation code here", value);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form method="POST" class="row g-3">

  <div class="col-md-4">
    <label for="Tipo" class="form-label">TIPO DE ALERTA <span style="color: red;">*</span></label>
    <select class="form-select chosen-select" name="Tipo" id="Tipo" required>
    <option selected>Selecione opções</option>
    <option value="1">Teste</option>
    <option value="2">Teste1</option>
    </select>
  </div>
  <div class="col-md-6">
    <label for="Assunto" class="form-label">Assunto <span style="color: red;">*</span></label>
    <input type="text" class="form-control" id="Assunto" name="Assunto" onkeyup="validate(this.value)" required>
  </div>
  <div class="col-12">
    <button type="button" class="btn-wide btn btn-success" style="float: right; margin-right: 5%; margin-top: 1%;" onclick="insert_form();"> Enviar <i class="metismenu-icon pe-7s-paper-plane"></i></button>
  </div>
</form>


问:
Starting Coroutine in Main Thread
So I'm trying to execute a UnityWebrequest, which needs to start from a Coroutine.
Now trying to Debug everything at some point I figured out calling the Coroutine from the Start function works (receiving the Debug.Log messages), but calling it from a normal function it will not work (I do not receive the debug messages within GetRequest).

Hence I think that for some reason the Coroutine is not running on the main-thread (as also no error appears).

Does anybody know how I can enforce a Coroutine to run on the main-thread or another solution to my issue?

Here you'll find the code where WebGet is being called from a class that is not in Monobehaviour, but the class containing WebGet & GetRequest is.

(Please ignore the request variable within WebGet this will be for a later stage.

```<code> public UnityWebRequest WebGet(string url)
        {
            Debug.Log("This is the URL Get " + url);
            var request = UnityWebRequest.Get(url);

            Debug.Log("Request URL: " + request.url);

            StartCoroutine(GetRequest(url));

            Debug.Log("After Coroutine");

            return request;
        }

private IEnumerator GetRequest(string url)
        {
            var request = UnityWebRequest.Get(url);

            Debug.Log("This is the URL inside coroutine " + url);

            yield return request.SendWebRequest();

            if (request.isNetworkError)
            {
                Debug.Log("Error While Sending: " + request.error);
            }
            else
            {
                Debug.Log("Received: " + request.result);
            }

        }
</code>```

答:
Most of the Unity API can only be used on the Unity main-thread, StartCoroutine is one of those things.

or another solution to my issue

If you already are on a background thread you can also simply use UnityWebRequest.Get without any Coroutine and just wait using e.g.

```<code>request.SendWebRequest();
while(!request.isDone)
{
    // depends on your use case, but in general for the love of your CPU
    // you do want to wait a specific amount that is "ok" as a delay
    // you could of curse reduce this to approximately frame wise check by using e.g. 17 ms (=> checks 60 times per second)
    Thread.Sleep(50); // checks 20 times per second
}

if (request.isNetworkError)
{
    Debug.Log("Error While Sending: " + request.error);
}
else
{
    Debug.Log("Received: " + request.result);
}
</code>```

Have in mind though that your are still on a background thread and also other Unity API calls might not be allowed at this point.

If your method is not on a background thread in general note that StartCoroutine does NOT delay the method calling it (this would be exactly what we want to avoid by using a Coroutine) but rather immediately continues with the rest of your code.

You can of course do something like

```<code>var request = UnityWebRequest.Get(url);
request.SendWebRequest();
return request;
</code>```

without yielding it and outside of any Coroutine but then it is up to you to ensure that request.isDone is true before you continue accessing and using the results.

How I can enforce a Coroutine to run on the main-thread?

The alternative in order to force things happening on the main thread you can use a pattern often called Main thread dispatcher. A simplified version could look like e.g.

```<code>public class MainThreadDispatcher : MonoBehaviour
{
    #region Singleton pattern (optional)
    private static MainThreadDispatcher _instance;
    public static MainThreadDispatcher Instance => _instance;

    private void Awake()
    {
        if(_instance && _instance != this)
        {
            Destroy(gameObject);
            return;
        }

        _instance = this;
        DontDestroyOnLoad(gameObject);
    }
    #endregion Singleton

    #region Dispatcher
    // You use a thread-safe collection first-in first-out so you can pass on callbacks between the threads
    private readonly ConcurrentQueue<Action> mainThreadActions = new ConcurrentQueue<Action>();

    // This now can be called from any thread/task etc
    // => dispatched action will be executed in the next Unity Update call
    public void DoInMainThread(Action action);
    {
        mainThreadActions.Enqueue(action);
    }

    // In the Unity main thread Update call routine you work off whatever has been enqueued since the last frame
    private void Update()
    {
        while(mainThreadActions.TryDequeue(out var action))
        {
            action?.Invoke();
        }
    }
    #endregion Dispatcher
}
</code>```

and then in your case you could use

```<code>//MainThreadDispatcher.Instance.DoInMainThread(() =>
yourMainThreadDispatcherReference.DoInMainThread(() =>
{
    StartCoroutine(GetRequest(url));
});
</code>```

Title: Starting Coroutine in Main Thread

Body:
So I'm trying to execute a UnityWebrequest, which needs to start from a Coroutine.
Now trying to Debug everything at some point I figured out calling the Coroutine from the Start function works (receiving the Debug.Log messages), but calling it from a normal function it will not work (I do not receive the debug messages within GetRequest).

Hence I think that for some reason the Coroutine is not running on the main-thread (as also no error appears).

Does anybody know how I can enforce a Coroutine to run on the main-thread or another solution to my issue?

Here you'll find the code where WebGet is being called from a class that is not in Monobehaviour, but the class containing WebGet & GetRequest is.

(Please ignore the request variable within WebGet this will be for a later stage.

 public UnityWebRequest WebGet(string url)
        {
            Debug.Log("This is the URL Get " + url);
            var request = UnityWebRequest.Get(url);

            Debug.Log("Request URL: " + request.url);

            StartCoroutine(GetRequest(url));

            Debug.Log("After Coroutine");

            return request;
        }

private IEnumerator GetRequest(string url)
        {
            var request = UnityWebRequest.Get(url);

            Debug.Log("This is the URL inside coroutine " + url);

            yield return request.SendWebRequest();

            if (request.isNetworkError)
            {
                Debug.Log("Error While Sending: " + request.error);
            }
            else
            {
                Debug.Log("Received: " + request.result);
            }

        }

Body:
Most of the Unity API can only be used on the Unity main-thread, StartCoroutine is one of those things.

or another solution to my issue

If you already are on a background thread you can also simply use UnityWebRequest.Get without any Coroutine and just wait using e.g.

request.SendWebRequest();
while(!request.isDone)
{
    // depends on your use case, but in general for the love of your CPU
    // you do want to wait a specific amount that is "ok" as a delay
    // you could of curse reduce this to approximately frame wise check by using e.g. 17 ms (=> checks 60 times per second)
    Thread.Sleep(50); // checks 20 times per second
}

if (request.isNetworkError)
{
    Debug.Log("Error While Sending: " + request.error);
}
else
{
    Debug.Log("Received: " + request.result);
}

Have in mind though that your are still on a background thread and also other Unity API calls might not be allowed at this point.

If your method is not on a background thread in general note that StartCoroutine does NOT delay the method calling it (this would be exactly what we want to avoid by using a Coroutine) but rather immediately continues with the rest of your code.

You can of course do something like

var request = UnityWebRequest.Get(url);
request.SendWebRequest();
return request;

without yielding it and outside of any Coroutine but then it is up to you to ensure that request.isDone is true before you continue accessing and using the results.

How I can enforce a Coroutine to run on the main-thread?

The alternative in order to force things happening on the main thread you can use a pattern often called Main thread dispatcher. A simplified version could look like e.g.

public class MainThreadDispatcher : MonoBehaviour
{
    #region Singleton pattern (optional)
    private static MainThreadDispatcher _instance;
    public static MainThreadDispatcher Instance => _instance;

    private void Awake()
    {
        if(_instance && _instance != this)
        {
            Destroy(gameObject);
            return;
        }

        _instance = this;
        DontDestroyOnLoad(gameObject);
    }
    #endregion Singleton

    #region Dispatcher
    // You use a thread-safe collection first-in first-out so you can pass on callbacks between the threads
    private readonly ConcurrentQueue<Action> mainThreadActions = new ConcurrentQueue<Action>();

    // This now can be called from any thread/task etc
    // => dispatched action will be executed in the next Unity Update call
    public void DoInMainThread(Action action);
    {
        mainThreadActions.Enqueue(action);
    }

    // In the Unity main thread Update call routine you work off whatever has been enqueued since the last frame
    private void Update()
    {
        while(mainThreadActions.TryDequeue(out var action))
        {
            action?.Invoke();
        }
    }
    #endregion Dispatcher
}

and then in your case you could use

//MainThreadDispatcher.Instance.DoInMainThread(() =>
yourMainThreadDispatcherReference.DoInMainThread(() =>
{
    StartCoroutine(GetRequest(url));
});


问:
TypeError: Cannot read properties of undefined (reading 'execute')
I have an error
CODE:

const prefix = '-';

import fs from 'fs'

client.commands = new DiscordJS.Collection();

const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.cjs'));
for(const file of commandFiles){
    const command = import(`./commands/${file}`);

    client.commands.set(command.name, command);
}

client.on('messageCreate', (message) => {
    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ + /);
    const command = args.shift().toLowerCase();

    if (command === `test`){
        client.commands.get('test').execute(message, args);
    }
});
```
<p>My test.cjs CODE:</p>
<pre class="lang-js prettyprint-override"><code>module.exports = {
    name: 'test',
    description: "This is a test",
    execute(message, args){
        message.channel.send('Test is working');
    }
}
</code>```

Does any1 know how to help??
The Console Error Message is

If any1 can help that would be amazing!
Have a good day!

https://i.stack.imgur.com/G6mOV.png

答:
.cjs is CommonJS file, but your code can run on JavaScript.
Try changing your extension to .js.

Body:
I have an error
CODE:

const prefix = '-';

import fs from 'fs'

client.commands = new DiscordJS.Collection();

const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.cjs'));
for(const file of commandFiles){
    const command = import(`./commands/${file}`);

    client.commands.set(command.name, command);
}

client.on('messageCreate', (message) => {
    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ + /);
    const command = args.shift().toLowerCase();

    if (command === `test`){
        client.commands.get('test').execute(message, args);
    }
});

My test.cjs CODE:

module.exports = {
    name: 'test',
    description: "This is a test",
    execute(message, args){
        message.channel.send('Test is working');
    }
}

Does any1 know how to help??
The Console Error Message is

If any1 can help that would be amazing!
Have a good day!

https://i.stack.imgur.com/G6mOV.png


问:
Combine two freemarker hash with same key inside table
My two hash/maps are as below. I want to get the value corresponding to the key from the first map and second map and then add them to table

Map 1
[
{
"key": "1",
"value":"Potato"
},
{
"key": "2",
"value":"Chilly"
}
]

Map 2
[
{
"key": "1",
"value":"Apple"
},
{
"key": "2",
"value":"Plum"
}
]

I want the data in the fashion so that I can fetch data for the same key from both the map at the same time

```<code><#list map1+map2?keys as key>
<tr>
    <td>${key}</td>
    <td >${map1[key]}</td>
    <td >${map2[key]}</td>
</tr>
</#list>
</code>```

I know I am doing something wrong, but not able to process the code. Can someone help?

答:
You need to parenthesize the map concatenation in order to be able to use the built-in ?keys, so (map1 + map2)?keys. Also, you might want to check for empty values if the maps are not equal by suffixing your expression with !"default value", or simply ! if you want to have no default:

```<code><#assign map1 = { "1": "Potato", "2": "Chilly" } >
<#assign map2 = { "1": "Apple", "2": "Plum", "3": "Extra" } >
<#list (map1 + map2)?keys as key>
<tr>
    <td>${key}</td>
    <td>${map1[key]!}</td>
    <td>${map2[key]!}</td>
</tr>
</#list>
</code>```

See also:

Freemarker - default value for variable that may be missing or blank?

Body:
My two hash/maps are as below. I want to get the value corresponding to the key from the first map and second map and then add them to table

Map 1
[
{
"key": "1",
"value":"Potato"
},
{
"key": "2",
"value":"Chilly"
}
]

Map 2
[
{
"key": "1",
"value":"Apple"
},
{
"key": "2",
"value":"Plum"
}
]

I want the data in the fashion so that I can fetch data for the same key from both the map at the same time

<#list map1+map2?keys as key>

    ${key}
    ${map1[key]}
    ${map2[key]}

</#list>

I know I am doing something wrong, but not able to process the code. Can someone help?

Body:
You need to parenthesize the map concatenation in order to be able to use the built-in ?keys, so (map1 + map2)?keys. Also, you might want to check for empty values if the maps are not equal by suffixing your expression with !"default value", or simply ! if you want to have no default:

<#assign map1 = { "1": "Potato", "2": "Chilly" } >
<#assign map2 = { "1": "Apple", "2": "Plum", "3": "Extra" } >
<#list (map1 + map2)?keys as key>
<tr>
    <td>${key}</td>
    <td>${map1[key]!}</td>
    <td>${map2[key]!}</td>
</tr>
</#list>

See also:

Freemarker - default value for variable that may be missing or blank?


问:
Call to a member function addEagerConstraints() on null
I want to sort query in relation by type_order:

```<code>public function posts()
{
    if (($this->type_order) == '1') {
        $type = 'id';
        return $this->belongsToMany(Post::class, 'feed_posts')->orderBy($type);
    }
}
</code>```

But get error:

```<code>FatalThrowableError
Call to a member function addEagerConstraints() on null
</code>```

答: The only reason is that not everytime inside your Laravel relation method you can access to $this object, for example on re-rendering Livewire component - in your relation method $this object will be empty. In your case $this->type_order can be null and you don't have else statement, thats why Call to a member function addEagerConstraints() on null

Body:
I want to sort query in relation by type_order:

public function posts()
{
    if (($this->type_order) == '1') {
        $type = 'id';
        return $this->belongsToMany(Post::class, 'feed_posts')->orderBy($type);
    }
}

But get error:

FatalThrowableError
Call to a member function addEagerConstraints() on null


问:
using c++ turn a text file into a adjacency list
Let's say you were given a text file with two columns like so:
commas represent a new line: --------------
blue green,
blue red,
red orange,
red purple,
and so on...

how could would you turn this into an adjacency list
with size n and the type of the array being a list of vertices.

答:
Hopefully this will help:

main.cpp

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

struct Item
{
    std::string first;
    std::string second;
};

int main()
{
    std::ifstream file("input.txt");

    std::vector<Item> items;

    std::string line;
    while (std::getline(file, line))
    {
        Item item;
        size_t p_space = line.find_first_of(' ');
        if(p_space == line.npos){
            //error: no space between two column
        }
        item.first = line.substr(0, p_space);
        item.second = line.substr(p_space + 1, line.size() - p_space - 1);
        items.push_back(item);
    }

    for (const auto &item : items)
        std::cout << item.first << ": " << item.second << "\n";
}
```
<p><code>input.txt</code>:</p>
```blue green
blue red
red orange
red purple
```

Body:
Hopefully this will help:

main.cpp

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

struct Item
{
    std::string first;
    std::string second;
};

int main()
{
    std::ifstream file("input.txt");

    std::vector<Item> items;

    std::string line;
    while (std::getline(file, line))
    {
        Item item;
        size_t p_space = line.find_first_of(' ');
        if(p_space == line.npos){
            //error: no space between two column
        }
        item.first = line.substr(0, p_space);
        item.second = line.substr(p_space + 1, line.size() - p_space - 1);
        items.push_back(item);
    }

    for (const auto &item : items)
        std::cout << item.first << ": " << item.second << "\n";
}

input.txt:

blue green
blue red
red orange
red purple


问:
Can I test just the code in a single module?
I've got a Rust project that uses a fairly large framework. Compilation and macro expansion take a really long time. If I make a tiny change to the code, it takes a minute or more before before "cargo test" actually executes.

Is it possible to create a sub-project or sub-module within the same crate and test just the code in the module, assuming there are no dependencies on code outside the module?

答:
You might be interested in "cargo workspaces" (https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html).

Essentially, instead of splitting your code into multiple mods, you split it into multiple crates. These crates can depend on each other via "path dependencies". For example, you could have something like:

[dependencies]
my_helper_crate = { path = "path/to/crate" }
```

The book has much more detail on this, but a nice feature of using workspaces is that your crates can have separate Cargo.tomls, but share a Cargo.lock, so you won't get issues around incompatible versions of crates.

With this setup, you can build one crate without building the rest of them, so you can cut down on a dev feedback loop.

However, if you have crate_a which depends on crate_b, building crate_a still requires building crate_b, there's not really any getting around that. The benefit is mainly for the leaves of your dependency graph.

Body:
You might be interested in "cargo workspaces" (https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html).

Essentially, instead of splitting your code into multiple mods, you split it into multiple crates. These crates can depend on each other via "path dependencies". For example, you could have something like:

[dependencies]
my_helper_crate = { path = "path/to/crate" }

The book has much more detail on this, but a nice feature of using workspaces is that your crates can have separate Cargo.tomls, but share a Cargo.lock, so you won't get issues around incompatible versions of crates.

With this setup, you can build one crate without building the rest of them, so you can cut down on a dev feedback loop.

However, if you have crate_a which depends on crate_b, building crate_a still requires building crate_b, there's not really any getting around that. The benefit is mainly for the leaves of your dependency graph.


问:
The behavior when putting Row into ConstrainedBox with Flutter is strange
When I put a Row in the ConstrainedBox with Flutter, the display is out of the way.
Is this a Flutter bug?

//Does not Stick out Pattern

```<code>ConstrainedBox(
  constraints: BoxConstraints(
  maxWidth: ScreenUtil.getFullWidth(context) * 0.8),
  child: Container(
    decoration: const BoxDecoration(color: Colors.red),
    width: 300,
    height: 100,
)),
</code>```

//Stick out Pattern

```<code>ConstrainedBox(
  constraints: BoxConstraints(
  maxWidth: ScreenUtil.getFullWidth(context) * 0.8),
  child: Row(
    children: [
      Container(
        decoration: const BoxDecoration(color: Colors.green),
        width: 300,
        height: 100,
      )
    ])),
</code>```

image

答:
do your ConstrainedBox is inside of a scaffold widget?

That is sometimes required.

Body:
When I put a Row in the ConstrainedBox with Flutter, the display is out of the way.
Is this a Flutter bug?

//Does not Stick out Pattern

ConstrainedBox(
  constraints: BoxConstraints(
  maxWidth: ScreenUtil.getFullWidth(context) * 0.8),
  child: Container(
    decoration: const BoxDecoration(color: Colors.red),
    width: 300,
    height: 100,
)),

//Stick out Pattern

ConstrainedBox(
  constraints: BoxConstraints(
  maxWidth: ScreenUtil.getFullWidth(context) * 0.8),
  child: Row(
    children: [
      Container(
        decoration: const BoxDecoration(color: Colors.green),
        width: 300,
        height: 100,
      )
    ])),

image


问:
How to enable CORS in ASP.NET Core
I am trying to enable cross origin resources sharing on my ASP.NET Core Web API, but I am stuck.

The EnableCors attribute accepts policyName of type string as parameter:

// Summary:
//     Creates a new instance of the Microsoft.AspNetCore.Cors.Core.EnableCorsAttribute.
//
// Parameters:
//   policyName:
//     The name of the policy to be applied.
public EnableCorsAttribute(string policyName);

```

What does the policyName mean and how can I configure CORS on an ASP.NET Core Web API?

答:
pay attantion that "/" in the end -  will block the CORS origin

```<code>builder.WithOrigins("http://example.com/","http://localhost:55233/");
</code>```

will block

use

```<code>builder.WithOrigins("http://example.com","http://localhost:55233");
</code>```

Title: How to enable CORS in ASP.NET Core

Body:
I am trying to enable cross origin resources sharing on my ASP.NET Core Web API, but I am stuck.

The EnableCors attribute accepts policyName of type string as parameter:

// Summary:
//     Creates a new instance of the Microsoft.AspNetCore.Cors.Core.EnableCorsAttribute.
//
// Parameters:
//   policyName:
//     The name of the policy to be applied.
public EnableCorsAttribute(string policyName);

What does the policyName mean and how can I configure CORS on an ASP.NET Core Web API?

Body:
pay attantion that "/" in the end -  will block the CORS origin

builder.WithOrigins("http://example.com/","http://localhost:55233/");

will block

use

builder.WithOrigins("http://example.com","http://localhost:55233");


问:
Horizontally align text from two different divs
I have the following structure of html code :

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

<div class="row">
  <div class="container">
    <p class="content">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum.
    </p>
    <p class="align">Should be aligned</p>
  </div>

  <div class="container">
    <p class="content">Very short text</p>

    <p class="align">Should be aligned</p>
    <p>Some more text here</p>
  </div>
</div>
</code>```

Here is my css :

```<code>.container {
  display: flex;
  flex-direction: column;
  width: 40%;
  margin-right: 20px;
}

.row {
  display: flex;
  flex-direction: row;
}
</code>```

I am trying to find a way to horizontally align the two element with the align class but I can not figure it out. I have to precise that the content of the element with "content" class could be anything so I need a solution that works in every case.

(If you have a solution using some Js code it is ok)

Here is a Jsfiddle demo.

Actual result is this :

And this is what I want to achieve :

The text should go where the arrow point to be aligned with the left text, and the "Some more text" should be after the aligned text I hope it's clear now

Thank you very much for your time !

答:
Please try this:

.row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-row: auto auto auto;
  grid-gap: 20px;
}

.item2{
  grid-row: 2 / 3;
}

.item5{
  grid-row: 3 / 4;
  grid-column: 2 / 3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="item1">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
  <div class="item2">Should be aligned</div>
  <div class="item3">Very short text</div>
  <div class="item4">Should be aligned</div>
  <div class="item5">Some more text here</div>

</div></code>```

Body:
I have the following structure of html code :

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

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum.

Should be aligned

Very short text

Should be aligned

Some more text here

Here is my css :

.container {
  display: flex;
  flex-direction: column;
  width: 40%;
  margin-right: 20px;
}

.row {
  display: flex;
  flex-direction: row;
}

I am trying to find a way to horizontally align the two element with the align class but I can not figure it out. I have to precise that the content of the element with "content" class could be anything so I need a solution that works in every case.

(If you have a solution using some Js code it is ok)

Here is a Jsfiddle demo.

Actual result is this :

And this is what I want to achieve :

The text should go where the arrow point to be aligned with the left text, and the "Some more text" should be after the aligned text I hope it's clear now

Thank you very much for your time !

Body:
Please try this:

.row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-row: auto auto auto;
  grid-gap: 20px;
}

.item2{
  grid-row: 2 / 3;
}

.item5{
  grid-row: 3 / 4;
  grid-column: 2 / 3;
}

<div class="row">
  <div class="item1">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
  <div class="item2">Should be aligned</div>
  <div class="item3">Very short text</div>
  <div class="item4">Should be aligned</div>
  <div class="item5">Some more text here</div>

</div>


问:
plot multiple curves on same plot inside function
I have a following function with takes 2 arguments psi,lam and returns 1 array y.

```<code>lam=np.arange(0,1,0.1)
psi=np.deg2rad(np.arange(0,361,1))

def test(psi,lam):

    y=[]

    for i in range(len(lam)):
        sin_psi  = np.sin(psi)
        cos_psi  = np.cos(psi)
        sin_beta = lam*sin_psi
        cos_beta = np.sqrt(1.0 - sin_beta**2)
        ssin_pb  = sin_psi*sin_beta
        y.append((lam*(cos_psi/cos_beta)**2 - ssin_pb)/cos_beta + cos_psi)
        plt.plot(psi,y[i])

return y
</code>```

I would like the function to return range(len(lam))=10 plots of y on the vertical axis  against psi on x axis.

However, it seems to be only plotting the same curve multiple times. Not sure what I am missing?

答:
```<code>import matplotlib.pyplot as plt
import numpy as np

lam=np.arange(0,1,0.1)
psi=np.deg2rad(np.arange(0,361,1))

def test(angle,var):
    sin_psi  = np.sin(psi)
    cos_psi  = np.cos(psi)
    sin_beta = var*sin_psi
    cos_beta = np.sqrt(1.0 - sin_beta**2)
    ssin_pb  = sin_psi*sin_beta
    return ((var*(cos_psi/cos_beta)**2 - ssin_pb)/cos_beta + cos_psi)

for i in lam:
    plt.plot(psi,test(psi,i))
plt.show()
</code>```

I moved the variable outside of the function, this way you may also use it for other cases. The only other thing is that you should call plt.show() after you're done drawing.

Body:
I have a following function with takes 2 arguments psi,lam and returns 1 array y.

lam=np.arange(0,1,0.1)
psi=np.deg2rad(np.arange(0,361,1))

def test(psi,lam):

    y=[]

    for i in range(len(lam)):
        sin_psi  = np.sin(psi)
        cos_psi  = np.cos(psi)
        sin_beta = lam*sin_psi
        cos_beta = np.sqrt(1.0 - sin_beta**2)
        ssin_pb  = sin_psi*sin_beta
        y.append((lam*(cos_psi/cos_beta)**2 - ssin_pb)/cos_beta + cos_psi)
        plt.plot(psi,y[i])

return y

I would like the function to return range(len(lam))=10 plots of y on the vertical axis  against psi on x axis.

However, it seems to be only plotting the same curve multiple times. Not sure what I am missing?

Body:
import matplotlib.pyplot as plt
import numpy as np

lam=np.arange(0,1,0.1)
psi=np.deg2rad(np.arange(0,361,1))

def test(angle,var):
    sin_psi  = np.sin(psi)
    cos_psi  = np.cos(psi)
    sin_beta = var*sin_psi
    cos_beta = np.sqrt(1.0 - sin_beta**2)
    ssin_pb  = sin_psi*sin_beta
    return ((var*(cos_psi/cos_beta)**2 - ssin_pb)/cos_beta + cos_psi)

for i in lam:
    plt.plot(psi,test(psi,i))
plt.show()

I moved the variable outside of the function, this way you may also use it for other cases. The only other thing is that you should call plt.show() after you're done drawing.