问:
How can I check the memory usage of objects in iPython?
I am using iPython to run my code. I wonder if there is any module or command which would allow me to check the memory usage of an object. For instance:

```<code>In [1]: a = range(10000)
In [2]: %memusage a
Out[2]: 1MB
</code>```

Something like %memusage <object> and return the memory used by the object.

Duplicate

Find out how much memory is being used by an object in Python

答:
UPDATE: Here is another, maybe more thorough recipe for estimating the size of a python object.

Here is a thread addressing a similar question

The solution proposed is to write your own... using some estimates of the known size of primitives, python's object overhead, and the sizes of built in container types.

Since the code is not that long, here is a direct copy of it:

```<code>def sizeof(obj):
    """APPROXIMATE memory taken by some Python objects in
    the current 32-bit CPython implementation.

    Excludes the space used by items in containers; does not
    take into account overhead of memory allocation from the
    operating system, or over-allocation by lists and dicts.
    """
    T = type(obj)
    if T is int:
        kind = "fixed"
        container = False
        size = 4
    elif T is list or T is tuple:
        kind = "variable"
        container = True
        size = 4*len(obj)
    elif T is dict:
        kind = "variable"
        container = True
        size = 144
        if len(obj) > 8:
            size += 12*(len(obj)-8)
    elif T is str:
        kind = "variable"
        container = False
        size = len(obj) + 1
    else:
        raise TypeError("don't know about this kind of object")
    if kind == "fixed":
        overhead = 8
    else: # "variable"
        overhead = 12
    if container:
        garbage_collector = 8
    else:
        garbage_collector = 0
    malloc = 8 # in most cases
    size = size + overhead + garbage_collector + malloc
    # Round to nearest multiple of 8 bytes
    x = size % 8
    if x != 0:
        size += 8-x
        size = (size + 8)
    return size
</code>```

Body:
I am using iPython to run my code. I wonder if there is any module or command which would allow me to check the memory usage of an object. For instance:

In [1]: a = range(10000)
In [2]: %memusage a
Out[2]: 1MB

Something like %memusage <object> and return the memory used by the object.

Duplicate

Find out how much memory is being used by an object in Python

LastEditorDisplayName: Rich B

Body:
UPDATE: Here is another, maybe more thorough recipe for estimating the size of a python object.

Here is a thread addressing a similar question

The solution proposed is to write your own... using some estimates of the known size of primitives, python's object overhead, and the sizes of built in container types.

Since the code is not that long, here is a direct copy of it:

def sizeof(obj):
    """APPROXIMATE memory taken by some Python objects in
    the current 32-bit CPython implementation.

    Excludes the space used by items in containers; does not
    take into account overhead of memory allocation from the
    operating system, or over-allocation by lists and dicts.
    """
    T = type(obj)
    if T is int:
        kind = "fixed"
        container = False
        size = 4
    elif T is list or T is tuple:
        kind = "variable"
        container = True
        size = 4*len(obj)
    elif T is dict:
        kind = "variable"
        container = True
        size = 144
        if len(obj) > 8:
            size += 12*(len(obj)-8)
    elif T is str:
        kind = "variable"
        container = False
        size = len(obj) + 1
    else:
        raise TypeError("don't know about this kind of object")
    if kind == "fixed":
        overhead = 8
    else: # "variable"
        overhead = 12
    if container:
        garbage_collector = 8
    else:
        garbage_collector = 0
    malloc = 8 # in most cases
    size = size + overhead + garbage_collector + malloc
    # Round to nearest multiple of 8 bytes
    x = size % 8
    if x != 0:
        size += 8-x
        size = (size + 8)
    return size

OwnerDisplayName: John Mulder

ContentLicense: CC BY-SA 2.5


来源: stackexchange

问:
am getting undefined while trying execute following code
TypeError: Cannot read property 'bind' of undefined

getting this error, please help me.

Am trying to check and uncheck the checkbox when onchange event occures

please find the code here
https://codesandbox.io/s/competent-mendeleev-cd881

答:
Becauuse this in the loop will change the context of the current object.

Assign this to another variable and use that variable instead.

self in this case:

See solution here

ContentLicense: CC BY-SA 4.0


问:
How to find out when, where, how an eventListener is added and removed in Chrome dev tools
I have an  tag that in some point in my JS application gets a click eventListener. And unexpectedly gets a second click event listener further in time. I expect the first one to be removed first, before it is added again.

How can i use the chrome dev tools to determine when an event listener is added, removed, and which code caused it, including a call stack?

I tried console logging stuff but i still cannot see the cause.

The adding and removing of listeners is done in such functions

```<code>class SomeClass {
    /**
     * Enables listeners so that clicking on the navigatableElement can work.
     */
    enableListeners() {
        this.disableListeners();
        this._navigatableElement.addEventListener('click', this._clickEventHandler.bind(this));
    }

    /**
     * Disables listeners so that clicking on the navigatableElement will never trigger the confirmation modal anymore via this controller
     */
    disableListeners() {
        this._navigatableElement.removeEventListener('click', this._clickEventHandler.bind(this));
    }
}
</code>```

答: Your removal code does not work, because every call to .bind() generates a new function object. You're asking to remove a listener the browser does not see as registered and it ignores the call.

Body:
I have an  tag that in some point in my JS application gets a click eventListener. And unexpectedly gets a second click event listener further in time. I expect the first one to be removed first, before it is added again.

How can i use the chrome dev tools to determine when an event listener is added, removed, and which code caused it, including a call stack?

I tried console logging stuff but i still cannot see the cause.

The adding and removing of listeners is done in such functions

class SomeClass {
    /**
     * Enables listeners so that clicking on the navigatableElement can work.
     */
    enableListeners() {
        this.disableListeners();
        this._navigatableElement.addEventListener('click', this._clickEventHandler.bind(this));
    }

    /**
     * Disables listeners so that clicking on the navigatableElement will never trigger the confirmation modal anymore via this controller
     */
    disableListeners() {
        this._navigatableElement.removeEventListener('click', this._clickEventHandler.bind(this));
    }
}


问:
DynamoDB alternatives in terms of pricing? (Only pay what you use)
What are other cloud-based, serverless, managed databases that have a pricing system similar to DynamoDB? I'm specifically talking about the On-Demand mode of DynamoDB

By similar I mean, being able to pay per requests and per GB/Month or similar, instead of paying a fixed monthly fee, I understand this will mostly gear towards NoSQL databases but for me it doesn't matter the type of database.

Apart from DynamoDB, I have also found FaunaDB, but it lacks documentation and tools/integrations

It's important to note that I'm not considering pay per hour here, as that is irrelevant once you go to production.

答:
All of these have a monthly storage cost, and so I will only mention the read/write costs for each product.

Amazon Aurora Serverless is a SQL database that is priced based on the amount of "Aurora capacity units" you use for reads and writes with per-second billing. The database “pauses” itself while not in use, and you don’t pay for ACUs while the DB is paused. There is a minimum billed amount of 5 minutes every time it starts up.

Amazon Timestream (currently only in preview) is a NoSQL database that is specifically optimized for storing time-series data. Pricing is based on the size of the data that is written or read during a request.

Strictly speaking, Amazon S3 is not a database—it's an object store—but it has a per-request pricing model. You can use Amazon EMR (per-second billing, one minute minimum) or Amazon Athena (per request billing, based on the amount of data scanned) to query/analyze data that is stored in S3.

<s>Azure CosmosDB is a NoSQL database and has a per-request pricing model.</s> it turns out that you have to pay for hourly provisioning of the request units.

GCP Big Query is an Analytics Data Warehouse. It has two pricing models, including a "pay for only what you use" pricing model that based on the amount of data read or written.


问:
A Foreign Constraint fail
I'm  having an issue with a part of my Website. You can Import an excel file, this file will create products and link them to a categorie.
When I import my excel, Some lines are working and some others no. the error message is the following :

Cannot add or update a child row: a foreign key constraint fails (shop.produit_categorie, CONSTRAINT FK_produit_categorie_categorie_id FOREIGN KEY (categorie_id) REFERENCES categorie (categorie_id))

Here is the code when the excel is imported :

 public static function saveData(PDO $bdd, PHPExcel_Worksheet $objWorksheet, $constructeur_id, $catalogue_id) {

/* . . . */
                     else if ($type == RowType::PRODUIT) {

                        $data_array = self::getRowData($row);
                        $taxe_id = self::generateTaxe($bdd);
                        $produit_id = self::generateProduit($bdd, $data_array, $constructeur_id, $taxe_id);
                        self::generatePrixProduitCatalogue($bdd, $data_array, $produit_id, $catalogue, $catalogue_id, $cpt_row_full);
                        self::generateCategorieProduit($bdd, $categorie_id_courante, $produit_id);

                        $code_retour = "200";

                    } else if ($type == RowType::PLATEFORME) {
                        // si la ligne est autre chose que produit ou info -> donc intitule plateforme
                        $code_retour = "200";
                    } else {
                        // erreur
                        $code_retour = "400_" . $cpt_row;
                        break;
                    }

                }
                $cpt_row_full++;

            }// fin IF "ligne pas vide"
            $cpt_row++;
        }// fin foreach
        echo $code_retour;
    }

