问:
In theory is it (perversely) legal to use only the accidental reuse of a memory range in the dynamic allocation to synchronize threads?
In C++, dynamic memory (de)allocation (malloc-free/new-delete) can obviously repeatedly get the same memory range that is free-ed and allocated again in sequence. In multithread C++, that can happen in multiple threads.

Obviously such reuse shouldn't be the problem of the user and he doesn't have to care about it; here is how that is specified in "Data races" [new.delete.dataraces]

For purposes of determining the existence of data races, the library
  versions of operator new, user replacement versions of global operator
  new, the C standard library functions aligned_alloc, calloc, and
  malloc, the library versions of operator delete, user replacement
  versions of operator delete, the C standard library function free, and
  the C standard library function realloc shall not introduce a data
  race ([res.on.data.races]). Calls to these functions that allocate or
  deallocate a particular unit of storage shall occur in a single total
  order, and each such deallocation call shall happen before the next
  allocation (if any) in this order.

The last sentence is interesting: not only the reuse of a memory range doesn't cause a conflict, but also that there must exist an happen before (HB) relation. Although it doesn't say that the implementation must create the HB relation, and while HB requirements are normally are requirements on the user, since the requirement is conditional and based on a special case created by the implementation (the standard library code), it seems clear that it can only be interpreted as a requirement on the implementation.

It means that in the special case where a subsequent allocation returns a previously freed memory location, there is an implied HB relation with the code that freed it.

Does that really mean that the visibility of any memory operation performed by a thread that does a deallocation can be expected to be extremely rarely guaranteed by code that does a memory allocation?

That would look like an extremely odd burden to put on implementations, only usable by extremely bizarre code that would memorize copies of deleted addresses in the event some other thread gets back these same addresses (all while not creating any synchronization, for example via relaxed atomic RMW operations on pointer representations).

Do real implementations take care to really provide that visibility? Are memory allocation functions treated as either "black box" functions, or as acquire (release) operations by the compiler?

ADDITIONAL PRECISION

Here is a potentially problematic case: the compiler could provide attributes to specify semantic properties of functions (like GCC Common Function Attributes) that identify functions that can only affect some memory range (in the current "module", which would be a domain of programming invariants: user, stdlib, other library...). I admit I not worked out the details but it seems intuitively doable and the concepts seem potentially useful for optimization.

There annotations would be invalid if the implementation must provide such guarantee across allocations.

答:
Visibility of arbitrary memory operations would not be guaranteed around such allocations.

Each de/allocation needs to be ordered with respect to the others, and allocations which return the same memory as a previous allocation are explicitly ordered. But this does not imply ordering with respect to other operations that happened inbetween. That is, it does not imply sequential consistency of all other operations.

Now, other operations can be visible, such as those which happen before the deallocation. But everything that preceded the deallocation does not.

The point of the statement is to make it clear that, if you do get the same memory address as a prior allocation, then the ordering that led you there certainly involved both an allocation and a deallocation of memory involving that address.

Specifications have to be rather pedantic sometimes.

That would look like an extremely odd burden to put on implementations

Not really. The visibility may only be required with regards to memory de/allocation, but even visibility would hardly be surprising or burdensome.

After all, the heap is a shared resource. So as a shared resource, access to it tends to be locked behind a mutex of some sort. And most mutexes ensure full visibility of everything lock/unlock. And this is important, because managing a heap requires writing heap management data, which must be made visible to other threads that try to allocate it. So you need a fairly broad memory barrier just to do your job as a thread-accessible allocator.

And it's not like anyone mistook a general memory allocator for being a fast operation.

So if an implementation did provide full visibility, it would likely be because it's needed for managing heap memory, and other memory accesses that gain visibility just came along for the ride.

Here is a potentially problematic case: the compiler could provide attributes to specify semantic properties of functions (like GCC Common Function Attributes) that identify functions that can only affect some memory range (in the current "module", which would be a domain of programming invariants: user, stdlib, other library...).

Such a function could not call the compiler-supplied, general-purpose memory allocator. By definition, such a function requires having tight control over what memory it uses, and the basic memory allocator doesn't give you that. So if it needs dynamic allocations, it would have to use a specialized allocator, and such an allocator can play by whatever rules it wants.


来源: stackexchange

问:
Is there a way to display static properties in a PropertyGrid?
I have a PropertyGrid that displays all of the instance properties for an object. Is there a way to also display the static properties of the class to which the object belongs, either in the same or a separate PropertyGrid? Alternatively, is there another Forms control that would allow me to do this?

答:
Type descriptors are responsible to provide list of properties to show in PropertyGrid.

To customize list of properties you need to provide custom type description for your class/object using either of the following options:

Your class can implement ICustomTypeDescriptor

Your class can derive from CustomTypeDescriptor

You can create a new type descriptor for your class by driving from above interface/class and using a TypeDescriptionProvider register it for your class or the object instance

You can create a wrapper object by deriving from CustomTypeDescriptor just to use for PropertyGrid.

Example

In this example I've implemented the last option. I assume you are going to keep the main class unchanged and just for purpose of showing in PropertyGrid, I've created a custom wrapper object which provides a list of properties for property grid, including the static properties.

Let's say you have a class like this:

```<code>public class MyClass
{
    public string InstanceProperty { get; set; }
    public static string StaticProperty { get; set; } = "Test";
}
</code>```

And you want to show it's properties in PropertyGrid.

Then usually the first thing which you need is a new property descriptor:

```<code>using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
public class StaticPropertyDescriptor : PropertyDescriptor
{
    PropertyInfo p;
    Type owenrType;
    public StaticPropertyDescriptor(PropertyInfo pi, Type owenrType)
        : base(pi.Name,
              pi.GetCustomAttributes().Cast<Attribute>().ToArray())
    {
        p = pi;
        this.owenrType = owenrType;
    }
    public override bool CanResetValue(object c) => false;
    public override object GetValue(object c) => p.GetValue(null);
    public override void ResetValue(object c) { }
    public override void SetValue(object c, object v) => p.SetValue(null, v);
    public override bool ShouldSerializeValue(object c) => false;
    public override Type ComponentType { get { return owenrType; } }
    public override bool IsReadOnly { get { return !p.CanWrite; } }
    public override Type PropertyType { get { return p.PropertyType; } }
}
</code>```

Then you can use either of the options which I mentioned above. For example, here I've created a wrapper type descriptor to not touch the original class:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
public class CustomObjectWrapper : CustomTypeDescriptor
{
    public object WrappedObject { get; private set; }
    private IEnumerable<PropertyDescriptor> staticProperties;
    public CustomObjectWrapper(object o)
        : base(TypeDescriptor.GetProvider(o).GetTypeDescriptor(o))
    {
        WrappedObject = o;
    }
    public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
    {
        var instanceProperties = base.GetProperties(attributes)
            .Cast<PropertyDescriptor>();
        staticProperties = WrappedObject.GetType()
            .GetProperties(BindingFlags.Static | BindingFlags.Public)
            .Select(p => new StaticPropertyDescriptor(p, WrappedObject.GetType()));
        return new PropertyDescriptorCollection(
            instanceProperties.Union(staticProperties).ToArray());
    }
}
</code>```

And the usage is quite easy:

```<code>var myClass = new MyClass();
propertyGrid1.SelectedObject = new CustomObjectWrapper (myClass);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Type descriptors are responsible to provide list of properties to show in PropertyGrid.

To customize list of properties you need to provide custom type description for your class/object using either of the following options:

Your class can implement ICustomTypeDescriptor

Your class can derive from CustomTypeDescriptor

You can create a new type descriptor for your class by driving from above interface/class and using a TypeDescriptionProvider register it for your class or the object instance

You can create a wrapper object by deriving from CustomTypeDescriptor just to use for PropertyGrid.

Example

In this example I've implemented the last option. I assume you are going to keep the main class unchanged and just for purpose of showing in PropertyGrid, I've created a custom wrapper object which provides a list of properties for property grid, including the static properties.

Let's say you have a class like this:

public class MyClass
{
    public string InstanceProperty { get; set; }
    public static string StaticProperty { get; set; } = "Test";
}

And you want to show it's properties in PropertyGrid.

Then usually the first thing which you need is a new property descriptor:

using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
public class StaticPropertyDescriptor : PropertyDescriptor
{
    PropertyInfo p;
    Type owenrType;
    public StaticPropertyDescriptor(PropertyInfo pi, Type owenrType)
        : base(pi.Name,
              pi.GetCustomAttributes().Cast<Attribute>().ToArray())
    {
        p = pi;
        this.owenrType = owenrType;
    }
    public override bool CanResetValue(object c) => false;
    public override object GetValue(object c) => p.GetValue(null);
    public override void ResetValue(object c) { }
    public override void SetValue(object c, object v) => p.SetValue(null, v);
    public override bool ShouldSerializeValue(object c) => false;
    public override Type ComponentType { get { return owenrType; } }
    public override bool IsReadOnly { get { return !p.CanWrite; } }
    public override Type PropertyType { get { return p.PropertyType; } }
}

Then you can use either of the options which I mentioned above. For example, here I've created a wrapper type descriptor to not touch the original class:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
public class CustomObjectWrapper : CustomTypeDescriptor
{
    public object WrappedObject { get; private set; }
    private IEnumerable<PropertyDescriptor> staticProperties;
    public CustomObjectWrapper(object o)
        : base(TypeDescriptor.GetProvider(o).GetTypeDescriptor(o))
    {
        WrappedObject = o;
    }
    public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
    {
        var instanceProperties = base.GetProperties(attributes)
            .Cast<PropertyDescriptor>();
        staticProperties = WrappedObject.GetType()
            .GetProperties(BindingFlags.Static | BindingFlags.Public)
            .Select(p => new StaticPropertyDescriptor(p, WrappedObject.GetType()));
        return new PropertyDescriptorCollection(
            instanceProperties.Union(staticProperties).ToArray());
    }
}

And the usage is quite easy:

var myClass = new MyClass();
propertyGrid1.SelectedObject = new CustomObjectWrapper (myClass);


问:
How from my envoy script to write app version to database?
With laravel 5.8  envoy command I deploy my changes and I need from my envoy script to write app version to database