```

So the products are created noramlly in my Database. But what I don't understand is why some products are working correctly and some other (on the same excel, same model but 2 lines later ans the next one is working).

Do you have any idea ?

答: Maybe check if you have any value set to 0 or blank in the excel sheet or if a non-existant ID is trying to be assigned in excel.</p>

Title: A Foreign Constraint fail

Body:
I'm  having an issue with a part of my Website. You can Import an excel file, this file will create products and link them to a categorie.
When I import my excel, Some lines are working and some others no. the error message is the following :

Cannot add or update a child row: a foreign key constraint fails (shop.produit_categorie, CONSTRAINT FK_produit_categorie_categorie_id FOREIGN KEY (categorie_id) REFERENCES categorie (categorie_id))

Here is the code when the excel is imported :

 public static function saveData(PDO $bdd, PHPExcel_Worksheet $objWorksheet, $constructeur_id, $catalogue_id) {

/* . . . */
                     else if ($type == RowType::PRODUIT) {

                        $data_array = self::getRowData($row);
                        $taxe_id = self::generateTaxe($bdd);
                        $produit_id = self::generateProduit($bdd, $data_array, $constructeur_id, $taxe_id);
                        self::generatePrixProduitCatalogue($bdd, $data_array, $produit_id, $catalogue, $catalogue_id, $cpt_row_full);
                        self::generateCategorieProduit($bdd, $categorie_id_courante, $produit_id);

                        $code_retour = "200";

                    } else if ($type == RowType::PLATEFORME) {
                        // si la ligne est autre chose que produit ou info -> donc intitule plateforme
                        $code_retour = "200";
                    } else {
                        // erreur
                        $code_retour = "400_" . $cpt_row;
                        break;
                    }

                }
                $cpt_row_full++;

            }// fin IF "ligne pas vide"
            $cpt_row++;
        }// fin foreach
        echo $code_retour;
    }

So the products are created noramlly in my Database. But what I don't understand is why some products are working correctly and some other (on the same excel, same model but 2 lines later ans the next one is working).

Do you have any idea ?


问:
In Silverlight, is it possible to bind buttons to a command from a different class?
In Silverlight, if  the datacontext of the userControl inn Xaml is Class A, can a button in the  bind to a command in a different class (lets say class B)?

Thanks.

答:
Yes this can be done. there are several ways:

You could assign the DataContext of the button to an instance of class B.

You could add an instance of class to the Resources of the button (or one of the button's parents) and point the binding to a StaticResource

Add a property of type B to class A and bind the Command of the button to that property of class A.

I prefer none of these option but if I have to chose I pick #3. #1 and #2 cause too much confusion. The best solution IMHO is to add the Command to class A because that is much more clear and fits a MVVM state of mind

ContentLicense: CC BY-SA 3.0


问:
ACF Post Object in Timber not showing on page template
Data isn't showing on page template using ACF Post Object and calling it with Timber.

Tried to add the data to index.php and the news.php template.

ACF Post Object Field Name:

```<code>news_author_data
</code>```

news.php

```<code>$post = new TimberPost();
$context['post'] = $post;

$context['news_author'] = new
TimberPost(get_field('news_author_data'));
Timber::render('core/news.twig', $context);
</code>```

news.twig

```<code>{% for news in news_author %}
  test
{% endfor %}
</code>```

No error message.  Just no data.

答:
If get_field('news_author_data') returns an array of post objects you can't put the collection directly into the "new TimberPost" constructor. You have to loop through them like so:

$post = new TimberPost();
$context['post'] = $post;

$context['news_author'] = array_map(function($post) {
    return new TimberPost($post);
}, get_field('news_author_data'));

Timber::render('core/news.twig', $context);
```

Hope this helps.

Body:
Data isn't showing on page template using ACF Post Object and calling it with Timber.

Tried to add the data to index.php and the news.php template.

ACF Post Object Field Name:

news_author_data

news.php

$post = new TimberPost();
$context['post'] = $post;

$context['news_author'] = new
TimberPost(get_field('news_author_data'));
Timber::render('core/news.twig', $context);

news.twig

{% for news in news_author %}
  test
{% endfor %}

No error message.  Just no data.

Body:
If get_field('news_author_data') returns an array of post objects you can't put the collection directly into the "new TimberPost" constructor. You have to loop through them like so:

$post = new TimberPost();
$context['post'] = $post;

$context['news_author'] = array_map(function($post) {
    return new TimberPost($post);
}, get_field('news_author_data'));

Timber::render('core/news.twig', $context);

Hope this helps.


问:
Using big endian in struct pack Python with a Pointer
I'm using the struct pack in Python 3.7.

I have this header containing 6 uint32 and one void * argument.

I want to put it in binary format. Unfortunately the interface I'm working on only supports big endian.So I actually need to transform what I send.
But since P format can't have its endianess modified I always get struct error.
So how can I rewrite this to avoid having this error.

PS: I cannot remove the void * it an mandatory field of my header

```<code>u1 = 0x4569
u2 = 0x1236
u3 = 0x4411
u4 = 0x1236
u5 = 0x9696
point = 0 #(For now)
data = 0x26358974
buffer = struct.pack('5IPI',u1,u2,u3,u4,u5,point,data)
</code>```

Actual output

```<code>buffer = b'\x69\x45\x00\x00\x36\x12\x00\x00\x11\x44\\x00\x00\x36\x12\x00\x00\x96\x96\\x00\x00\x00\x00\x00\x00\x74\x89\x35\26'
</code>```

WHILE what I want would be:

```<code>buffer = b'\x00\x00\45\x69\x00\x00\x12\36\x00\x00\x44\x11\x00\x00\x12\x36\\x00\x00\x96\x96\x00\x00\x00\x00\x26\x35\x89\x74'
</code>```

答:
You may need to do this in two stages:

```<code>u1=1
u2=2
u3=3
u4=4
u5=5
point=6
data=7

# construct two separate buffers
b1 = struct.pack('>5I', u1, u2, u3, u4, u5)
b2 = struct.pack('P', point)
</code>```

Then convert the pointer back to a regular uint, and then back to a pointer:

```<code>p2 = struct.unpack('I', b2)
b2a = struct.pack('>I', p2[0])
b1 = b1 + b2a
print(b1)
</code>```

Output:

```<code>b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06'
</code>```

Body:
I'm using the struct pack in Python 3.7.

I have this header containing 6 uint32 and one void * argument.

I want to put it in binary format. Unfortunately the interface I'm working on only supports big endian.So I actually need to transform what I send.
But since P format can't have its endianess modified I always get struct error.
So how can I rewrite this to avoid having this error.

PS: I cannot remove the void * it an mandatory field of my header

u1 = 0x4569
u2 = 0x1236
u3 = 0x4411
u4 = 0x1236
u5 = 0x9696
point = 0 #(For now)
data = 0x26358974
buffer = struct.pack('5IPI',u1,u2,u3,u4,u5,point,data)

Actual output

buffer = b'\x69\x45\x00\x00\x36\x12\x00\x00\x11\x44\\x00\x00\x36\x12\x00\x00\x96\x96\\x00\x00\x00\x00\x00\x00\x74\x89\x35\26'

WHILE what I want would be:

buffer = b'\x00\x00\45\x69\x00\x00\x12\36\x00\x00\x44\x11\x00\x00\x12\x36\\x00\x00\x96\x96\x00\x00\x00\x00\x26\x35\x89\x74'

Body:
You may need to do this in two stages:

u1=1
u2=2
u3=3
u4=4
u5=5
point=6
data=7

# construct two separate buffers
b1 = struct.pack('>5I', u1, u2, u3, u4, u5)
b2 = struct.pack('P', point)

Then convert the pointer back to a regular uint, and then back to a pointer:

p2 = struct.unpack('I', b2)
b2a = struct.pack('>I', p2[0])
b1 = b1 + b2a
print(b1)

Output:

b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06'


问:
Maven: build Scala code and Java code together into a Fat JAR
I have a Scala project that I build into a Fat JAR. Today I needed to add some Java classes to the project but now my Maven build is failing.

My project structure looks (roughly) like this:

```<code>.
├── src
│   └── main
│       ├── resources
│       │   └── Log4j.properties
|       ├── java
│       │   └── com
│       │       └── myorg
│       │           └── myproject
│       │               └── MyPublicJavaClass.java
│       └── scala
│           └── com
│               └── myorg
│                   └── myproject
│                       └── spark
│                           └── Main.scala
└── pom.xml
</code>```

And here's what my POM file looks like:

```<code><?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <name>myproject</name>
  <url>http://maven.apache.org</url>

  <groupId>com.myorg</groupId>
  <artifactId>myproject</artifactId>
  <packaging>jar</packaging>
  <version>0.1.0-RELEASE</version>

  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <encoding>UTF-8</encoding>
    <scala.tools.version>2.11</scala.tools.version>
    <scala.version>2.11.8</scala.version>
    <spark.version>2.4.0</spark.version>
    <aws.sdk.version>1.11.553</aws.sdk.version>
  </properties>

  <build>
    <sourceDirectory>src/main/scala</sourceDirectory>
    <testSourceDirectory>src/test/scala</testSourceDirectory>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>src/test/resources</directory>
      </testResource>
    </testResources>

    <plugins>
      <!-- I added this plugin today to try and make it compile the Java code -->
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>3.0.0</version>
        <executions>
          <execution>
            <phase>generate-sources</phase>
            <configuration>
              <sources>
                <source>src/main/java</source>
              </sources>
            </configuration>
          </execution>
        </executions>
      </plugin>

      <!-- This compiles the Scala code -->
      <plugin>
        <groupId>org.scala-tools</groupId>
        <artifactId>maven-scala-plugin</artifactId>
        <version>2.15.2</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>testCompile</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <!-- This builds the fat JAR -->
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.myorg.myproject.spark.Main</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
        <executions>
          <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>${scala.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-core_${scala.tools.version}</artifactId>
      <version>${spark.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-sql_${scala.tools.version}</artifactId>
      <version>${spark.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-core</artifactId>
      <version>${aws.sdk.version}</version>
    </dependency>
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-dynamodb</artifactId>
      <version>${aws.sdk.version}</version>
    </dependency>
    <dependency>
      <groupId>com.amazon.emr</groupId>
      <artifactId>emr-dynamodb-hadoop</artifactId>
      <version>4.8.0</version>
    </dependency>
    <dependency>
      <groupId>com.github.scopt</groupId>
      <artifactId>scopt_${scala.tools.version}</artifactId>
      <version>3.7.1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-scala</artifactId>
      <version>11.0</version>
      <type>pom</type>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.2</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>
</code>```

Before I added the Java class, along with the build-helper-maven-plugin today, Maven was able to build this project without any problems. But now, it seems I haven't configured that plugin correctly, or perhaps I'm not using the right one?

My Scala code is trying to use an object of type MyPublicJavaClass so now the build errors I see in Maven look like this:

[ERROR] ~/src/main/scala/com/myorg/myproject/spark/Main.scala:227: error: not found: type MyPublicJavaClass

...

[ERROR] Failed to execute goal org.scala-tools:maven-scala-plugin:2.15.2:compile (default) on project myproject: wrap: org.apache.commons.exec.ExecuteException: Process exited with an error: 1(Exit value: 1) -> [Help 1]

I thought that the build-helper-maven-plugin would tell it to add the Java code's source directory to the list of sources to generate before compile time, but apparently not. How can I fix this?

答:
You are using a very old plugin for your Scala compilation (last version 2.15.2 have been released Feb 6 2011).

I suggest you first to upgrade to a more recent plugin, like scala-maven-plugin (latest release 4.0.2 on May 11 2019).

You can then found an example with mixed Scala/Java sources in the docs. There is no need to use build-helper-maven-plugin in this case, nor to configure sourceDirectory and testSourceDirectory. Check this simple pom.xml with this plugin (I have just removed the unused dependencies from the example you have provided when I reproduced the problem locally) :

<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <name>myproject</name>
  <url>http://maven.apache.org</url>

  <groupId>com.myorg</groupId>
  <artifactId>myproject</artifactId>
  <packaging>jar</packaging>
  <version>0.1.0-RELEASE</version>

  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <encoding>UTF-8</encoding>
    <scala.tools.version>2.11</scala.tools.version>
    <scala.version>2.11.8</scala.version>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>net.alchim31.maven</groupId>
        <artifactId>scala-maven-plugin</artifactId>
        <version>4.0.2</version>
          <executions>
            <execution>
              <id>scala-compile-first</id>
              <phase>process-resources</phase>
              <goals>
                <goal>add-source</goal>
                <goal>compile</goal>
              </goals>
            </execution>
            <execution>
              <id>scala-test-compile</id>
              <phase>process-test-resources</phase>
              <goals>
                <goal>testCompile</goal>
              </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.myorg.myproject.spark.Main</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
        <executions>
          <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>${scala.version}</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
</project>
```

Body:
I have a Scala project that I build into a Fat JAR. Today I needed to add some Java classes to the project but now my Maven build is failing.

My project structure looks (roughly) like this:

.
├── src
│   └── main
│       ├── resources
│       │   └── Log4j.properties
|       ├── java
│       │   └── com
│       │       └── myorg
│       │           └── myproject
│       │               └── MyPublicJavaClass.java
│       └── scala
│           └── com
│               └── myorg
│                   └── myproject
│                       └── spark
│                           └── Main.scala
└── pom.xml

And here's what my POM file looks like:

<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <name>myproject</name>
  <url>http://maven.apache.org</url>

  <groupId>com.myorg</groupId>
  <artifactId>myproject</artifactId>
  <packaging>jar</packaging>
  <version>0.1.0-RELEASE</version>

  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <encoding>UTF-8</encoding>
    <scala.tools.version>2.11</scala.tools.version>
    <scala.version>2.11.8</scala.version>
    <spark.version>2.4.0</spark.version>
    <aws.sdk.version>1.11.553</aws.sdk.version>
  </properties>

  <build>
    <sourceDirectory>src/main/scala</sourceDirectory>
    <testSourceDirectory>src/test/scala</testSourceDirectory>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>src/test/resources</directory>
      </testResource>
    </testResources>

    <plugins>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>3.0.0</version>
        <executions>
          <execution>
            <phase>generate-sources</phase>
            <configuration>
              <sources>
                <source>src/main/java</source>
              </sources>
            </configuration>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.scala-tools</groupId>
        <artifactId>maven-scala-plugin</artifactId>
        <version>2.15.2</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>testCompile</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.myorg.myproject.spark.Main</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
        <executions>
          <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>${scala.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-core_${scala.tools.version}</artifactId>
      <version>${spark.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-sql_${scala.tools.version}</artifactId>
      <version>${spark.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-core</artifactId>
      <version>${aws.sdk.version}</version>
    </dependency>
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-dynamodb</artifactId>
      <version>${aws.sdk.version}</version>
    </dependency>
    <dependency>
      <groupId>com.amazon.emr</groupId>
      <artifactId>emr-dynamodb-hadoop</artifactId>
      <version>4.8.0</version>
    </dependency>
    <dependency>
      <groupId>com.github.scopt</groupId>
      <artifactId>scopt_${scala.tools.version}</artifactId>
      <version>3.7.1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-scala</artifactId>
      <version>11.0</version>
      <type>pom</type>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.2</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

Before I added the Java class, along with the build-helper-maven-plugin today, Maven was able to build this project without any problems. But now, it seems I haven't configured that plugin correctly, or perhaps I'm not using the right one?

My Scala code is trying to use an object of type MyPublicJavaClass so now the build errors I see in Maven look like this:

[ERROR] ~/src/main/scala/com/myorg/myproject/spark/Main.scala:227: error: not found: type MyPublicJavaClass

...

[ERROR] Failed to execute goal org.scala-tools:maven-scala-plugin:2.15.2:compile (default) on project myproject: wrap: org.apache.commons.exec.ExecuteException: Process exited with an error: 1(Exit value: 1) -> [Help 1]

I thought that the build-helper-maven-plugin would tell it to add the Java code's source directory to the list of sources to generate before compile time, but apparently not. How can I fix this?

Body:
You are using a very old plugin for your Scala compilation (last version 2.15.2 have been released Feb 6 2011).

I suggest you first to upgrade to a more recent plugin, like scala-maven-plugin (latest release 4.0.2 on May 11 2019).

You can then found an example with mixed Scala/Java sources in the docs. There is no need to use build-helper-maven-plugin in this case, nor to configure sourceDirectory and testSourceDirectory. Check this simple pom.xml with this plugin (I have just removed the unused dependencies from the example you have provided when I reproduced the problem locally) :

<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <name>myproject</name>
  <url>http://maven.apache.org</url>

  <groupId>com.myorg</groupId>
  <artifactId>myproject</artifactId>
  <packaging>jar</packaging>
  <version>0.1.0-RELEASE</version>

  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <encoding>UTF-8</encoding>
    <scala.tools.version>2.11</scala.tools.version>
    <scala.version>2.11.8</scala.version>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>net.alchim31.maven</groupId>
        <artifactId>scala-maven-plugin</artifactId>
        <version>4.0.2</version>
          <executions>
            <execution>
              <id>scala-compile-first</id>
              <phase>process-resources</phase>
              <goals>
                <goal>add-source</goal>
                <goal>compile</goal>
              </goals>
            </execution>
            <execution>
              <id>scala-test-compile</id>
              <phase>process-test-resources</phase>
              <goals>
                <goal>testCompile</goal>
              </goals>
          </execution>
        </executions>
      </plugin>

      <!-- This builds the fat JAR -->
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.myorg.myproject.spark.Main</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
        <executions>
          <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>${scala.version}</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
</project>


问:
OCaml pattern matching on integers
I have an assignment to fill in the following code stub:

```<code>let quad (x,y) =
  match (x,y) with
  | ... -> ...
  ...