For this I created console command , which is located in app/Console/Commands/envoyWriteAppVersion.php file,
but I did not find how to assign additive parameter to my consol commad. I tried like :

```<code>php artisan envoy:write-app-version  "654"
php artisan envoy:write-app-version  654
php artisan envoy:write-app-version  app_version=7.654
</code>```

But I got error :

```<code>Too many arguments, expected arguments "command".
This task did not complete successfully on one of your servers
</code>```

Which is the valid way ?

Thanks!

答:
I found a valid decision to use in my console command method :

```<code>$arguments = $this->arguments();
</code>```

as it is written here https://laravel.com/docs/5.8/artisan#command-io.

and run from console with space :

```<code>php artisan envoy:write-app-version 0.101
</code>```

Body:
With laravel 5.8  envoy command I deploy my changes and I need from my envoy script to write app version to database

For this I created console command , which is located in app/Console/Commands/envoyWriteAppVersion.php file,
but I did not find how to assign additive parameter to my consol commad. I tried like :

php artisan envoy:write-app-version  "654"
php artisan envoy:write-app-version  654
php artisan envoy:write-app-version  app_version=7.654

But I got error :

Too many arguments, expected arguments "command".
This task did not complete successfully on one of your servers

Which is the valid way ?

Thanks!

Body:
I found a valid decision to use in my console command method :

$arguments = $this->arguments();

as it is written here https://laravel.com/docs/5.8/artisan#command-io.

and run from console with space :

php artisan envoy:write-app-version 0.101


问:
How can gitlab-CI install private python packages from a gitlab dependency that also refers to gitlab repositories
This question is about how to manage access for private gitlab python packages with nested dependencies on other private gitlab packages.  This assumes all the access is via direct git repository patterns and not a private package repository.

package-a is in a private gitlab repository and it depends on package-b, which depends on package-c and they are also in a private gitlab repository.

package-a has a pyproject.toml like this:

```<code>[tool.poetry]
name = "package-a"
repository = "https://gitlab.com/org/package_a.git"

[tool.poetry.dependencies]
python = "^3.6"
package-b = {git = "ssh://git@gitlab.com/org/package_b.git", tag = "0.1.0"}
</code>```

package-b has a pyproject.toml like this:

```<code>[tool.poetry]
name = "package-b"
repository = "https://gitlab.com/org/package_b.git"

[tool.poetry.dependencies]
python = "^3.6"
package-c = {git = "ssh://git@gitlab.com/org/package_c.git", tag = "0.1.0"}
</code>```

Any user with the right org membership on gitlab and an ssh-key can use poetry to install package-a and it's dependency on package-b and then it's dependency on package-c, all into a python venv on a development laptop.  The ssh protocol access also works for docker builds (with experimental features for ssh mounts).

However, the same projects with private dependencies are not installed in gitlab-CI runners, because they lack ssh access.  (Is there any secure way to enable that?)

Assuming the gitlab-CI runners must use an access token to clone the private gitlab repositories, a sed script is applied to the pyproject.toml file for project-a, so the gitlab-CI runner can clone package-b to discover that it depends on package-c; the sed script changes the ssh to https access for project-b by editing the project-a dependency spec in pyproject.toml, i.e.

```<code>sed -i -e 's#ssh://git@gitlab.com/org#https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.com/org#g' pyproject.toml
</code>```

The CI_JOB_TOKEN is an environment variable provided by the gitlab-CI runner.  It is securely managed by the gitlab-CI runner.  So, gitlab-CI runner can now clone the project-b repository somewhere.  The same sed trick might work if it could be applied to this project-b repository somewhere, but this is now in the hands of poetry and it cannot be touched.  So project-b has a git+ssh dependency on project-c and the gitlab-CI runner fails to install project-c because it has no git+ssh credentials to clone it.

Thus, the private package dependency chain works for development and docker build on a laptop with git+ssh access, but it's all broken on gitlab-CI.  What's the better practice to manage this private package access across all these build environments?

答:
These snippets are based on:

https://docs.gitlab.com/ee/ci/ssh_keys/

https://gitlab.com/gitlab-examples/ssh-private-key

https://gitlab.com/gitlab-examples/ssh-private-key/issues/7

https://gitlab.com/gitlab-examples/ssh-private-key/issues/1

```<code>ssh-keygen -o -t rsa -b 4096 -C "git@gitlab.com"

# output to something like ~/.ssh/gitlab_ci_rsa
# do not add any passphrase

# once created, copy the private key to the clipboard, e.g.
cat ~/.ssh/gitlab_ci_rsa | base64 -w0 > tmp.txt
xclip -sel clip < tmp.txt
</code>```

The public key is used as a private deploy key,
which is enabled from a project settings page, e.g.

https://gitlab.com/org/project-a/settings/repository

https://gitlab.com/org/project-b/settings/repository

https://gitlab.com/org/project-c/settings/repository

The private key is pasted into the gitlab-CI variable SSH_PRIVATE_KEY
and gitlab should be able to mask it (when it is base64 encoded).  Then the .gitlab-ci.yml file can add this private key to the ssh-agent using:

```<code>before_script:
  - apt-get update -y -qq && apt-get install -y -qq git make openssh-client
  - eval $(ssh-agent -s)
  ## Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store
  - ssh-add <(echo "$SSH_PRIVATE_KEY" | base64 --decode)
  ## Create the SSH directory and give it the right permissions
  - mkdir -p ~/.ssh
  - chmod 700 ~/.ssh
  - ssh-keyscan gitlab.com >> ~/.ssh/known_hosts
  - chmod 644 ~/.ssh/known_hosts
</code>```

The gitlab documentation does not use base64 encoding, but it's essential to copying all of the private key into the variable and that avoids a prompt for a passphrase from ssh-add.

Body:
This question is about how to manage access for private gitlab python packages with nested dependencies on other private gitlab packages.  This assumes all the access is via direct git repository patterns and not a private package repository.

package-a is in a private gitlab repository and it depends on package-b, which depends on package-c and they are also in a private gitlab repository.

package-a has a pyproject.toml like this:

[tool.poetry]
name = "package-a"
repository = "https://gitlab.com/org/package_a.git"

[tool.poetry.dependencies]
python = "^3.6"
package-b = {git = "ssh://git@gitlab.com/org/package_b.git", tag = "0.1.0"}

package-b has a pyproject.toml like this:

[tool.poetry]
name = "package-b"
repository = "https://gitlab.com/org/package_b.git"

[tool.poetry.dependencies]
python = "^3.6"
package-c = {git = "ssh://git@gitlab.com/org/package_c.git", tag = "0.1.0"}

Any user with the right org membership on gitlab and an ssh-key can use poetry to install package-a and it's dependency on package-b and then it's dependency on package-c, all into a python venv on a development laptop.  The ssh protocol access also works for docker builds (with experimental features for ssh mounts).

However, the same projects with private dependencies are not installed in gitlab-CI runners, because they lack ssh access.  (Is there any secure way to enable that?)

Assuming the gitlab-CI runners must use an access token to clone the private gitlab repositories, a sed script is applied to the pyproject.toml file for project-a, so the gitlab-CI runner can clone package-b to discover that it depends on package-c; the sed script changes the ssh to https access for project-b by editing the project-a dependency spec in pyproject.toml, i.e.

sed -i -e 's#ssh://git@gitlab.com/org#https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.com/org#g' pyproject.toml

The CI_JOB_TOKEN is an environment variable provided by the gitlab-CI runner.  It is securely managed by the gitlab-CI runner.  So, gitlab-CI runner can now clone the project-b repository somewhere.  The same sed trick might work if it could be applied to this project-b repository somewhere, but this is now in the hands of poetry and it cannot be touched.  So project-b has a git+ssh dependency on project-c and the gitlab-CI runner fails to install project-c because it has no git+ssh credentials to clone it.

Thus, the private package dependency chain works for development and docker build on a laptop with git+ssh access, but it's all broken on gitlab-CI.  What's the better practice to manage this private package access across all these build environments?

Body:
These snippets are based on:

https://docs.gitlab.com/ee/ci/ssh_keys/

https://gitlab.com/gitlab-examples/ssh-private-key

https://gitlab.com/gitlab-examples/ssh-private-key/issues/7

https://gitlab.com/gitlab-examples/ssh-private-key/issues/1

ssh-keygen -o -t rsa -b 4096 -C "git@gitlab.com"

# output to something like ~/.ssh/gitlab_ci_rsa
# do not add any passphrase

# once created, copy the private key to the clipboard, e.g.
cat ~/.ssh/gitlab_ci_rsa | base64 -w0 > tmp.txt
xclip -sel clip < tmp.txt

The public key is used as a private deploy key,
which is enabled from a project settings page, e.g.

https://gitlab.com/org/project-a/settings/repository

https://gitlab.com/org/project-b/settings/repository

https://gitlab.com/org/project-c/settings/repository

The private key is pasted into the gitlab-CI variable SSH_PRIVATE_KEY
and gitlab should be able to mask it (when it is base64 encoded).  Then the .gitlab-ci.yml file can add this private key to the ssh-agent using:

before_script:
  - apt-get update -y -qq && apt-get install -y -qq git make openssh-client
  - eval $(ssh-agent -s)
  ## Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store
  - ssh-add <(echo "$SSH_PRIVATE_KEY" | base64 --decode)
  ## Create the SSH directory and give it the right permissions
  - mkdir -p ~/.ssh
  - chmod 700 ~/.ssh
  - ssh-keyscan gitlab.com >> ~/.ssh/known_hosts
  - chmod 644 ~/.ssh/known_hosts

The gitlab documentation does not use base64 encoding, but it's essential to copying all of the private key into the variable and that avoids a prompt for a passphrase from ssh-add.


问:
Add value to dynamically populated list c#
I'm constructing a web page based on ASN.NET MVC3 with Razor templates and Entity. The task is to populate a @Html.DropDownList from the database, so far so good but now I want to insert a static value in the DropDownList.

The code looks as follows

The create method

```<code>public ActionResult Create()
{
    var parents = db.Organizations.OrderBy(o => o.Title).ToList();
    var organization = new Organization();
    return View(organization);
}
</code>```

Extract from the Razor template

```<code><div class="editor-field">
    @Html.DropDownList("ParentGuid",
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "ParentGuid", "Title", Model.ParentGuid))
</div>
</code>```

So, the above code works but Im stuck in figuring out how to insert an empty row in the dropdown.

答: You could add a row with an empty string to your model before passing it to the view, no?</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm constructing a web page based on ASN.NET MVC3 with Razor templates and Entity. The task is to populate a @Html.DropDownList from the database, so far so good but now I want to insert a static value in the DropDownList.

The code looks as follows

The create method

public ActionResult Create()
{
    var parents = db.Organizations.OrderBy(o => o.Title).ToList();
    var organization = new Organization();
    return View(organization);
}

Extract from the Razor template

    @Html.DropDownList("ParentGuid",
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "ParentGuid", "Title", Model.ParentGuid))

So, the above code works but Im stuck in figuring out how to insert an empty row in the dropdown.


问:
Read Excel header and row value
I would need to read the excel content which has header and N.of rows.
Based on column header input,the row needs to be extracted in JAVA.

the java code which i has reads the full excel content.

```<code>        //Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook(file);

        //Get first/desired sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0);
        int totalRows = sheet.getPhysicalNumberOfRows();

        //Iterate through each rows one by one
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext())
        {
            Row row = rowIterator.next();
            //For each row, iterate through all the columns
            Iterator<Cell> cellIterator = row.cellIterator();

            while (cellIterator.hasNext())
            {
                Cell cell = cellIterator.next();
                //Check the cell type and format accordingly
                switch (cell.getCellType())
                {
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "\t");
                        break;
                }
            }
            System.out.println("");
</code>```

Excel content

```<code>Coln1 Coln2 Coln3 Coln4
A        12   nice  3e
A        23   talk  s2
A        43   res   23
B        11   xl    34
B        88   out   r45
C        45    tr    h5
</code>```

EXPECTED result

```<code>if (Coln1==B)
{

Loop the list of B rows (here its 2 rows)
Coln1 Coln2 Coln3 Coln4
B        11   xl    34
B        88   out   r45

if i need , r45 , How to pass the row cell to get the value?

}
</code>```

can someone please assist. Thanks

答:
If header is row 1, maybe you can do this.

```<code>Row headerRow = sheet.getRow(0);
</code>```

You can define some constant for index.
e.g

```<code>int n1ColIndex = 0;    // 0-based.    this is the index of row in excel.
int n2ColIndex = 1;    //
int n3ColIndex = 2;
int n4ColIndex = 3;

// then you can read cell by Row.getCell() method.

// below code, you can put in loop.
XSSFCell n1Cell = row.getCell(n1ColIndex);
if ( n1Cell == null ){
    continue;
}

String n1Col = n1Cell.getStringCellValue();
if( "B".equals(n1Col) ) {
    // get r45 value.

    XSSFCell n4Cell = row.getCell(n4ColIndex);
    if ( n4Cell == null ){
        continue;
    }

    String val = n4Cell.getStringCellValue();
    // this value will be 34 or r45
    // Do you understand ?

}

// update 1. how to get a row.

// method 1.
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
    Row row = rowIterator.next();

    // do something with the row var.
}

// method 2.
for ( int index=0; index < sheet.getLastRowNum(); index++){
    Row row = sheet.getRow(index);

    // check null.
    if ( row == null ){
        continue;
    }

    // do something with the row var.

}
</code>```

API DOC XSSFSheet

All write by hand, no test.
Any question, reply me .

Title: Read Excel header and row value

Body:
I would need to read the excel content which has header and N.of rows.
Based on column header input,the row needs to be extracted in JAVA.

the java code which i has reads the full excel content.

        //Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook(file);

        //Get first/desired sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0);
        int totalRows = sheet.getPhysicalNumberOfRows();

        //Iterate through each rows one by one
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext())
        {
            Row row = rowIterator.next();
            //For each row, iterate through all the columns
            Iterator<Cell> cellIterator = row.cellIterator();

            while (cellIterator.hasNext())
            {
                Cell cell = cellIterator.next();
                //Check the cell type and format accordingly
                switch (cell.getCellType())
                {
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "\t");
                        break;
                }
            }
            System.out.println("");

Excel content

Coln1 Coln2 Coln3 Coln4
A        12   nice  3e
A        23   talk  s2
A        43   res   23
B        11   xl    34
B        88   out   r45
C        45    tr    h5

EXPECTED result

if (Coln1==B)
{

Loop the list of B rows (here its 2 rows)
Coln1 Coln2 Coln3 Coln4
B        11   xl    34
B        88   out   r45

if i need , r45 , How to pass the row cell to get the value?

}

can someone please assist. Thanks

Body:
If header is row 1, maybe you can do this.

Row headerRow = sheet.getRow(0);

You can define some constant for index.
e.g

int n1ColIndex = 0;    // 0-based.    this is the index of row in excel.
int n2ColIndex = 1;    //
int n3ColIndex = 2;
int n4ColIndex = 3;

// then you can read cell by Row.getCell() method.

// below code, you can put in loop.
XSSFCell n1Cell = row.getCell(n1ColIndex);
if ( n1Cell == null ){
    continue;
}

String n1Col = n1Cell.getStringCellValue();
if( "B".equals(n1Col) ) {
    // get r45 value.

    XSSFCell n4Cell = row.getCell(n4ColIndex);
    if ( n4Cell == null ){
        continue;
    }

    String val = n4Cell.getStringCellValue();
    // this value will be 34 or r45
    // Do you understand ?

}

// update 1. how to get a row.

// method 1.
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
    Row row = rowIterator.next();

    // do something with the row var.
}

// method 2.
for ( int index=0; index < sheet.getLastRowNum(); index++){
    Row row = sheet.getRow(index);

    // check null.
    if ( row == null ){
        continue;
    }

    // do something with the row var.

}

API DOC XSSFSheet

All write by hand, no test.
Any question, reply me .


问:
Cannot navigate to an html inner element with href=#id , in angular6
Im using scrollspy in angular6 along with uiRouter for routing now i cannot navigate to an html inner element with href=#id, it is going into url not going to particular div.

i have defined if any wrong url redirect to home in appmodule.ts as shown below.. so whenever i click an anchor tag having href="#id" it redirecting to home page... is there any solution for this abnormal behaviour??

```<code>UIRouterModule.forRoot({
      states: APP_STATES,
      useHash: true,
      otherwise: { state: 'home' },
      config: routerConfigFn,
      deferIntercept: true,
    }),
</code>```

答:
please see if this helps Angular2 Routing with Hashtag to page anchor
or this navigation option</p>

Body:
Im using scrollspy in angular6 along with uiRouter for routing now i cannot navigate to an html inner element with href=#id, it is going into url not going to particular div.

i have defined if any wrong url redirect to home in appmodule.ts as shown below.. so whenever i click an anchor tag having href="#id" it redirecting to home page... is there any solution for this abnormal behaviour??

UIRouterModule.forRoot({
      states: APP_STATES,
      useHash: true,
      otherwise: { state: 'home' },
      config: routerConfigFn,
      deferIntercept: true,
    }),


问:
Toggle classes when triggered by anchor
Using Bootstrap 4.1 to build a collapsible element.

```<code><div class="card text-left mb-3 mt-3">
  <div class="card-head p-3 d-flex justify-content-between">
    <h4>How do we get started?</h4>
    <a id="ToggleElement" class="" data-toggle="collapse" href="#collapse1" aria-expanded="false" aria-controls="collapse1"><i class="fas fa-caret-down"></i></a>
  </div>
  <div class="collapse" id="collapse1">
  <div class="card card-body">
    content...
  </div>
  </div>
</div>
</code>```

How do I change the class from caret-down when closed to caret-up when open.

I know I can use something kind of like

```<code><script type="text/javascript">
    function changeClass(){
        // Code to swap the classes
    }
    $('#ToggleElement').click(changeClass);
</script>
</code>```

What do I need to make this work?

答:
You can use toggleClass of jQuery.

```<code>function changeClass(event) {
  $(event.target).find('i.fas').toggleClass('fa-caret-down');
  $(event.target).find('i.fas').toggleClass('fa-caret-up');
}
</code>```

Title: Toggle classes when triggered by anchor

Body:
Using Bootstrap 4.1 to build a collapsible element.

How do we get started?

    content...

How do I change the class from caret-down when closed to caret-up when open.

I know I can use something kind of like

What do I need to make this work?

Body:
You can use toggleClass of jQuery.

function changeClass(event) {
  $(event.target).find('i.fas').toggleClass('fa-caret-down');
  $(event.target).find('i.fas').toggleClass('fa-caret-up');
}


问:
Chart.js error: type lacks a call signature '((...items: number[]) => number) | ((...items: ChartPoint[]) => number)' in Angular
When deployed angular app to Heroku, I am getting an error

error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((...items: number[]) => number) | ((...items: ChartPoint[]) => number)' has no compatible call signatures.

But I don't have such type of code inside this component the error is showing. So this seems the chart.js type lack issue or mismatch @types/chart.js version.

Following versions are being used

```<code>"chart.js": "^2.8.0",
"@types/chart.js": "^2.7.52"
</code>```

Update

```<code><div style="display: block;">
    <canvas #myChart baseChart
            [datasets]="lineChartData"
            [labels]="lineChartLabels"
            [options]="lineChartOptions"
            [colors]="lineChartColors"
            [legend]="lineChartLegend"
            [chartType]="lineChartType"
          (chartClick)="onChartClick($event)">
    </canvas>
</div>
</code>```

in .ts file

```<code>this.lineChartData[0].data = [0]
this.lineChartData[0].data = [1]
this.lineChartData[0].data = [2]
</code>```

答:
Actually [datasets]="lineChartData" has two types. One is number[] and other is ChartPoint[] so to store data as number we need to type-cast data as

```<code>(this.lineChartData[0].data as number[]).push(1)
</code>```

HTML

```<code><div style="display: block;">
    <canvas #myChart baseChart [datasets]="lineChartData"></canvas>
</div>
</code>```

Body:
When deployed angular app to Heroku, I am getting an error