</code>```

where the quad function is supposed to take a tuple of ints as its argument, and return an algebraic data type representing the quadrant that the coordinates lie in.  I know exactly how to do it using if-clauses, but how would one do this using matching?  Is there a way to match integers with their sign?  I know I could even do it by matching on the value of a sign function.  I could write a function sign such that sign 10 = 1 and sign (-10) = -1 and so on, and then match on these values, but according to the code stub I shouldn't even do that.  Any hint on how to accomplish this?  Should I only do my matching on 0, and then if it's not 0 use if-clauses after the ->?  Or is there some use of matching that can detect positive and negative integers?

答:
Ugly solution but fits the code stub :)

```<code>let quad (x,y) =
  match (x,y) with
  | (0, 0) -> `Center
  | _ -> begin
    let sign = function
      | 0 -> 0
      | x -> if x < 0 then -1 else 1
    in
    match (sign x), (sign y) with
    | -1, -1 -> `LeftBottom
    | -1, 1 -> `LeftTop
    | 1, -1 -> `RightBottom
    | 1, 1 -> `RightTop
  end
</code>```

(I would never solve the task this way in real life)

UPD. As @Virgile mentioned in comments, the code above is not complete. There is an edge case which is not processed properly: when the point belongs to x- or y-axis (e.g. only one of its coordinates is zero). These cases can be obviously matched either in the outer match

```<code>...
| (0, _) -> `YAxis
| (_, 0) -> `XAxis
...
</code>```

or in the inner match with clauses like

```<code>| 0, -1 | 0, 1 -> `YAxis
...
</code>```

(or even in a more detailed manner if necessary - with different variants for positive and negative semiaxis)

Title: OCaml pattern matching on integers

Body:
I have an assignment to fill in the following code stub:

let quad (x,y) =
  match (x,y) with
  | ... -> ...
  ...

where the quad function is supposed to take a tuple of ints as its argument, and return an algebraic data type representing the quadrant that the coordinates lie in.  I know exactly how to do it using if-clauses, but how would one do this using matching?  Is there a way to match integers with their sign?  I know I could even do it by matching on the value of a sign function.  I could write a function sign such that sign 10 = 1 and sign (-10) = -1 and so on, and then match on these values, but according to the code stub I shouldn't even do that.  Any hint on how to accomplish this?  Should I only do my matching on 0, and then if it's not 0 use if-clauses after the ->?  Or is there some use of matching that can detect positive and negative integers?

Body:
Ugly solution but fits the code stub :)

let quad (x,y) =
  match (x,y) with
  | (0, 0) -> `Center
  | _ -> begin
    let sign = function
      | 0 -> 0
      | x -> if x < 0 then -1 else 1
    in
    match (sign x), (sign y) with
    | -1, -1 -> `LeftBottom
    | -1, 1 -> `LeftTop
    | 1, -1 -> `RightBottom
    | 1, 1 -> `RightTop
  end

(I would never solve the task this way in real life)

UPD. As @Virgile mentioned in comments, the code above is not complete. There is an edge case which is not processed properly: when the point belongs to x- or y-axis (e.g. only one of its coordinates is zero). These cases can be obviously matched either in the outer match

...
| (0, _) -> `YAxis
| (_, 0) -> `XAxis
...

or in the inner match with clauses like

| 0, -1 | 0, 1 -> `YAxis
...

(or even in a more detailed manner if necessary - with different variants for positive and negative semiaxis)


问:
Unknown element <select> in SQL statement MyBatis
I am trying the functionality like saveOrUpdate with MyBatis, but I am getting the exception while deployment. Below is the query

```<code>@Select("<script>"
            + "<foreach item='item' index='index' collection='machineList'>"
            + "<select id='count' resultType='int'>"
            + "Select count(*) from nc_macine_data where (machine_id=#{item.machineId} and machine_name=#{item.machineName} and mchine_value=#{item.machineValue})"
            + "</select>"
            + "<if test='count > 0'>" +
            "    UPDATE nc_macine_data set mchine_value=#{item.machineValue} where (machine_id=#{item.machineId} and machine_name=#{item.machineName}"
            + "</if>"
            + "<if test='count==0'>"
            + " INSERT INTO nc_macine_data (machine_id, machine_name, mchine_value) values (#{element.machineId}, #{element.machineName}, #{element.machineValue})"
            + "</if>"
            + "</foreach>"
            + "</script>")