error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((...items: number[]) => number) | ((...items: ChartPoint[]) => number)' has no compatible call signatures.

But I don't have such type of code inside this component the error is showing. So this seems the chart.js type lack issue or mismatch @types/chart.js version.

Following versions are being used

"chart.js": "^2.8.0",
"@types/chart.js": "^2.7.52"

Update

    <canvas #myChart baseChart
            [datasets]="lineChartData"
            [labels]="lineChartLabels"
            [options]="lineChartOptions"
            [colors]="lineChartColors"
            [legend]="lineChartLegend"
            [chartType]="lineChartType"
          (chartClick)="onChartClick($event)">
    </canvas>

in .ts file

this.lineChartData[0].data = [0]
this.lineChartData[0].data = [1]
this.lineChartData[0].data = [2]

Body:
Actually [datasets]="lineChartData" has two types. One is number[] and other is ChartPoint[] so to store data as number we need to type-cast data as

(this.lineChartData[0].data as number[]).push(1)

HTML

<div style="display: block;">
    <canvas #myChart baseChart [datasets]="lineChartData"></canvas>
</div>


问:
Flask not receiving arguments from curl post
Trying to implement a flask API with the following code:

```<code>import tweepy,flask,os,flask_api,re,json,logging
app = flask.Flask(__name__,template_folder='')
@app.route('/',methods=['POST'])
def answer():
    app.logger.info('server responding')
    for key,value in flask.request.args.items():
        app.logger.info(key+':'+value)
    return 'Server on line'

@app.route('/',methods=['GET'])
def home():
    return flask.render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)#use_reloader=False
    logging.basicConfig(filename='error.log',level=logging.DEBUG)
    app.logger.info('Successfull info message')
    app.logger.error('Successfull error message')
</code>```

When I try to curl it wit windows,

```<code>curl -X POST -d query=cheese http://127.0.0.1:5000/
</code>```

(long form)

```<code>curl --header "Content-Type: application/json"  --request POST  --data '{"query":"cheese"}'   http://127.0.0.1:5000/
</code>```

I get

```<code> INFO in logtest: server responding
</code>```

But not a single key/value pair is returned

答:
flask.request.args are URL query parameters.

curl --data is body.

You're sending a request body but expecting them to show up in the URL params. Which will obviously not work.

You need to access request.data instead. There is a convenience method get_json() that you can use to have Flask parse the body into a dictionary for you.

Body:
Trying to implement a flask API with the following code:

import tweepy,flask,os,flask_api,re,json,logging
app = flask.Flask(__name__,template_folder='')
@app.route('/',methods=['POST'])
def answer():
    app.logger.info('server responding')
    for key,value in flask.request.args.items():
        app.logger.info(key+':'+value)
    return 'Server on line'

@app.route('/',methods=['GET'])
def home():
    return flask.render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)#use_reloader=False
    logging.basicConfig(filename='error.log',level=logging.DEBUG)
    app.logger.info('Successfull info message')
    app.logger.error('Successfull error message')

When I try to curl it wit windows,

curl -X POST -d query=cheese http://127.0.0.1:5000/

(long form)

curl --header "Content-Type: application/json"  --request POST  --data '{"query":"cheese"}'   http://127.0.0.1:5000/

I get

 INFO in logtest: server responding

But not a single key/value pair is returned


问:
Fastest Dictionary lookup in c# .net Compact Framework 3.5
I'm looking for the fastest way to lookup if List, Set, Dictionary contains a specific Keyword (string). I don't need to store any data inside I just want to know if my Keyword is in the List.

I thought about some possibilities like:

```<code>Dictionary<string, bool> myDictionary = new Dictionary<string, bool>();
if (myDictionary.ContainsKey(valueToSearch))
{
    // do something
}
</code>```

but I don't need a value.

```<code>string[] myArray = {"key1", "key2", "key3"}
if (Array.IndexOf(myArray, valueToSearch) != -1)
{
    // do something
}
</code>```

Then I found:

```<code>List<string> list = new List<string>();
if (list.Contains(valueToSearch))
{
    // do something
}
</code>```

The lookup will happen very often and has to be very fast.
Any idea what's the fastest way to check if a value equals one of a given list of keys?

答:
In general, a Dictionary lookup is the usual solution to a problem like this, as long as your keys are good hash values that get a somewhat even distribution in the dictionary's lookup table.

However, there may be certain cases where a list lookup appears to run faster, depending on how the data is sorted and what exactly you are looking up.

The best way to tell is to run a profile of each case, and see which performs better.

Body:
I'm looking for the fastest way to lookup if List, Set, Dictionary contains a specific Keyword (string). I don't need to store any data inside I just want to know if my Keyword is in the List.

I thought about some possibilities like:

Dictionary<string, bool> myDictionary = new Dictionary<string, bool>();
if (myDictionary.ContainsKey(valueToSearch))
{
    // do something
}

but I don't need a value.

string[] myArray = {"key1", "key2", "key3"}
if (Array.IndexOf(myArray, valueToSearch) != -1)
{
    // do something
}

Then I found:

List<string> list = new List<string>();
if (list.Contains(valueToSearch))
{
    // do something
}

The lookup will happen very often and has to be very fast.
Any idea what's the fastest way to check if a value equals one of a given list of keys?


问:
Echo an Array and make the content look pretty on the page
I am trying to echo out my array on each line, not bunched together.

I have tried
, this only show's on the front end, but when you look at HTML code. Its still clumped together.

```<code>$arrays = [];

$arrays[] = "Good";
$arrays[] = "Bad";

foreach ($arrays as $array){
    echo $array;
}
</code>```

Result:

GoodBad

Want Result:

Good

Bad

答: Try using print_r($arrays). docs here.

Body:
I am trying to echo out my array on each line, not bunched together.

I have tried
, this only show's on the front end, but when you look at HTML code. Its still clumped together.

$arrays = [];

$arrays[] = "Good";
$arrays[] = "Bad";

foreach ($arrays as $array){
    echo $array;
}

Result:

GoodBad

Want Result:

Good

Bad

Body: Try using print_r($arrays). docs here.


问:
org.gradle.tooling.BuildException: invalid code lengths set
I am trying to make dlib-android on Android Studio. It was downloaded from:
 https://github.com/tzutalin/dlib-android.

After changing a couple of things such as a mips64... file, it synced and built successfully. But when I try to run with a device or a virtual device, I always get

"Cause: invalid code lengths set" error. The run tasks ended at App:packageDebug. From the long list of things, three under compiler are more informative I guess:

```<code>org.gradle.tooling.BuildException: invalid code lengths set

java.util.zip.ZipException: invalid code lengths set

java.lang.IllegalStateException: Still waiting to inspect output APK's res/raw/shape_predictor_68_face_landmarks.dat

On the right side there was: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:packageDebug'.
</code>```

I searched all over the places and tried everything I could find, but it did not work. Also, I cleaned the cache and restarted, I tried different emulator and devices. I also tried different project settings and structure settings.
I also noticed that a very similar post was not answered:
 build failed because of "org.gradle.tooling.BuildException: invalid code lengths set"

I would like to add that other projects made on the same machine went through fine and ran well on phones or virtual devices.

Or, is it caused by the large res/raw/shape_predictor_68_face_landmarks.dat file that it could not compress?

Or, should I remove the current android studio and install an older version?

Thanks a lot for any suggestion!

答:
I came up with is by downgrading your project level gradle to 3.1.0. It seems to be working on it. The only reason why I think it is causing the problem is latest gradle plugin try to validate every file in your project and somehow it cant read the shape_predictor_68_face_landmarks.dat.

Reference: https://github.com/tzutalin/dlib-android-app/issues/47

Body:
I am trying to make dlib-android on Android Studio. It was downloaded from:
 https://github.com/tzutalin/dlib-android.

After changing a couple of things such as a mips64... file, it synced and built successfully. But when I try to run with a device or a virtual device, I always get

"Cause: invalid code lengths set" error. The run tasks ended at App:packageDebug. From the long list of things, three under compiler are more informative I guess:

org.gradle.tooling.BuildException: invalid code lengths set

java.util.zip.ZipException: invalid code lengths set

java.lang.IllegalStateException: Still waiting to inspect output APK's res/raw/shape_predictor_68_face_landmarks.dat

On the right side there was: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:packageDebug'.

I searched all over the places and tried everything I could find, but it did not work. Also, I cleaned the cache and restarted, I tried different emulator and devices. I also tried different project settings and structure settings.
I also noticed that a very similar post was not answered:
 build failed because of "org.gradle.tooling.BuildException: invalid code lengths set"

I would like to add that other projects made on the same machine went through fine and ran well on phones or virtual devices.

Or, is it caused by the large res/raw/shape_predictor_68_face_landmarks.dat file that it could not compress?

Or, should I remove the current android studio and install an older version?

Thanks a lot for any suggestion!


问:
Moving method out of the Class
I'd like to re-factor Cache class purely for academic reason.

However, I'm having a tough time figuring out how I can move getMap out of the Cache class and have it as a regular function.

```<code>function isObject(arg) {
  const typeOfObj = typeof arg;
  return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}

class Cache {
  constructor() {
    this.map = new Map();
    this.weakmap = new WeakMap();
  }
  // return a Cache's value at a key
  getMap(key) {
    // console.log(this);
    const map = this[isObject(key) ? 'weakmap' : 'map'];
    // console.log(map);
    this.setKeyIfNeeded(map, key);
    let valueMap = map.get(key);
    return valueMap;
  }
  // create a Cache's key, if needed

  setKeyIfNeeded(map, key) {
    if (!map.has(key)) {
      map.set(key, new Cache());
    }
  }
}

const getNestedMap = (keys, initialCache) =>
  keys.reduce((cache, key) => cache.getMap(key), initialCache);

function memoize(fn) {
  const cache = new Cache();
  return (...args) => {
    // get (or create) a cache item

    const item = getNestedMap(args, cache);

    if (Reflect.has(item, 'value')) {
      return item.value;
    }
    return (item.value = fn(args));
  };
}

let counter = 1;
function foo() {
  counter += 1;
  return counter;
}

const id1 = Symbol('id');
const id2 = Symbol('id');

const memoizedFoo = memoize(foo);

console.log(memoizedFoo(3, 4, 5, 6)); //2
console.log(memoizedFoo(3, 4, 5, 6)); //2
console.log(memoizedFoo(3, 4, 6)); //3
console.log(memoizedFoo(3, 4, 6)); //3
</code>```

答:
You will need to rewrite your function to accept all things.  Then you'd just call it from within your class.

One example might be:

```<code>getMap(cache, key, isObject, setKeyIfNeeded) {
    // console.log(this);
    const map = cache[isObject(key) ? 'weakmap' : 'map'];
    // console.log(map);
    setKeyIfNeeded(map, key);
    let valueMap = map.get(key);
    return valueMap;
  }
</code>```

Title: Moving method out of the Class

Body:
I'd like to re-factor Cache class purely for academic reason.

However, I'm having a tough time figuring out how I can move getMap out of the Cache class and have it as a regular function.

function isObject(arg) {
  const typeOfObj = typeof arg;
  return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}

class Cache {
  constructor() {
    this.map = new Map();
    this.weakmap = new WeakMap();
  }
  // return a Cache's value at a key
  getMap(key) {
    // console.log(this);
    const map = this[isObject(key) ? 'weakmap' : 'map'];
    // console.log(map);
    this.setKeyIfNeeded(map, key);
    let valueMap = map.get(key);
    return valueMap;
  }
  // create a Cache's key, if needed

  setKeyIfNeeded(map, key) {
    if (!map.has(key)) {
      map.set(key, new Cache());
    }
  }
}

const getNestedMap = (keys, initialCache) =>
  keys.reduce((cache, key) => cache.getMap(key), initialCache);

function memoize(fn) {
  const cache = new Cache();
  return (...args) => {
    // get (or create) a cache item

    const item = getNestedMap(args, cache);

    if (Reflect.has(item, 'value')) {
      return item.value;
    }
    return (item.value = fn(args));
  };
}

let counter = 1;
function foo() {
  counter += 1;
  return counter;
}

const id1 = Symbol('id');
const id2 = Symbol('id');

const memoizedFoo = memoize(foo);

console.log(memoizedFoo(3, 4, 5, 6)); //2
console.log(memoizedFoo(3, 4, 5, 6)); //2
console.log(memoizedFoo(3, 4, 6)); //3
console.log(memoizedFoo(3, 4, 6)); //3

Body:
You will need to rewrite your function to accept all things.  Then you'd just call it from within your class.

One example might be:

getMap(cache, key, isObject, setKeyIfNeeded) {
    // console.log(this);
    const map = cache[isObject(key) ? 'weakmap' : 'map'];
    // console.log(map);
    setKeyIfNeeded(map, key);
    let valueMap = map.get(key);
    return valueMap;
  }


问:
How do I capture all error & display an error message
In my python code, I would like to catch all the errors & display an error message. For example, I would like to do this thing

```<code>try:
'my code block
catch:
print("Error:x error occurred" )
</code>```

Can you suggest me how to do this?

答:
If you're interested in the exception type, then you can catch all exceptions using except Exception as ex (ex can be anything), and then get the exception type using type(ex).__name__:

```<code>try:
  # example, dividing by zero
  x = 1 / 0
except Exception as ex:
  print("Error: {} error occurred".format(type(ex).__name__))
</code>```

Output:

```<code>Error: ZeroDivisionError error occurred
</code>```

If the type doesn't matter, then this will do:

```<code>try:
  # some code
except:
  print("Error:an error occurred") # any error, but you don't know which
</code>```

Body:
In my python code, I would like to catch all the errors & display an error message. For example, I would like to do this thing

try:
'my code block
catch:
print("Error:x error occurred" )

Can you suggest me how to do this?

Body:
If you're interested in the exception type, then you can catch all exceptions using except Exception as ex (ex can be anything), and then get the exception type using type(ex).__name__:

try:
  # example, dividing by zero
  x = 1 / 0
except Exception as ex:
  print("Error: {} error occurred".format(type(ex).__name__))

Output:

Error: ZeroDivisionError error occurred

If the type doesn't matter, then this will do:

try:
  # some code
except:
  print("Error:an error occurred") # any error, but you don't know which


问:
pointer-event - none is not working when I use tab key
I am making a form where I am using a Class to disabled my inputs using pointer-even: none, my input is not editable when I am trying to click on the input which is correct, but when I am using "TAB" key it is focusing on input and I can edit the input, how i can prevent focus should not go on my input using tab key, and should allow to edit the input.

```<code><form style="padding:10px; margin:10px" action="" class=" form-inline">
          <div class="form-group">
            <div class="input-group">
            <div class="form-group">
                <div class="input-group">
                  <input type="text" class="form-control disabledClass" placeholder="1">
                </div>
              </div>
              <div class="form-group">
                <div class="input-group">
                  <input type="text" class="form-control disabledClass" placeholder="2" >
                </div>
              </div>

            </div>
          </div>
        </form>

CSS:
.disabledClass{
  background: #f1f1f1;
  pointer-events: none;
}
</code>```

your early reply appreciated..

答:
pointer-events CSS rules only affects pointer events (think of mouse-events, even though there are other pointer-events).

Navigating through keyboard is not part of the pointer events.

There were some CSS rules that were supposed to help in your situation, but none seems to properly work, and they aren't standardized anyway.

For instance, I would have thought that the non standard -moz-user-focus (only in FF) would have done this, but it doesn't. user-select or non-standard user-modify do not prevent it either.

The only way I found is actually though HTML, by setting both the readonly and the tabindex="-1" attributes (disabled would also do, but generally comes with some dimmed styling):

input {
  pointer-events: none;
}
.no-focus {
  -moz-user-focus: none;
  -webkit-user-focus: none;
  -ms-user-focus: none;
  user-focus: none;
  -moz-user-modify: read-only;
  -webkit-user-modify: read-only;
  -ms-user-modify: read-only;
  user-modify: read-only;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" class="no-focus" value="CSS">
<input type="text" readonly value="readonly" tabindex="-1">

```First click this iframe then try to navigate using TAB```</code>```

Body:
I am making a form where I am using a Class to disabled my inputs using pointer-even: none, my input is not editable when I am trying to click on the input which is correct, but when I am using "TAB" key it is focusing on input and I can edit the input, how i can prevent focus should not go on my input using tab key, and should allow to edit the input.

<form style="padding:10px; margin:10px" action="" class=" form-inline">

                  <input type="text" class="form-control disabledClass" placeholder="1">

                  <input type="text" class="form-control disabledClass" placeholder="2" >

        </form>

CSS:
.disabledClass{
  background: #f1f1f1;
  pointer-events: none;
}

your early reply appreciated..

Body:
pointer-events CSS rules only affects pointer events (think of mouse-events, even though there are other pointer-events).

Navigating through keyboard is not part of the pointer events.

There were some CSS rules that were supposed to help in your situation, but none seems to properly work, and they aren't standardized anyway.

For instance, I would have thought that the non standard -moz-user-focus (only in FF) would have done this, but it doesn't. user-select or non-standard user-modify do not prevent it either.

The only way I found is actually though HTML, by setting both the readonly and the tabindex="-1" attributes (disabled would also do, but generally comes with some dimmed styling):

input {
  pointer-events: none;
}
.no-focus {
  -moz-user-focus: none;
  -webkit-user-focus: none;
  -ms-user-focus: none;
  user-focus: none;
  -moz-user-modify: read-only;
  -webkit-user-modify: read-only;
  -ms-user-modify: read-only;
  user-modify: read-only;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

<input type="text" class="no-focus" value="CSS">
<input type="text" readonly value="readonly" tabindex="-1">

<pre>First click this iframe then try to navigate using TAB</pre>


问:
Migrating Classic ASP.NET solution to Azure Repo
Our development team deploys about 6 ASP.NET applications (Web forms, SOAP service, RESTful service, and executables).  These applications all reference the same few .DLL libraries that hold most of our business code and those libraries reference a few lower level framework and security libraries (this is all in C#).  Right now it's all hosted in TFVC in azure.

We are creating a new Azure organization and moving everything into Azure Git and more importantly we're setting up CI/CD using Pipelines.  Up until this point we've just had one giant solution that we use for deployments that holds everything.  The application projects just use project references to the library projects and when I build for deployment it builds it all.  Then we just publish each application independently using Web Deployment out to our Azure Virtual Machines.

We're going to need a pipeline for each of these applications and we're trying to figure out the best way to (1) structure our projects in our Repos repository and (2) how to best reference the libraries.

Should the libraries be built into packages and then we reference them from an artifacts feed that we pull into the pipelines?  Also, should each application and library be its own project in the repository or does it tend to flow better as one large project?  I'm not sure these questions have definitive answers but I'm hoping for either some direction or best practices I can reference.

答:
Should the libraries be built into packages and then we reference them from an artifacts feed that we pull into the pipelines?

Building a library into a package is a good choice, especially those libraries are referenced by multiple applications. Using nuget package will reduce the citation relationship between projects, making it easier for us to manage our projects.

Check the this thread for more nuget advantages and this thread for selecting Project reference or NuGet.

should each application and library be its own project in the
  repository or does it tend to flow better as one large project?

Just as you know, this question is hard to have a definitive answer. Although more and more voices now support monorepos, but it is recommended that monorepos still have controversy and indeed in some cases we still want multiple repositories, like:

A single repository would be too large to be efficient.

Your repositories are loosely coupled, or decoupled.

A developer typically only needs one, or a small subset of your
repositories to develop.

You typically want to develop the repositories independently, and
only need to synchronize them occasionally.

You want to encourage more modularity.

Different teams work on different repositories.

So, just like DJ said, you have to choose by yourself.

You can check following threads for some more info about this topic:

Why you should use a single repository for all your company’s projects

Choosing between Single or multiple projects in a git repository?

Hope this helps.


问:
AlarmManager not triggering repeated alarm on proper time
I am developing an application for Android Lollipop and KitKat devices. The application needs to call an API in every predefined interval (Based on the interval received from server). I am doing this using AlarmManager class.
But the problem is it works till some time then stops.

Say for example If I set to start the alarm at 08:00 AM with an interval of 30 minutes it works till 11:00AM (aprx) and then alarm doesn't trigger.

If I set a long interval (eg : 8 hours from current time, still same issue happens, not reiggering even once )

Code

```<code>public void setRepeatedAlarm(Context context, int requestCode, long next, long interval, Intent intent) {
   PendingIntent sender = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
   AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   am.setRepeating(AlarmManager.RTC_WAKEUP, next, interval, sender);
}
</code>```

Function calling

```<code>AlarmHandleManager.get().setRepeatedAlarm(this, Constants.SchedulerRequestCodes.UPLOAD_LOG, date.getTime(), AlarmManager.INTERVAL_DAY, intent);
</code>```

Let me know if any one can figure out the issue.
Have seen a bug reported in lollipop in Google bug tracker, If that is the case let me know if there is any alternative solution for this.

答:
i don't think it's a bug since it's already mentioned in the official documentation

Note: As of API 19, all repeating alarms are inexact. Because this method has been available since API 3, your application can safely call it and be assured that it will get similar behavior on both current and older versions of Android.

Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.

Note: Beginning with API 19 (Build.VERSION_CODES.KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, android.app.PendingIntent) and setExact(int, long, android.app.PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.

Body:
I am developing an application for Android Lollipop and KitKat devices. The application needs to call an API in every predefined interval (Based on the interval received from server). I am doing this using AlarmManager class.
But the problem is it works till some time then stops.

Say for example If I set to start the alarm at 08:00 AM with an interval of 30 minutes it works till 11:00AM (aprx) and then alarm doesn't trigger.

If I set a long interval (eg : 8 hours from current time, still same issue happens, not reiggering even once )

Code

public void setRepeatedAlarm(Context context, int requestCode, long next, long interval, Intent intent) {
   PendingIntent sender = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
   AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   am.setRepeating(AlarmManager.RTC_WAKEUP, next, interval, sender);
}

Function calling

AlarmHandleManager.get().setRepeatedAlarm(this, Constants.SchedulerRequestCodes.UPLOAD_LOG, date.getTime(), AlarmManager.INTERVAL_DAY, intent);

Let me know if any one can figure out the issue.
Have seen a bug reported in lollipop in Google bug tracker, If that is the case let me know if there is any alternative solution for this.


问:
How to convert rows to columns in PostgreSQL?
I have two database tables as below

```<code>site
id    |    name
1        Site One
2        Site Two
3        Site Three

asset_quantities
id   |   site_id   |  asset_type   | quantity
1           1             1              10
2           1             2              15
3           1             3              25
4           2             1              11
5           2             2              16
6           2             3              7
7           3             1              12
8           3             2              15
9           3             3              16
</code>```

I want to write a SQL query that will sort results based on the 'quantity' column for a given asset type
E.g. I want to sort descending results based on the quantity for asset type 1 across all sites.
How would I frame the SQL query for a scenario like this?

Below is a sample result I want if I want descending order results for the quantity of asset type 1 across all sites

```<code>site_id  |   asset_type_1_qty   |   asset_type_2_qty  |  asset_type_3_qty
   3                12                     15                  16
   2                11                     16                  7
   1                10                     15                  25
</code>```

答:
OK, it is easy to implement this, just use a self join, as below:

```<code>select
    s1.site_id,
    s1.quantity as asset_type_1_qty,
    s2.quantity as asset_type_2_qty,
    s3.quantity as asset_type_3_qty
from
    asset_quantities s1
join
    asset_quantities s2 on s1.site_id=s2.site_id and s1.asset_type=1 and s2.asset_type=2
join
    asset_quantities s3 on s1.site_id=s3.site_id and s3.asset_type=3
order by
    s1.quantity desc
</code>```

OK, there is a function called crosstab which can transform rows to columns, I think it would meet your needs perfectly, just as below:

```<code>postgres=# select * from asset_quantities;
 id | site_id | asset_type | quantity
----+---------+------------+----------
  1 |       1 |          1 |       10
  2 |       1 |          2 |       15
  3 |       1 |          3 |       25
  4 |       2 |          1 |       11
  5 |       2 |          2 |       16
  6 |       2 |          3 |        7
  7 |       3 |          1 |       12
  8 |       3 |          2 |       15
  9 |       3 |          3 |       16
(9 rows)

postgres=# select * from crosstab(
'select
    site_id,
    asset_type,
    quantity
from
    asset_quantities order by site_id,asset_type'
) as result(site_id int,asset_type_1_qty int,asset_type_2_qty int,asset_type_3_qty int);
 site_id | asset_type_1_qty | asset_type_2_qty | asset_type_3_qty