</code>```

Error:

```<code>Caused by: org.apache.ibatis.builder.BuilderException: Could not find value method on SQL annotation.  Cause: org.apache.ibatis.builder.BuilderException: Unknown element <select> in SQL statement.
</code>```

What I am missing here?

Body:
I am trying the functionality like saveOrUpdate with MyBatis, but I am getting the exception while deployment. Below is the query

@Select("")

Error:

Caused by: org.apache.ibatis.builder.BuilderException: Could not find value method on SQL annotation.  Cause: org.apache.ibatis.builder.BuilderException: Unknown element <select> in SQL statement.

What I am missing here?

Body:
In the example you are implicitly assuming that foreach, select, if and update are commands that are executed from top to bottom. And this is not the case.

The elements in <script> are very much like definitions in xml mapper. They are not a part of an imperative language like you are trying to use them.

The code tries to use select to "define" a variable that it tries to use later in if and this is exactly what does not work.

Back to the original problem. What you are trying to do is called upsert and this is inherently hard problem and the naive approach to check and update or insert will not work correctly.

Different DBs provide different means to do upserts: postgres solution, mysql, oracle.


问:
How can I turn a UNIX timestamp into a Google Sheets date value?
I'm using Google Apps Script to retrieve some data through an API. The date that is given to me is a standard ISO 8601 string, and I need to convert that to a date number that will be understood by Google Sheets when I display it (i.e. as the Google Sheets / Excel standard date value)

Currently I'm using a workaround which is passing a string in my cells then converting it through the DATEVALUE() function but it is not optimal, since I cant use that function natively in my script (from my research on the topic).

I want to create a function directly in Google Apps script that converts the Javascript ol' Date() object into a readable value for my spreadsheet.

I've made a few attempts by converting the seconds since 1970 to the number of days since 1900 but I always have a two-hour gap that I can't explain. I suspect it has to do with the fact that I am in UTC+2, but can't really solve it, and adding two hours sounds like a bad fix.

The baseline of what I've gotten to so far is this :

```<code>function toDateNum(string) {

  //Parsing to Unix Timestamp
  date = new Date(string).getTime() / 1000

  //Here I need convert to GSheets date value, add the number of days between 1900-01-01 and 1970-01-01

  return date ;

}
</code>```

I'm looking either for an arithmetic solve for this (converting and adding dates) or for a function integrated in the Google Sheets app that would allow me to work with this. Any suggestions ?

Thanks a lot !

EDIT (with additional clarification)

One of my issues is that the toISOString format returned is not supported by google sheets directly. It will only be read as a string, not as a date value. Currently, I'm working around this by sending the toISOString value in the cells and reformat using DateValue() directly in the table. I'm trying to do that natively in the script.

To the best of my knowledge, the date value supported by Google Sheets (and Excel) is the number of days since 1900-01-01. A simple arithmetic solution should be found (computing a unix timestamp from seconds then to days then add the difference between 1900-01-01 to 1970-01-01) but, then again, I get my two-hour gap that messes everything up.

答:
In the question linked below, the response by user79865 explains how to manage dates and their formats within sheets. The Sheets API documentation also specifies all the different formats you can use as well as how to create your own when working with dates and times. The     Utilities.formatDate() will help you change the date format to whatever you need.

Question URL: https://webapps.stackexchange.com/questions/88621/basic-date-manipulation-in-google-script?newreg=7c66fdcf156f4ff5a30eb5fa4153b243

Sheets Documentation URL: https://developers.google.com/sheets/api/guides/formats

Body:
I'm using Google Apps Script to retrieve some data through an API. The date that is given to me is a standard ISO 8601 string, and I need to convert that to a date number that will be understood by Google Sheets when I display it (i.e. as the Google Sheets / Excel standard date value)

Currently I'm using a workaround which is passing a string in my cells then converting it through the DATEVALUE() function but it is not optimal, since I cant use that function natively in my script (from my research on the topic).

I want to create a function directly in Google Apps script that converts the Javascript ol' Date() object into a readable value for my spreadsheet.

I've made a few attempts by converting the seconds since 1970 to the number of days since 1900 but I always have a two-hour gap that I can't explain. I suspect it has to do with the fact that I am in UTC+2, but can't really solve it, and adding two hours sounds like a bad fix.

The baseline of what I've gotten to so far is this :

function toDateNum(string) {

  //Parsing to Unix Timestamp
  date = new Date(string).getTime() / 1000

  //Here I need convert to GSheets date value, add the number of days between 1900-01-01 and 1970-01-01

  return date ;

}

I'm looking either for an arithmetic solve for this (converting and adding dates) or for a function integrated in the Google Sheets app that would allow me to work with this. Any suggestions ?

Thanks a lot !

EDIT (with additional clarification)

One of my issues is that the toISOString format returned is not supported by google sheets directly. It will only be read as a string, not as a date value. Currently, I'm working around this by sending the toISOString value in the cells and reformat using DateValue() directly in the table. I'm trying to do that natively in the script.

To the best of my knowledge, the date value supported by Google Sheets (and Excel) is the number of days since 1900-01-01. A simple arithmetic solution should be found (computing a unix timestamp from seconds then to days then add the difference between 1900-01-01 to 1970-01-01) but, then again, I get my two-hour gap that messes everything up.


问:
How to rate limit scan to AWS DynamoDB for AWS CLI?
I have created the following query to query my table :

```<code>aws dynamodb scan --table-name TableName --scan-filter '{
"attributeName" : {
    "AttributeValueList" : [ {"S" : "StringToQuery"}],
    "ComparisonOperator" : "CONTAINS"
}
}'
</code>```

This is causing a spike in read capacity for that table, which will probably lead to throttling of customer requests. I couldn't find any command line option to limit the rate in https://docs.aws.amazon.com/cli/latest/reference/dynamodb/scan.html, but I did find a java script with rate limit : https://aws.amazon.com/blogs/developer/rate-limited-scans-in-amazon-dynamodb/

Is there any way to do it from AWS CLI?

答:
Went ahead with creating a new index over a value which i knew was almost always "Y", like isActive, and added a filter on top of the query. Since it was a new index, it didn't affect existing index capacity.

Answer by cementblocks would reduce the RCU consumed too, but I needed a guarantee that customers would not be impacted.

Body:
I have created the following query to query my table :

aws dynamodb scan --table-name TableName --scan-filter '{
"attributeName" : {
    "AttributeValueList" : [ {"S" : "StringToQuery"}],
    "ComparisonOperator" : "CONTAINS"
}
}'

This is causing a spike in read capacity for that table, which will probably lead to throttling of customer requests. I couldn't find any command line option to limit the rate in https://docs.aws.amazon.com/cli/latest/reference/dynamodb/scan.html, but I did find a java script with rate limit : https://aws.amazon.com/blogs/developer/rate-limited-scans-in-amazon-dynamodb/

Is there any way to do it from AWS CLI?


问:
Mac C++/eclipse cannot debug: Error while launching command: gdb --version
I am using c++/eclipse kepler on mac, and I cannot debug any project. The error is "Error while launching command: gdb --version" Besides that, I can build and run my code using other libraries.

I searched a site that is similar to my problem: Debugger for C++ eclipse gives the following error. 'Launching program name' has encountered a ... Error while launching command: gdb --version

But what should I change if I am using a mac?

答:
Mac OS Sierra 10.13.6 gdb 8.0.1

had the same error as topic-starter.

first, I set the path as Neil Traft (here in the answers) explains to usr/local/bin/gdb;

But it didn't work.

I found these instructions:
https://gist.github.com/gravitylow/fb595186ce6068537a6e9da6d8b5b96d

and I discovered that I already had gdbcert1 in my System. So I followed everything from 7. Works!


答:
Try adding a constant referencing this inside your render like so:

```<code>import React from "react";
import todosData from "./TodoData";
import ToDoItems from "./ToDoItems";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      todos: todosData
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(id) {
    this.setState(prevState => {
      const updateTodo = prevState.todos.map(todo => {
        if (todo.id === id) {
          todo.completed = !todo.completed;
        }
        return todo;
      });
      return {
        todos: updateTodo
      };
    });
  }
  render() {
    const that = this;
    const todoData = this.state.todos.map(function(item) {
      return (
        <ToDoItems key={item.id} item={item} handleChange={that.handleChange} />
      );
    });
    return <div>{todoData}</div>;
  }
}
export default App;
</code>```

Title: am getting undefined while trying execute following code

Body:
TypeError: Cannot read property 'bind' of undefined

getting this error, please help me.

Am trying to check and uncheck the checkbox when onchange event occures

please find the code here
https://codesandbox.io/s/competent-mendeleev-cd881

Body:
Try adding a constant referencing this inside your render like so:

import React from "react";
import todosData from "./TodoData";
import ToDoItems from "./ToDoItems";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      todos: todosData
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(id) {
    this.setState(prevState => {
      const updateTodo = prevState.todos.map(todo => {
        if (todo.id === id) {
          todo.completed = !todo.completed;
        }
        return todo;
      });
      return {
        todos: updateTodo
      };
    });
  }
  render() {
    const that = this;
    const todoData = this.state.todos.map(function(item) {
      return (
        <ToDoItems key={item.id} item={item} handleChange={that.handleChange} />
      );
    });
    return <div>{todoData}</div>;
  }
}
export default App;


问:
View PDFs with forms in Firefox
I am working on a web application and there is a need to preview PDF in Firefox.

Obviously I have embedded the PDF in the HTML code. The problem is that these PDFs contain forms and I know that the built-in Firefox viewer cannot display forms. Except the forms (which contain digital signatures) the rest of the document is displayed properly and in Chrome everything works fine (displaying the signatures too).

I want to ask which is the best approach to support the view of the whole document in Firefox. The current version I am working on is 52.7.3 but I want to do the system scalable for future versions.

I was thinking of transforming the PDF into a Base64 String and embed like that but trying this with some online demos did not work either (maybe the document is quite big?).

The other posibility I was thinking of, is transforming the PDF in JPEG (or similar format) and preview like that. What do you think about that?

Is there any library to handle PDF files from Java/Javascript code that does not use embedded viewers? I tried PDF.js but I realised that it is using the built in viewers. Correct me on this If I am wrong.

答: Is mandatory to open file specifically with Firefox? If not, you can use     Desktop.open(File) to open a file with the default application for PDF files. (https://docs.oracle.com/javase/7/docs/api/java/awt/Desktop.html)</p>

Title: View PDFs with forms in Firefox


问:
Function to check a row in database with session variable not working
I'm working on a web app, in PHP and AngularJS.

I want to restrict a part of my navbar for users that has a special row. (Like admins)

I made an angularJS function in my controller, which calls a function in my PHP Controller. (I'm working on with MVC and no PHP framework)

The problem is that I pass a variable session in parameter, which the one I can identify my user in my database, and it's not working.

The function is not working. No erros in the logs, no errors in the console, nothing. The "Admin" part of my navbar won't go back if I got the good right to see it.

PHP Function

```<code>function verifierHabilitation ( $req, $api ){
    if(droitsModificationAdmin( $_SESSION['nni'] ) == "administration") {
        return 1;
    }
}
</code>```

I'm calling my function droitsModificationAdmin() to verify the row, and I'm using a variable session in parameter.

AngularJS Function Call in my navbar

```<code><li class="nav-item" ng-if="droitsAdmin() == 1" >
    <h2 ng-class="{ 'grdf-ss-title' : isActive('/admin') }" >
       <a class="nav-link" href="#/admin">Admin</a>
    </h2>
</li>
</code>```

Here I'm using ng-if to verify the return of my previous function.

I don't know where the problem is. Do you have any idea ?

EDIT :

Here is all the code I used :

AJS :
In my controller.js

```<code>$scope.droitsAdmin = function() { factoryDossier.verifierHabilitation(); };
</code>```

In my factory.js

```<code>verifierHabilitation : function(){

    return $http({
        url: 'controleurs/Controleur-Admin.php'
        ,method: "POST"
        ,data: $.param({
            fonction : 'verifierHabilitation'
        })
        ,headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });
},

</code>```

PHP:
Controller.php

```<code>function verifierHabilitation ( $req, $api ){
    if(droitsModificationAdmin( $_SESSION['nni'] ) == "administration") {
        echo "ceci est un test";
        return 1;
    }
}
</code>```

Here I am calling the function which is in the global controller.

Global Controller

```<code>function droitsModificationAdmin( $nni ){
    $bdd = new Model_Habilitation( PDO_bdd_app() );
    $utilisateur = $bdd->habilitation( $nni );
    return ( $utilisateur[0]['h_habilitation'] );
}
</code>```

Model.php

```<code>public function habilitation( $nni ){
        $sql = $this->grea_ouest->prepare('SELECT h_habilitation FROM '.$this->table_habilitation.' h WHERE h.h_nni = :nni');
        $sql->execute( array( ':nni' => $nni ) );
        return $sql->fetchAll(PDO::FETCH_ASSOC);
    }
</code>```

Controleur-Configuration.php

(Sorry the code is in french)

```<code><?php

require_once('Controleur-Configuration.php');
require_once('api_rest.php');
require_once(dirname(__FILE__).'/../class/ClassAdmin.php');
require_once(model_url('Model_Admin'));
require_once('Helpers.php');

#############################################################
gestion_session();//Gestion à partir du fichier configuration
#############################################################

$api = new Rest;

try {
    $req = $api->get_request();
    if( function_exists( $req['fonction'] ) ){ $req['fonction']( $req, $api ); } else { throw new Exception('Fonction inexistante'); }
} catch(Exception $e){
    $api->response(array(), 501);
}

/**
 * Retourne les informations d'un admin
 * @param $req array : les données passées en parametres
 * @param $api Rest : l'objet Rest permettant l'interaction avec le client.
 * @return array : les informations du dossier.
 */