---------+------------------+------------------+------------------
       1 |               10 |               15 |               25
       2 |               11 |               16 |                7
       3 |               12 |               15 |               16
(3 rows)
</code>```

Oh right, before you use the crosstab function, you should execute the clause below in PostgreSQL, otherwise you would get an error.

```<code>CREATE EXTENSION tablefunc;
</code>```

Body:
I have two database tables as below

site
id    |    name
1        Site One
2        Site Two
3        Site Three

asset_quantities
id   |   site_id   |  asset_type   | quantity
1           1             1              10
2           1             2              15
3           1             3              25
4           2             1              11
5           2             2              16
6           2             3              7
7           3             1              12
8           3             2              15
9           3             3              16

I want to write a SQL query that will sort results based on the 'quantity' column for a given asset type
E.g. I want to sort descending results based on the quantity for asset type 1 across all sites.
How would I frame the SQL query for a scenario like this?

Below is a sample result I want if I want descending order results for the quantity of asset type 1 across all sites

site_id  |   asset_type_1_qty   |   asset_type_2_qty  |  asset_type_3_qty
   3                12                     15                  16
   2                11                     16                  7
   1                10                     15                  25

Body:
OK, it is easy to implement this, just use a self join, as below:

select
    s1.site_id,
    s1.quantity as asset_type_1_qty,
    s2.quantity as asset_type_2_qty,
    s3.quantity as asset_type_3_qty
from
    asset_quantities s1
join
    asset_quantities s2 on s1.site_id=s2.site_id and s1.asset_type=1 and s2.asset_type=2
join
    asset_quantities s3 on s1.site_id=s3.site_id and s3.asset_type=3
order by
    s1.quantity desc

OK, there is a function called crosstab which can transform rows to columns, I think it would meet your needs perfectly, just as below:

postgres=# select * from asset_quantities;
 id | site_id | asset_type | quantity
----+---------+------------+----------
  1 |       1 |          1 |       10
  2 |       1 |          2 |       15
  3 |       1 |          3 |       25
  4 |       2 |          1 |       11
  5 |       2 |          2 |       16
  6 |       2 |          3 |        7
  7 |       3 |          1 |       12
  8 |       3 |          2 |       15
  9 |       3 |          3 |       16
(9 rows)

postgres=# select * from crosstab(
'select
    site_id,
    asset_type,
    quantity
from
    asset_quantities order by site_id,asset_type'
) as result(site_id int,asset_type_1_qty int,asset_type_2_qty int,asset_type_3_qty int);
 site_id | asset_type_1_qty | asset_type_2_qty | asset_type_3_qty
---------+------------------+------------------+------------------
       1 |               10 |               15 |               25
       2 |               11 |               16 |                7
       3 |               12 |               15 |               16
(3 rows)

Oh right, before you use the crosstab function, you should execute the clause below in PostgreSQL, otherwise you would get an error.

CREATE EXTENSION tablefunc;


问:
What is an idiomatic Scala way to "remove" one element from an immutable List?
I have a List, which may contain elements that will compare as equal. I would like a similar List, but with one element removed. So from (A, B, C, B, D) I would like to be able to "remove" just one B to get e.g. (A, C, B, D). The order of the elements in the result does not matter.

I have working code, written in a Lisp-inspired way in Scala. Is there a more idiomatic way
to do this?

The context is a card game where two decks of standard cards are in play, so there may
be duplicate cards but still played one at a time.

```<code>def removeOne(c: Card, left: List[Card], right: List[Card]): List[Card] = {
  if (Nil == right) {
    return left
  }
  if (c == right.head) {
    return left ::: right.tail
  }
  return removeOne(c, right.head :: left, right.tail)
}

def removeCard(c: Card, cards: List[Card]): List[Card] = {
  return removeOne(c, Nil, cards)
}
</code>```

答:
```<code>// throws a MatchError exception if i isn't found in li
def remove[A](i:A, li:List[A]) = {
   val (head,_::tail) = li.span(i != _)
   head ::: tail
}
</code>```

Body:
I have a List, which may contain elements that will compare as equal. I would like a similar List, but with one element removed. So from (A, B, C, B, D) I would like to be able to "remove" just one B to get e.g. (A, C, B, D). The order of the elements in the result does not matter.

I have working code, written in a Lisp-inspired way in Scala. Is there a more idiomatic way
to do this?

The context is a card game where two decks of standard cards are in play, so there may
be duplicate cards but still played one at a time.

def removeOne(c: Card, left: List[Card], right: List[Card]): List[Card] = {
  if (Nil == right) {
    return left
  }
  if (c == right.head) {
    return left ::: right.tail
  }
  return removeOne(c, right.head :: left, right.tail)
}

def removeCard(c: Card, cards: List[Card]): List[Card] = {
  return removeOne(c, Nil, cards)
}


问:
How to fix child node snapshot issue with ARKitSample project?
I've downloaded the ARKitSample project with the ship from - https://github.com/xamarin/ios-samples/blob/master/ios11/ARKitSample/ARKitSample/GameViewController.cs

After running the code, it works as expected until I tap on the screen, the gesture recognize event is called and it works fine the first time - I get a plane node with a snapshot of the screen. But when this is called the second time, instead of creating a new node at the location of the second tap, it overlaps the initial child node.

The code is a port of the original swift version from the ARKit keynote here - https://youtu.be/LLRweyZ1KpA?t=1380

private void HandleTap(UIGestureRecognizer gestureRecognize)
{
    // Get current frame
    var currentFrame = SceneView.Session.CurrentFrame;
    if (currentFrame == null) return;

    // Create an image plane using a snapshot of the view
    var imagePlane = SCNPlane.Create(SceneView.Bounds.Width / 6000, SceneView.Bounds.Height / 6000);
    imagePlane.FirstMaterial.Diffuse.Contents = SceneView.Snapshot();
    imagePlane.FirstMaterial.LightingModelName = SCNLightingModel.Constant;

    // Create a plane node and add it to the scene
    var planeNode = SCNNode.FromGeometry(imagePlane);
    SceneView.Scene.RootNode.AddChildNode(planeNode);

    // Set transform of node to be 10cm in front of the camera
    var translation = SCNMatrix4.CreateTranslation(0, 0, 0.1f);
    var cameraTranslation = currentFrame.Camera.Transform.ToSCNMatrix4();
    planeNode.Transform = SCNMatrix4.Mult(cameraTranslation, translation);
}
```