function getAdmins( $req, $api ){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $Admins = $bdd->getAdmins();
        foreach($Admins as $key=>$Admin){ $Admins[$key] = $Admin->json_encode(); }
        $api->response( $Admins, 200);
    } catch(Exception $e){ error_log( $e ); $api->response( "", 500); }
}

/**
 * Retourne les habilitations
 * @param $req array : les données passées en parametres
 * @param $api Rest : l'objet Rest permettant l'interaction avec le client.
 * @return array : les informations du dossier.
 */
function getHabilitations( $req, $api ){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $Habilitations = $bdd->getHabilitations();
        foreach($Habilitations as $key=>$Habilitation){ $Habilitations[$key] = $Habilitation->json_encode(); }
        $api->response( $Habilitations, 200);
    } catch(Exception $e){ error_log( $e ); $api->response( "", 500); }
}

/**
* Met a jour un habilité
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function updateAdmin( $req, $api ){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try {
        if( isset($req['NewAdmin']) ){
            $admin = cast( $req['NewAdmin'], 'Admin' );
        } else { $api->response( array( "erreur" => array(array("Aucunes informations saisies"))), 409); }

            try
            {
                $bdd = new Model_Admin( PDO_bdd_app() );
                $newAdmin = $bdd->updateAdmin( $admin );
                $api->response( array( "dev"=>$newAdmin->json_encode(), "info"=>array("Le développeur a été modifié")), 200);
    } catch( Exception $e ){ error_log( $e ); $api->response( "", 500); }
    } catch( Exception $e ){ error_log( $e ); $api->response( "", 500); }
}

/**
* Change l'habilitation d'un utilisateur
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function changerHabilitation ($req, $api){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $habilitation = $bdd->changerHabilitation( $req['nni'], $req['habilitation'] );
    } catch(Exception $e){
        error_log( $e );
        $api->response( $e, 500);
    }
}

function verifierHabilitation ( $req, $api ){
    if(droitsModificationAdmin( $_SESSION['nni'] ) == "administration") {
        echo "ceci est un test";
        return 1;
    }
}

/**
* Approuve un utilisateur
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function approuverUtilisateur ($req, $api){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $utilisateur = $bdd->approuverUtilisateur( $req['nni'] );
    } catch(Exception $e){
        error_log( $e );
        $api->response( $e, 500);
    }
}

/**
* Refuse un utilisateur
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function refuserUtilisateur ($req, $api){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $utilisateur = $bdd->refuserUtilisateur( $req['nni'] );
    } catch(Exception $e){
        error_log( $e );
        $api->response( $e, 500);
    }
}

?>

</code>```

答:
Okay so as you need some permission module you can do something like this:
Create an Angularjs service to store all the permission values, so you don't have to hit your database again and again, store your permission values in this service at the time of login.
Use your code like this :

```<code><div ng-if="permission == 'user'">
    Some content which you want to show to **USER** only.
</div>
<div ng-if="permission == 'user' || permission == 'admin'">
    Some content which you want to show to **USER and ADMIN** both.
</div>
<div ng-if="permission == 'admin'">
    Some content which you want to show to **ADMIN** only.
</div>
</code>```

Looks like you are calling your PHP function from JAVASCRIPT.
You cannot do this.
You have to make an HTTP request (AJAX CALL) to perform this operation.
Let me know if you have any doubt.

Body:
I'm working on a web app, in PHP and AngularJS.

I want to restrict a part of my navbar for users that has a special row. (Like admins)

I made an angularJS function in my controller, which calls a function in my PHP Controller. (I'm working on with MVC and no PHP framework)

The problem is that I pass a variable session in parameter, which the one I can identify my user in my database, and it's not working.

The function is not working. No erros in the logs, no errors in the console, nothing. The "Admin" part of my navbar won't go back if I got the good right to see it.

PHP Function

function verifierHabilitation ( $req, $api ){
    if(droitsModificationAdmin( $_SESSION['nni'] ) == "administration") {
        return 1;
    }
}

I'm calling my function droitsModificationAdmin() to verify the row, and I'm using a variable session in parameter.

AngularJS Function Call in my navbar

       Admin

Here I'm using ng-if to verify the return of my previous function.

I don't know where the problem is. Do you have any idea ?

EDIT :

Here is all the code I used :

AJS :
In my controller.js

$scope.droitsAdmin = function() { factoryDossier.verifierHabilitation(); };

In my factory.js

verifierHabilitation : function(){

    return $http({
        url: 'controleurs/Controleur-Admin.php'
        ,method: "POST"
        ,data: $.param({
            fonction : 'verifierHabilitation'
        })
        ,headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });
},

PHP:
Controller.php

function verifierHabilitation ( $req, $api ){
    if(droitsModificationAdmin( $_SESSION['nni'] ) == "administration") {
        echo "ceci est un test";
        return 1;
    }
}

Here I am calling the function which is in the global controller.

Global Controller

function droitsModificationAdmin( $nni ){
    $bdd = new Model_Habilitation( PDO_bdd_app() );
    $utilisateur = $bdd->habilitation( $nni );
    return ( $utilisateur[0]['h_habilitation'] );
}

Model.php

public function habilitation( $nni ){
        $sql = $this->grea_ouest->prepare('SELECT h_habilitation FROM '.$this->table_habilitation.' h WHERE h.h_nni = :nni');
        $sql->execute( array( ':nni' => $nni ) );
        return $sql->fetchAll(PDO::FETCH_ASSOC);
    }

Controleur-Configuration.php

(Sorry the code is in french)

<?php

require_once('Controleur-Configuration.php');
require_once('api_rest.php');
require_once(dirname(__FILE__).'/../class/ClassAdmin.php');
require_once(model_url('Model_Admin'));
require_once('Helpers.php');

#############################################################
gestion_session();//Gestion à partir du fichier configuration
#############################################################

$api = new Rest;

try {
    $req = $api->get_request();
    if( function_exists( $req['fonction'] ) ){ $req['fonction']( $req, $api ); } else { throw new Exception('Fonction inexistante'); }
} catch(Exception $e){
    $api->response(array(), 501);
}

/**
 * Retourne les informations d'un admin
 * @param $req array : les données passées en parametres
 * @param $api Rest : l'objet Rest permettant l'interaction avec le client.
 * @return array : les informations du dossier.
 */
function getAdmins( $req, $api ){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $Admins = $bdd->getAdmins();
        foreach($Admins as $key=>$Admin){ $Admins[$key] = $Admin->json_encode(); }
        $api->response( $Admins, 200);
    } catch(Exception $e){ error_log( $e ); $api->response( "", 500); }
}

/**
 * Retourne les habilitations
 * @param $req array : les données passées en parametres
 * @param $api Rest : l'objet Rest permettant l'interaction avec le client.
 * @return array : les informations du dossier.
 */
function getHabilitations( $req, $api ){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $Habilitations = $bdd->getHabilitations();
        foreach($Habilitations as $key=>$Habilitation){ $Habilitations[$key] = $Habilitation->json_encode(); }
        $api->response( $Habilitations, 200);
    } catch(Exception $e){ error_log( $e ); $api->response( "", 500); }
}