I've tried this on an iPhone XS and 7, am I missing something obvious?

答:
The sample changes the node's transform for you. If you want to change the node's position, you can try the code below:</p>

```<code>var tapLocation = gestureRecognize.LocationInView(SceneView);
var hitTestResults = SceneView.HitTest(tapLocation, ARHitTestResultType.EstimatedHorizontalPlane);

var hitTestResult = hitTestResults.FirstOrDefault();
if (hitTestResult == null) return;
var position = new SCNVector3(hitTestResult.WorldTransform.Column3.X, hitTestResult.WorldTransform.Column3.Y, hitTestResult.WorldTransform.Column3.Z);
planeNode.Position = position;
</code>```

Body:
I've downloaded the ARKitSample project with the ship from - https://github.com/xamarin/ios-samples/blob/master/ios11/ARKitSample/ARKitSample/GameViewController.cs

After running the code, it works as expected until I tap on the screen, the gesture recognize event is called and it works fine the first time - I get a plane node with a snapshot of the screen. But when this is called the second time, instead of creating a new node at the location of the second tap, it overlaps the initial child node.

The code is a port of the original swift version from the ARKit keynote here - https://youtu.be/LLRweyZ1KpA?t=1380

private void HandleTap(UIGestureRecognizer gestureRecognize)
{
    // Get current frame
    var currentFrame = SceneView.Session.CurrentFrame;
    if (currentFrame == null) return;

    // Create an image plane using a snapshot of the view
    var imagePlane = SCNPlane.Create(SceneView.Bounds.Width / 6000, SceneView.Bounds.Height / 6000);
    imagePlane.FirstMaterial.Diffuse.Contents = SceneView.Snapshot();
    imagePlane.FirstMaterial.LightingModelName = SCNLightingModel.Constant;

    // Create a plane node and add it to the scene
    var planeNode = SCNNode.FromGeometry(imagePlane);
    SceneView.Scene.RootNode.AddChildNode(planeNode);

    // Set transform of node to be 10cm in front of the camera
    var translation = SCNMatrix4.CreateTranslation(0, 0, 0.1f);
    var cameraTranslation = currentFrame.Camera.Transform.ToSCNMatrix4();
    planeNode.Transform = SCNMatrix4.Mult(cameraTranslation, translation);
}

I've tried this on an iPhone XS and 7, am I missing something obvious?

Body:
The sample changes the node's transform for you. If you want to change the node's position, you can try the code below:

var tapLocation = gestureRecognize.LocationInView(SceneView);
var hitTestResults = SceneView.HitTest(tapLocation, ARHitTestResultType.EstimatedHorizontalPlane);

var hitTestResult = hitTestResults.FirstOrDefault();
if (hitTestResult == null) return;
var position = new SCNVector3(hitTestResult.WorldTransform.Column3.X, hitTestResult.WorldTransform.Column3.Y, hitTestResult.WorldTransform.Column3.Z);
planeNode.Position = position;


问:
renderInContext does not work correctly when changing layer Z position
My application allow user to switch UIImageView back and front and then user can capture that screen. Here is my code to capture the screen into UIImage

```<code>-(UIImage *)imageWithView:(UIView *)view
{
   UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 2.0f);

// I even tried view.layer.presentationLayer but still not working
[view.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return image;

}
</code>```

I do not use [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES] because it is slower and sometimes (when view is not visible) drawn the screenshot in black.

But problem with renderInContext is the Z position that change between UIImageView  ( imageView.layer.zPosition = 0.01;etc ). In my iPhone screen this work correctly when I assigned value to zPosition but in the capture screen it turns out wrong.

Are there anyway I can resolve this problem ? Thanks in advance

Edited:
Here is what I tried to do before capture the screenshot. I use this code to make one ImageView display in front of another one.

```<code>-(void)bringOneLevelUp:(UIImageView*)imageView
{
//_imgArray is sorted by Z position order (small to big)
    NSUInteger currentObjectIndex = [_imgArray indexOfObject:imageView];

if(currentObjectIndex+1< _imgArray.count){

UIImageView *upperImageView = [_imgArray objectAtIndex:currentObjectIndex+1];

    CGFloat currentZIndex = imageView.layer.zPosition;
    CGFloat upperZIndex= upperImageView.layer.zPosition;

    imageView.layer.zPosition = upperZIndex;
    upperImageView.layer.zPosition = currentZIndex;

// swap position in array
[_imgArray exchangeObjectAtIndex:currentObjectIndex withObjectAtIndex:currentObjectIndex+1];

}
</code>```

}

And liked I explained earlier the result of this code in the phone screen is correct. The newImageView is in front of lastImageView.  But when I captured screenshot by renderInContext. They are not.

答:
This is an annoying bug of Apple's, but the solution is easy, simply re-order the view you are snapshotting's subviews (and their subviews (and so on)) recursively, based on their zPositions, using a comparator. </p>

<p>Just call the following method, passing the view you are about to snapshot, directly before snapshotting it. </p>

```<code>///UIGraphicsGetCurrentContext doesn't obey layer zPositions so have to adjust view heirarchy (integer index) to match zpositions (float values) for all nested subviews.
-(void)recursivelyAdjustHeirarchyOfSubviewsBasedOnZPosition:(UIView *)parentView {

    NSArray *sortedSubviews = [[parentView subviews] sortedArrayUsingComparator:
                           ^NSComparisonResult(UIView *view1, UIView *view2)
                           {
                               float zpos1 = view1.layer.zPosition;
                               float zpos2 = view2.layer.zPosition;
                               return zpos1 > zpos2;
                           }];

    for (UIView *childView in sortedSubviews) {
        [parentView bringSubviewToFront:childView];
        [self recursivelyAdjustHeirarchyOfSubviewsBasedOnZPosition:childView];
    }

}
</code>```

Body:
My application allow user to switch UIImageView back and front and then user can capture that screen. Here is my code to capture the screen into UIImage

-(UIImage *)imageWithView:(UIView *)view
{
   UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 2.0f);

// I even tried view.layer.presentationLayer but still not working
[view.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return image;

}

I do not use [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES] because it is slower and sometimes (when view is not visible) drawn the screenshot in black.

But problem with renderInContext is the Z position that change between UIImageView  ( imageView.layer.zPosition = 0.01;etc ). In my iPhone screen this work correctly when I assigned value to zPosition but in the capture screen it turns out wrong.

Are there anyway I can resolve this problem ? Thanks in advance

Edited:
Here is what I tried to do before capture the screenshot. I use this code to make one ImageView display in front of another one.

-(void)bringOneLevelUp:(UIImageView*)imageView
{
//_imgArray is sorted by Z position order (small to big)
    NSUInteger currentObjectIndex = [_imgArray indexOfObject:imageView];

if(currentObjectIndex+1< _imgArray.count){

UIImageView *upperImageView = [_imgArray objectAtIndex:currentObjectIndex+1];

    CGFloat currentZIndex = imageView.layer.zPosition;
    CGFloat upperZIndex= upperImageView.layer.zPosition;

    imageView.layer.zPosition = upperZIndex;
    upperImageView.layer.zPosition = currentZIndex;

// swap position in array
[_imgArray exchangeObjectAtIndex:currentObjectIndex withObjectAtIndex:currentObjectIndex+1];

}

}

And liked I explained earlier the result of this code in the phone screen is correct. The newImageView is in front of lastImageView.  But when I captured screenshot by renderInContext. They are not.

Body:
This is an annoying bug of Apple's, but the solution is easy, simply re-order the view you are snapshotting's subviews (and their subviews (and so on)) recursively, based on their zPositions, using a comparator.

Just call the following method, passing the view you are about to snapshot, directly before snapshotting it.

///UIGraphicsGetCurrentContext doesn't obey layer zPositions so have to adjust view heirarchy (integer index) to match zpositions (float values) for all nested subviews.
-(void)recursivelyAdjustHeirarchyOfSubviewsBasedOnZPosition:(UIView *)parentView {

    NSArray *sortedSubviews = [[parentView subviews] sortedArrayUsingComparator:
                           ^NSComparisonResult(UIView *view1, UIView *view2)
                           {
                               float zpos1 = view1.layer.zPosition;
                               float zpos2 = view2.layer.zPosition;
                               return zpos1 > zpos2;
                           }];

    for (UIView *childView in sortedSubviews) {
        [parentView bringSubviewToFront:childView];
        [self recursivelyAdjustHeirarchyOfSubviewsBasedOnZPosition:childView];
    }

}


问:
Is there an equivalent of "None()" in LINQ?
I've been running into situations where I feel I'm lacking a LINQ extension method which effectivelly checks if there is no match of the specified predicate in a collection. There is Any and All, but if I for instance use the following code:

if (Objects.All(u => u.Distance <= 0))

This returns true if all the objects in the collection are 0 or less yards away.

if (Objects.Any(u => u.Distance <= 0))

This returns true if there is at least one object in the collection which is 0 or less yards away from me.

So far so good, both those methods make sense and the syntax for them makes sense too. Now, if I want to check if there is no object with 0 or less distance, I'd have to invert the predicate inside the All method to >= 0 instead of <= 0 or call !All(), which in some cases results in very poorly readable code.

Is there no method which effectively does Collection.None(u => u.Distance <= 0) to check if there is no object in the collection which is 0 or less yards away? It's syntactic sugar more than an actual problem, but I just have the feeling it's missing.

答:
Even shorter version</p>

```<code>static class LinqExtensions
{
    public static bool None<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => !source.Any(predicate);
}
</code>```

Body:
Even shorter version

static class LinqExtensions
{
    public static bool None<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => !source.Any(predicate);
}


问:
Sending a push notification while iPhone is starting up - notification not delivered to device
We are getting reports from our testers that not all Apple Push Notifications are delivered. Specifically, if a notification is sent while the target device is starting up (booting up, establishing network connection, etc), then the notification is never received.

I understand that APNS delivers notifications on a best-effort basis. I've perused Apple's documentation which says the following regarding QoS:

Apple Push Notification service includes a Quality of Service (QoS) component that performs a store-and-forward function. If APNs attempts to deliver a notification and the destination device is offline, APNs stores the notification for a limited period of time and delivers it when the device becomes available again. This component stores only the most recent notification per device and per app. If a device is offline, sending a notification request targeting that device causes the previous request to be discarded. If a device remains offline for a long time, all its stored notifications in APNs are discarded.

I've set the apns-expiration to 90 minutes to engage the QoS functionality.

Notifications are delivered when:

The notification was sent while the device is switched on and operating normally.

The notification was sent while the device was switched off (it is subsequently delivered a short time after the device is switched on).

As an aside, we're using template notifications with Azure Notification Hub to integrate with APNS. As such, our configuration for APNS expiration and priority looks like this:

```<code>registration = new AppleTemplateRegistrationDescription(deviceUpdate.Handle, PushNotifications.IosTemplate)
{
    Expiry = DateTimeOffset.UtcNow.AddMinutes(90).ToString("o"),
    Priority = "10"
};
</code>```

How can I debug/troubleshoot this problem, has anybody encountered similar behaviour?

答:
Addressed this behaviour by adding the following headers to each template notification:

```<code>var templateProperties = new Dictionary<string, string> {
    // omitted
};

var notification = new TemplateNotification(templateProperties);

notification.Headers.Add("ServiceBusNotification-Apns-Expiry", DateTimeOffset.UtcNow.AddDays(7).ToString("yyyy-MM-ddTHH:mmzzz"));
notification.Headers.Add("apns-expiration", DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds().ToString());

await hubClient.SendNotificationAsync(notification, destinationTags);
</code>```

And removed the Expiry property from the initialisation of AppleTemplateRegistrationDescription:

```<code>var apnsHeaders = new Dictionary<string, string> { { "apns-priority", "10" } };
registration = new AppleTemplateRegistrationDescription(deviceUpdate.Handle, PushNotifications.IosTemplate, apnsHeaders)
{
    Priority = "10"
};
</code>```

It was useful to take a look at the Microsoft.Azure.NotificationHubs source on GitHub.

Body:
We are getting reports from our testers that not all Apple Push Notifications are delivered. Specifically, if a notification is sent while the target device is starting up (booting up, establishing network connection, etc), then the notification is never received.

I understand that APNS delivers notifications on a best-effort basis. I've perused Apple's documentation which says the following regarding QoS:

Apple Push Notification service includes a Quality of Service (QoS) component that performs a store-and-forward function. If APNs attempts to deliver a notification and the destination device is offline, APNs stores the notification for a limited period of time and delivers it when the device becomes available again. This component stores only the most recent notification per device and per app. If a device is offline, sending a notification request targeting that device causes the previous request to be discarded. If a device remains offline for a long time, all its stored notifications in APNs are discarded.

I've set the apns-expiration to 90 minutes to engage the QoS functionality.

Notifications are delivered when:

The notification was sent while the device is switched on and operating normally.

The notification was sent while the device was switched off (it is subsequently delivered a short time after the device is switched on).

As an aside, we're using template notifications with Azure Notification Hub to integrate with APNS. As such, our configuration for APNS expiration and priority looks like this:

registration = new AppleTemplateRegistrationDescription(deviceUpdate.Handle, PushNotifications.IosTemplate)
{
    Expiry = DateTimeOffset.UtcNow.AddMinutes(90).ToString("o"),
    Priority = "10"
};

How can I debug/troubleshoot this problem, has anybody encountered similar behaviour?

Body:
Addressed this behaviour by adding the following headers to each template notification:

var templateProperties = new Dictionary<string, string> {
    // omitted
};

var notification = new TemplateNotification(templateProperties);

notification.Headers.Add("ServiceBusNotification-Apns-Expiry", DateTimeOffset.UtcNow.AddDays(7).ToString("yyyy-MM-ddTHH:mmzzz"));
notification.Headers.Add("apns-expiration", DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds().ToString());

await hubClient.SendNotificationAsync(notification, destinationTags);

And removed the Expiry property from the initialisation of AppleTemplateRegistrationDescription:

var apnsHeaders = new Dictionary<string, string> { { "apns-priority", "10" } };
registration = new AppleTemplateRegistrationDescription(deviceUpdate.Handle, PushNotifications.IosTemplate, apnsHeaders)
{
    Priority = "10"
};

It was useful to take a look at the Microsoft.Azure.NotificationHubs source on GitHub.


问:
How can you run a python function stored in a different file
I know how to do this in C, but I'm not sure how to do it in python. I'm trying to make a python program which will read from an external file, then execute a function name which was read from that file. Example:

File structure:

```<code>main.py
map.py
Scripts/
  script1.py
</code>```

map.py contains just an array and a function to get the correct array index:

```<code>map = ["One","script1.function_one","Two","scrip1.function_two"]
def return_mapping(str):
  for i in range(0,len(map)):
    if str in map[i]:
      return map[i+1]
</code>```

The functions: "function_one()" and "function_two()" are defined in script1.py.
main.py will contain something like this:

```<code>selection = raw_input("What function would you like to run?")
function_ptr = map.return_mapping(selection)
#This is where I don't know what the correct code is... I want to now execute
#whatever function was returned.
</code>```

Any suggestions?

答: As said before, you should use import. More informations can be found here: Python Documentation

Body:
I know how to do this in C, but I'm not sure how to do it in python. I'm trying to make a python program which will read from an external file, then execute a function name which was read from that file. Example:

File structure:

main.py
map.py
Scripts/
  script1.py

map.py contains just an array and a function to get the correct array index:

map = ["One","script1.function_one","Two","scrip1.function_two"]
def return_mapping(str):
  for i in range(0,len(map)):
    if str in map[i]:
      return map[i+1]

The functions: "function_one()" and "function_two()" are defined in script1.py.
main.py will contain something like this:

selection = raw_input("What function would you like to run?")
function_ptr = map.return_mapping(selection)
#This is where I don't know what the correct code is... I want to now execute
#whatever function was returned.

Any suggestions?


问:
how to fix yandex api code leak in twitter bot?
I'm a beginner in programming and I'm developing a bot on node-red in the ibm cloud, and I've had problems with the return of the yandex translation API. It returns part of the api code in the tweets, which is not pleasant at all.

The api of yandex allows the api to return in json or xml, I tried both and I could not solve the problem. The bot in question has other api's in use and I was able to configure them normally, something that does not occur with the result of that, which would be the final result for the tweet to be released.

to send the translation to be made use the following request in a function of node red:

```<code>var translate =   msg.method ='GET';
              msg.url = "https://translate.yandex.net/api/v1.5/tr/translate?key= *API KEY* &text=" + recipe + "&lang=pt"
              return [msg,null];]
</code>```

in the next block, and the last one before sending the message, I'm using something like:

```<code>var yandex= msg.payload;
yandex = 'a' + msg.payload.text;
return msg;
</code>```

and this makes me return something like this in the public tweet

```<code>"<?xml version="1.0" encoding="utf-8"?>
< Translation code="200" lang="en-pt"><text>é uma receita com Estilo grego Desfrutar de sua comida!</text>< / T"
</code>```

hope to remove all this code that is being sent to output and only send the translation to the tweet, which is what is inside .
Forgive me code redundancies, but I do not know javascript fully and my college is teaching languages a bit old, like pascal.

答:
You can perform the translation without writing a single line of code. This is the power of Node-RED. All you need is to send a properly formatted payload to an http request node. In the configuration dialog of this node tick the option Append msg.payload as query string parameters. You will get the translation by extracting msg.payload.text.

The payload to send to the http request has to be structured as follows:

```<code>{
    "key": "you key",
    "lang": "en-pt",
    "format": "plain",
    "text": "Life is like a game"
}
</code>```

The code you posted has syntax errors and will not produce the output you want.

I recommend you to study a little bit more Node-RED and ask questions their forum in case you did not understand what is explained above.

Body:
I'm a beginner in programming and I'm developing a bot on node-red in the ibm cloud, and I've had problems with the return of the yandex translation API. It returns part of the api code in the tweets, which is not pleasant at all.

The api of yandex allows the api to return in json or xml, I tried both and I could not solve the problem. The bot in question has other api's in use and I was able to configure them normally, something that does not occur with the result of that, which would be the final result for the tweet to be released.

to send the translation to be made use the following request in a function of node red:

var translate =   msg.method ='GET';
              msg.url = "https://translate.yandex.net/api/v1.5/tr/translate?key= *API KEY* &text=" + recipe + "&lang=pt"
              return [msg,null];]

in the next block, and the last one before sending the message, I'm using something like:

var yandex= msg.payload;
yandex = 'a' + msg.payload.text;
return msg;

and this makes me return something like this in the public tweet

"<?xml version="1.0" encoding="utf-8"?>
< Translation code="200" lang="en-pt"><text>é uma receita com Estilo grego Desfrutar de sua comida!</text>< / T"

hope to remove all this code that is being sent to output and only send the translation to the tweet, which is what is inside .
Forgive me code redundancies, but I do not know javascript fully and my college is teaching languages a bit old, like pascal.

Body:
You can perform the translation without writing a single line of code. This is the power of Node-RED. All you need is to send a properly formatted payload to an http request node. In the configuration dialog of this node tick the option Append msg.payload as query string parameters. You will get the translation by extracting msg.payload.text.

The payload to send to the http request has to be structured as follows:

{
    "key": "you key",
    "lang": "en-pt",
    "format": "plain",
    "text": "Life is like a game"
}

The code you posted has syntax errors and will not produce the output you want.

I recommend you to study a little bit more Node-RED and ask questions their forum in case you did not understand what is explained above.