/**
* Met a jour un habilité
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function updateAdmin( $req, $api ){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try {
        if( isset($req['NewAdmin']) ){
            $admin = cast( $req['NewAdmin'], 'Admin' );
        } else { $api->response( array( "erreur" => array(array("Aucunes informations saisies"))), 409); }

            try
            {
                $bdd = new Model_Admin( PDO_bdd_app() );
                $newAdmin = $bdd->updateAdmin( $admin );
                $api->response( array( "dev"=>$newAdmin->json_encode(), "info"=>array("Le développeur a été modifié")), 200);
    } catch( Exception $e ){ error_log( $e ); $api->response( "", 500); }
    } catch( Exception $e ){ error_log( $e ); $api->response( "", 500); }
}

/**
* Change l'habilitation d'un utilisateur
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function changerHabilitation ($req, $api){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $habilitation = $bdd->changerHabilitation( $req['nni'], $req['habilitation'] );
    } catch(Exception $e){
        error_log( $e );
        $api->response( $e, 500);
    }
}

function verifierHabilitation ( $req, $api ){
    if(droitsModificationAdmin( $_SESSION['nni'] ) == "administration") {
        echo "ceci est un test";
        return 1;
    }
}

/**
* Approuve un utilisateur
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function approuverUtilisateur ($req, $api){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $utilisateur = $bdd->approuverUtilisateur( $req['nni'] );
    } catch(Exception $e){
        error_log( $e );
        $api->response( $e, 500);
    }
}

/**
* Refuse un utilisateur
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function refuserUtilisateur ($req, $api){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $utilisateur = $bdd->refuserUtilisateur( $req['nni'] );
    } catch(Exception $e){
        error_log( $e );
        $api->response( $e, 500);
    }
}

?>

Body:
Okay so as you need some permission module you can do something like this:
Create an Angularjs service to store all the permission values, so you don't have to hit your database again and again, store your permission values in this service at the time of login.
Use your code like this :

<div ng-if="permission == 'user'">
    Some content which you want to show to **USER** only.
</div>
<div ng-if="permission == 'user' || permission == 'admin'">
    Some content which you want to show to **USER and ADMIN** both.
</div>
<div ng-if="permission == 'admin'">
    Some content which you want to show to **ADMIN** only.
</div>

Looks like you are calling your PHP function from JAVASCRIPT.
You cannot do this.
You have to make an HTTP request (AJAX CALL) to perform this operation.
Let me know if you have any doubt.


问:
Is it possible to make a proper tail-call of hanoi tower in lua?
I made a code of tower of hanoi problem with recursion and run it on the online lua compiler. If I put the input over 14, it didn't run.

local num = io.read("*n")
local count = 0
function hanoi(n, st, mid, dst)
    if n == 1 then
        count = count + 1
        print(st, dst)
    else
        hanoi(n-1, st, dst, mid)
        count = count + 1
        print(st, dst)
        hanoi(n-1, mid, st, dst)
    end
end

hanoi(num, 1, 2, 3)
print(count)
```

<p>I think this can be solved by proper tail-call, but in my knowledge the proper tail call must return the same function. But in that code, there are two "hanoi" function in recursive.</p>

<hr>

<p>So is this a proper tail call in lua?</p>

```function f(args)
    return f(args_1), f(args_2)
end
```

And is there any way to make proper tail call of hanoi problem?

答:
The proper tail call is not about calling the same function. The call to any function would be a tail call if that call happens under required conditions, and it's not limited to recursions.

In your example:

```<code>function hanoi(n, st, mid, dst)
    if n == 1 then
        count = count + 1
        print(st, dst)
    else
        hanoi(n-1, st, dst, mid) -- you continue after this call,
                                 -- possibly expecting the result, this call
                                 -- can't be a proper tail call
        count = count + 1
        print(st, dst)

        hanoi(n-1, mid, st, dst) -- this call can be made a tail call,
                                 -- just return the result of that call

        return hanoi(n-1, mid, st, dst) -- now this is a proper tail call
    end
end
</code>```

The function must return the result of the call, it must not use or alter the result of the call.

In your hanoi example only the second call can be made a tail call, but not the first one.

Body:
I made a code of tower of hanoi problem with recursion and run it on the online lua compiler. If I put the input over 14, it didn't run.

local num = io.read("*n")
local count = 0
function hanoi(n, st, mid, dst)
    if n == 1 then
        count = count + 1
        print(st, dst)
    else
        hanoi(n-1, st, dst, mid)
        count = count + 1
        print(st, dst)
        hanoi(n-1, mid, st, dst)
    end
end

hanoi(num, 1, 2, 3)
print(count)

I think this can be solved by proper tail-call, but in my knowledge the proper tail call must return the same function. But in that code, there are two "hanoi" function in recursive.

So is this a proper tail call in lua?

function f(args)
    return f(args_1), f(args_2)
end

And is there any way to make proper tail call of hanoi problem?

Body:
The proper tail call is not about calling the same function. The call to any function would be a tail call if that call happens under required conditions, and it's not limited to recursions.

In your example:

function hanoi(n, st, mid, dst)
    if n == 1 then
        count = count + 1
        print(st, dst)
    else
        hanoi(n-1, st, dst, mid) -- you continue after this call,
                                 -- possibly expecting the result, this call
                                 -- can't be a proper tail call
        count = count + 1
        print(st, dst)

        hanoi(n-1, mid, st, dst) -- this call can be made a tail call,
                                 -- just return the result of that call

        return hanoi(n-1, mid, st, dst) -- now this is a proper tail call
    end
end

The function must return the result of the call, it must not use or alter the result of the call.

In your hanoi example only the second call can be made a tail call, but not the first one.


问:
WPF: How to interact with inactive window?
Is it possible to interact with an inactive window from another window? I want to focus a textbox in a window without making it active, and then send keystrokes and mouse events to it. It seem to be possible to send messages to inactive windows using SendMessage but could it be possible to also focus a textbox in the window and send keystrokes to it, without ever making the window active?</p>

答:
Have a look at the same question worded a little different here

Quote @Kevin Montrose: "Windows assumes that the activate window is the one getting keyboard input. The proper way to fake keyboard input is with SendInput, and you'll notice that it sends messages to the active window only."


问:
I use data transfer via bundle, but for some reason the data is transmitted only 1 time
I use this piece of code to send data

```<code> @Override
public void onClick(View v) {
    DialogFragment dlg;
    dlg = new barcodeView();
    Coupons coupons = coupons2.get(position);
    String i = coupons.getTAG();

    Log.v("dwdwdw",""+i);
    Bundle bundle = new Bundle();
    if (i.equals("lentaAmount500")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "5000112592702");

        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("lentaAmount300")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0000054490086");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("lentaAmount100")){
        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0000054491472");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("petiarochkaAmount500")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0000054492387");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("petiarochkaAmount300")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0049000065206");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("petiarochkaAmount100")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "050051000481");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
</code>```

And such for obtaining barcode_data = bundle.getString("someValue");

But why the first time all is well, the data is sent, but with the next click displays the old data, that is, the data sent does not change. How to clean them?
I checked Debug mode and realized that Coupons coupons = coupons 2.get(position); not changed. Why is this happening and how to fix it?

All Recycler Adapter from where I send data:

```<code>class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> implements View.OnClickListener {

private Context context;
private LayoutInflater inflater;
private List<Coupons> coupons2;
 RecyclerAdapter(Context context, List<Coupons> coupons2){

    this.coupons2 = coupons2;
    this.inflater = LayoutInflater.from(context);
    this.context = context;

}

@Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
    View view = inflater.inflate(R.layout.coupon,parent,false);

    return new ViewHolder(view);
}
 private int position;
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
    Coupons coupons = coupons2.get(position);
    this.position = position;

    viewHolder.imageView.setImageResource(coupons.getLogo());
    viewHolder.imageView.setOnClickListener(this);

}
Coupons coupons;

@Override
public int getItemCount(){
    return coupons2.size();
}

@Override
public void onClick(final View v) {
    DialogFragment dlg;
    dlg = new barcodeView();
    if (coupons!=null){
        coupons = null;
    }

    Coupons coupons = coupons2.get(position);

    String i = coupons.getTAG();

    Log.v("dwdwdw",""+i);
    Bundle bundle = new Bundle();
    if (i.equals("lentaAmount500")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "5000112592702");

        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("lentaAmount300")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0000054490086");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("lentaAmount100")){
        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0000054491472");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("petiarochkaAmount500")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0000054492387");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("petiarochkaAmount300")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0049000065206");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("petiarochkaAmount100")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "050051000481");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");

    }

}

static class ViewHolder extends RecyclerView.ViewHolder{
    final ImageView imageView;

    ViewHolder(View v){
        super(v);
        imageView = v.findViewById(R.id.logo);
    }
}
</code>```

All DialogFragment where I get data:

```<code> public class barcodeView extends DialogFragment implements
View.OnClickListener {

ImageView barcodeview;
TextView barcodetextView;
String barcode_data;
// barcode image
Bitmap bitmap = null;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    getDialog().setTitle("Ваш штрихкод");
    View v = inflater.inflate(R.layout.barcode_view, null);
    Bundle bundle = this.getArguments();
    barcode_data = bundle.getString("someValue");
    barcodetextView = v.findViewById(R.id.textViewbarcode);
    barcodeview =  v.findViewById(R.id.barcodeView);

    try {
        bitmap = encodeAsBitmap(barcode_data, BarcodeFormat.CODE_128, 600, 300);
        barcodeview.setImageBitmap(bitmap);
        barcodetextView.setText(barcode_data);
    } catch (WriterException e) {
        e.printStackTrace();
    }

    return v;

}
Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
    String contentsToEncode = contents;
    if (contentsToEncode == null) {
        return null;
    }
    Map<EncodeHintType, Object> hints = null;
    String encoding = guessAppropriateEncoding(contentsToEncode);
    if (encoding != null) {
        hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
        hints.put(EncodeHintType.CHARACTER_SET, encoding);
    }
    MultiFormatWriter writer = new MultiFormatWriter();
    BitMatrix result;
    try {
        result = writer.encode(contentsToEncode, format, img_width, img_height, hints);
    } catch (IllegalArgumentException iae) {
        // Unsupported format
        return null;
    }
    int width = result.getWidth();
    int height = result.getHeight();
    int[] pixels = new int[width * height];
    for (int y = 0; y < height; y++) {
        int offset = y * width;
        for (int x = 0; x < width; x++) {
            pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
        }
    }

    Bitmap bitmap = Bitmap.createBitmap(width, height,
            Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    return bitmap;
}

private static String guessAppropriateEncoding(CharSequence contents) {
    // Very crude at the moment
    for (int i = 0; i < contents.length(); i++) {
        if (contents.charAt(i) > 0xFF) {
            return "UTF-8";
        }
    }
    return null;
}

public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);
   barcodeview = null;
   barcodetextView = null;
   barcode_data = null;
   Log.v("dwdw","wdwdwd");

}

@Override
public void onClick(View v) {
    dismiss();

}
</code>```

答:
It's not good to use private int position; to get position in onClick

Let try to implement OnClickListener follows below code:

```<code>@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int position) {
    final Coupons coupons = coupons2.get(position);

    viewHolder.imageView.setImageResource(coupons.getLogo());
    viewHolder.imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //TODO: you can use 'coupons' and 'position' declared as final here
            String i = coupons.getTAG();
        }
    });
}
</code>```

Body:
I use this piece of code to send data

 @Override
public void onClick(View v) {
    DialogFragment dlg;
    dlg = new barcodeView();
    Coupons coupons = coupons2.get(position);
    String i = coupons.getTAG();

    Log.v("dwdwdw",""+i);
    Bundle bundle = new Bundle();
    if (i.equals("lentaAmount500")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "5000112592702");

        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("lentaAmount300")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0000054490086");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("lentaAmount100")){
        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0000054491472");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("petiarochkaAmount500")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0000054492387");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("petiarochkaAmount300")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0049000065206");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("petiarochkaAmount100")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "050051000481");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }

And such for obtaining barcode_data = bundle.getString("someValue");

But why the first time all is well, the data is sent, but with the next click displays the old data, that is, the data sent does not change. How to clean them?
I checked Debug mode and realized that Coupons coupons = coupons 2.get(position); not changed. Why is this happening and how to fix it?

All Recycler Adapter from where I send data:

class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> implements View.OnClickListener {

private Context context;
private LayoutInflater inflater;
private List<Coupons> coupons2;
 RecyclerAdapter(Context context, List<Coupons> coupons2){

    this.coupons2 = coupons2;
    this.inflater = LayoutInflater.from(context);
    this.context = context;

}

@Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
    View view = inflater.inflate(R.layout.coupon,parent,false);

    return new ViewHolder(view);
}
 private int position;
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
    Coupons coupons = coupons2.get(position);
    this.position = position;

    viewHolder.imageView.setImageResource(coupons.getLogo());
    viewHolder.imageView.setOnClickListener(this);

}
Coupons coupons;

@Override
public int getItemCount(){
    return coupons2.size();
}

@Override
public void onClick(final View v) {
    DialogFragment dlg;
    dlg = new barcodeView();
    if (coupons!=null){
        coupons = null;
    }

    Coupons coupons = coupons2.get(position);

    String i = coupons.getTAG();

    Log.v("dwdwdw",""+i);
    Bundle bundle = new Bundle();
    if (i.equals("lentaAmount500")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "5000112592702");

        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("lentaAmount300")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0000054490086");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("lentaAmount100")){
        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0000054491472");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("petiarochkaAmount500")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0000054492387");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("petiarochkaAmount300")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "0049000065206");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");
    }
    if (i.equals("petiarochkaAmount100")){

        FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        bundle.clear();
        bundle.putString("someValue", "050051000481");
        dlg.setArguments(bundle);
        dlg.show(fragmentManager,"barcodeview");

    }

}

static class ViewHolder extends RecyclerView.ViewHolder{
    final ImageView imageView;

    ViewHolder(View v){
        super(v);
        imageView = v.findViewById(R.id.logo);
    }
}

All DialogFragment where I get data:

 public class barcodeView extends DialogFragment implements
View.OnClickListener {

ImageView barcodeview;
TextView barcodetextView;
String barcode_data;
// barcode image
Bitmap bitmap = null;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    getDialog().setTitle("Ваш штрихкод");
    View v = inflater.inflate(R.layout.barcode_view, null);
    Bundle bundle = this.getArguments();
    barcode_data = bundle.getString("someValue");
    barcodetextView = v.findViewById(R.id.textViewbarcode);
    barcodeview =  v.findViewById(R.id.barcodeView);

    try {
        bitmap = encodeAsBitmap(barcode_data, BarcodeFormat.CODE_128, 600, 300);
        barcodeview.setImageBitmap(bitmap);
        barcodetextView.setText(barcode_data);
    } catch (WriterException e) {
        e.printStackTrace();
    }

    return v;

}
Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
    String contentsToEncode = contents;
    if (contentsToEncode == null) {
        return null;
    }
    Map<EncodeHintType, Object> hints = null;
    String encoding = guessAppropriateEncoding(contentsToEncode);
    if (encoding != null) {
        hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
        hints.put(EncodeHintType.CHARACTER_SET, encoding);
    }
    MultiFormatWriter writer = new MultiFormatWriter();
    BitMatrix result;
    try {
        result = writer.encode(contentsToEncode, format, img_width, img_height, hints);
    } catch (IllegalArgumentException iae) {
        // Unsupported format
        return null;
    }
    int width = result.getWidth();
    int height = result.getHeight();
    int[] pixels = new int[width * height];
    for (int y = 0; y < height; y++) {
        int offset = y * width;
        for (int x = 0; x < width; x++) {
            pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
        }
    }

    Bitmap bitmap = Bitmap.createBitmap(width, height,
            Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    return bitmap;
}

private static String guessAppropriateEncoding(CharSequence contents) {
    // Very crude at the moment
    for (int i = 0; i < contents.length(); i++) {
        if (contents.charAt(i) > 0xFF) {
            return "UTF-8";
        }
    }
    return null;
}

public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);
   barcodeview = null;
   barcodetextView = null;
   barcode_data = null;
   Log.v("dwdw","wdwdwd");

}

@Override
public void onClick(View v) {
    dismiss();

}

Body:
It's not good to use private int position; to get position in onClick

Let try to implement OnClickListener follows below code:

@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int position) {
    final Coupons coupons = coupons2.get(position);

    viewHolder.imageView.setImageResource(coupons.getLogo());
    viewHolder.imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //TODO: you can use 'coupons' and 'position' declared as final here
            String i = coupons.getTAG();
        }
    });
}


问:
How to handle an error in DataPower policy rule when receiving specific error code
I have a rule in a policy, and I want to handle an error message. For example if I receive error code "0x80e003aa", stop the rule and write an input "code13" (some error code).I know there is "On Error Action", but something is not working. Any ideas?</p>

答:
You will need to make sure you catch the first error in the Rule. Set your debug logging on and produce the error. In the log you will (most likely) see a number of errors and then copy the error code of the first of them.

Create a new Match rule in your Processing Policy and set it to match on Error Code. In the selection list where you can chose error codes find the code you copied and add it. If you can't find the code in the list it is not a "main" error which can be catched and you will have to add another of the error codes.
If you are unsure, just add all of the codes into your Match Action (you can have multiple).

Next make sure that your rule is an "error rule" and that no other error rule is placed before it (higher up in the rules list). DataPower only executes ONE error rule so you need to be sure they come in order.

Another solution is to add a new Error rule with a "match all" (*) Match action and in it use GatewayScript or XSLT to check the code and take the appropriate action, e.g. for GWS:

// get the service metadata, i.e. the service var's
var sm = require ('service-metadata');

console.log(JSON.stringify(sm));
console.log(JSON.stringify(sm).slice(1566));
console.log(sm.errorSubcode);

if (sm.errorSubcode === '0x01d30003') {
  // This is a XSD schema validation error
  const err = sm.errorMessage.slice(sm.errorMessage.indexOf('/validate: ') + 10).trim();
  session.output.write(err);
} else {
  session.output.write(sm.errorMessage);
}```


问:
Wordpress - Form options.php - How to not overwrite a setting if it didn't found the name attribute for this setting
I'm currently working on a plugin wordpress.

I have a form with inside some inputs tags except one (for this one, I use ajax and update_option, so we don't need to submit this form to update this setting).
When I submit this form, options.php didn't found a name for a setting, so it overwrites this setting with an empty value.

I would like to know how I can avoid this ? I would like to avoid to do a hidden input, because this plugin is not finish at all, I don't want to have 50 hidden inputs at the end... I want it to keep the values if it doesn't found a name for the setting.

EDIT : One of the solution I found is to have differents forms and differents option group for the register_setting. I have 4 forms, so I have 4 options groups, that works, I wanted something better, but it's ok !

答:
For the update value you need to use:

```<code><?php update_option( 'my_custom_option', get_the_ID() ); ?>
</code>```

NOTE: Please add the ID for the update.

You need to check this option values into wordpress wp_options table.
All the option data will be save into wp_options.

Get the option value by this function:

```<code>$my_custom_option = get_option( 'my_custom_option' );
var_dump( $my_custom_option );
</code>```

OR

```<code>$my_custom_option = get_option( 'my_custom_option', get_the_ID() );
    var_dump( $my_custom_option );
</code>```

Body:
For the update value you need to use:

<?php update_option( 'my_custom_option', get_the_ID() ); ?>

NOTE: Please add the ID for the update.

You need to check this option values into wordpress wp_options table.
All the option data will be save into wp_options.

Get the option value by this function:

$my_custom_option = get_option( 'my_custom_option' );
var_dump( $my_custom_option );

OR

$my_custom_option = get_option( 'my_custom_option', get_the_ID() );
    var_dump( $my_custom_option );