问:
dyld: Library not loaded - sqlplus installation
I want to install sqlplus on my Mac. So, first I downloaded  two files from this link
https://www.oracle.com/technetwork/topics/intel-macsoft-096467.html these two file:

instantclient-basic-macos.x64-18.1.0.0.0.zip

instantclient-sqlplus-macos.x64-18.1.0.0.0.zip

Then, I moved these files.zip on my desktop and from my terminal
I wrote these commands:

```<code>unzip /Users/nietmochi/Desktop/instantclient-basic-macos.x64-18.1.0.0.0.zip
</code>```

and

```<code>unzip /Users/nietmochi/Desktop/instantclient-sqlplus-macos.x64-18.1.0.0.0.zip
</code>```

and then:

```<code>export PATH=/Users/nietmochi/Desktop/instantclient_18_1:$PATH
</code>```

and:

```<code>which sqlplus
</code>```

Now, when I try to launch sqlplus with the command sqlplus, I have this message:

```<code>dyld: Library not loaded: @rpath/libclntsh.dylib.18.1
  Referenced from: /Users/nietmochi/Desktop/instantclient_18_1/sqlplus
  Reason: image not found
Abort trap: 6
</code>```

Why? How to fix it?

Thanks a lot!

答:
The error suggests that your ~/Desktop/instantclient_18_1 directory only has the contents of the instantclient-sqlplus-macos.x64-18.1.0.0.0.zip file. I suspect you've tried this several times from various locations, and you've ended up with a mix of partial and full installations, and you're happening to pick up a partial one.

When you do:

```<code>unzip /Users/nietmochi/Desktop/instantclient-basic-macos.x64-18.1.0.0.0.zip
unzip /Users/nietmochi/Desktop/instantclient-sqlplus-macos.x64-18.1.0.0.0.zip
</code>```

then both zip archives should be expanded into the same instantclient_18_1 directory, which will be in your current working directory. If you didn't change to ~/Desktop before running then that could be anywhere...

I'd suggest you start again. Find and remove any directories called instantclient_18_1, from your home directory, ~/Desktop, ~/Downloads etc., anywhere you can find them; mostly just to avoid confusion.

Then, since your zip files are currently on the desktop, for simplicity for now do:

```<code>cd ~/Desktop
unzip instantclient-basic-macos.x64-18.1.0.0.0.zip
ls instantclient_18_1 | wc -l
unzip instantclient-sqlplus-macos.x64-18.1.0.0.0.zip
ls instantclient_18_1 | wc -l
</code>```

The first ls should give you a count of 18 files. The second should give you a count of 23 files.

Once you have done that then sqlplus should work, using the PATH you've already modified.

You can put that instantclient_18_1 directory anywhere you want, as long as your PATH refers to it, and you can add setting your path to your ~/.bash_profile file so you don't have to do that manually in future.

Body:
I want to install sqlplus on my Mac. So, first I downloaded  two files from this link
https://www.oracle.com/technetwork/topics/intel-macsoft-096467.html these two file:

instantclient-basic-macos.x64-18.1.0.0.0.zip

instantclient-sqlplus-macos.x64-18.1.0.0.0.zip

Then, I moved these files.zip on my desktop and from my terminal
I wrote these commands:

unzip /Users/nietmochi/Desktop/instantclient-basic-macos.x64-18.1.0.0.0.zip

and

unzip /Users/nietmochi/Desktop/instantclient-sqlplus-macos.x64-18.1.0.0.0.zip

and then:

export PATH=/Users/nietmochi/Desktop/instantclient_18_1:$PATH

and:

which sqlplus

Now, when I try to launch sqlplus with the command sqlplus, I have this message:

dyld: Library not loaded: @rpath/libclntsh.dylib.18.1
  Referenced from: /Users/nietmochi/Desktop/instantclient_18_1/sqlplus
  Reason: image not found
Abort trap: 6

Why? How to fix it?

Thanks a lot!

Body:
The error suggests that your ~/Desktop/instantclient_18_1 directory only has the contents of the instantclient-sqlplus-macos.x64-18.1.0.0.0.zip file. I suspect you've tried this several times from various locations, and you've ended up with a mix of partial and full installations, and you're happening to pick up a partial one.

When you do:

unzip /Users/nietmochi/Desktop/instantclient-basic-macos.x64-18.1.0.0.0.zip
unzip /Users/nietmochi/Desktop/instantclient-sqlplus-macos.x64-18.1.0.0.0.zip

then both zip archives should be expanded into the same instantclient_18_1 directory, which will be in your current working directory. If you didn't change to ~/Desktop before running then that could be anywhere...

I'd suggest you start again. Find and remove any directories called instantclient_18_1, from your home directory, ~/Desktop, ~/Downloads etc., anywhere you can find them; mostly just to avoid confusion.

Then, since your zip files are currently on the desktop, for simplicity for now do:

cd ~/Desktop
unzip instantclient-basic-macos.x64-18.1.0.0.0.zip
ls instantclient_18_1 | wc -l
unzip instantclient-sqlplus-macos.x64-18.1.0.0.0.zip
ls instantclient_18_1 | wc -l

The first ls should give you a count of 18 files. The second should give you a count of 23 files.

Once you have done that then sqlplus should work, using the PATH you've already modified.

You can put that instantclient_18_1 directory anywhere you want, as long as your PATH refers to it, and you can add setting your path to your ~/.bash_profile file so you don't have to do that manually in future.


来源: stackexchange

问:
Using a Cursor in a Stored Procudure
I have the following code extremely slow code in a MS SQL 2016 Stored Procedure (I think it is stuck in a never ending loop):

```<code>@DBID Integer
AS
BEGIN

DECLARE TagCursor CURSOR FOR SELECT MemberID
FROM           ADMIN_API_Master_Members_List
WHERE DBID= @DBID AND Len(Pending) > 0

DECLARE @ProgramCode VARCHAR(10)
DECLARE @Values VARCHAR(MAX)
DECLARE @tag nvarchar(10)

  OPEN TagCursor

      FETCH NEXT FROM TagCursor INTO @tag
      WHILE (@@FETCH_STATUS = 0)
      BEGIN

     SELECT @ProgramCode = Program_Code, @Values= Pending FROM  ADMIN_API_Master_Members_List WHERE MemberID= @tag

     DELETE FROM ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE
     WHERE  (MemberID =@tag)

     INSERT INTO ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE ( ProgramCode, MemberID, DBID, PMID)
     SELECT    @ProgramCode, @tag, @DBID ,  Value FROM STRING_SPLIT(@Values, ',')
     END

      CLOSE TagCursor
      DEALLOCATE TagCursor
END
</code>```

This Procedure is only a maintenance process and does not get run very often but when it does it would be nice to only take a few seconds.  The purpose is to normalize in a Table one record for each comma seperated value in the ADMIN_API_Master_Members_List Table and put it into the ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE with the Program_Code and MemberID and DBID.

There are only about 150 records in the Master Table and the comma separated strings may have 5 values.  I am receptive to other solutions.

Thanks in advance

答:
I haven't tested this, but like I mentioned in the comments, using a CURSOR is a bad idea; they are inherently slow as SQL Server excels at set based methods not iterative tasks (and a CURSOR is the latter).

I suspect that this achieves the answer you're after and avoids the CURSOR all together:

```<code>CREATE PROC YourProc @DBID integer
AS
BEGIN

    DECLARE @Deleted table (ProgramCode varchar(10),
                            [Value] varchar(MAX),
                            Tag nvarchar(10));

    DELETE HT
    OUTPUT deleted.Program_Code,
           deleted.Pending,
           deleted.MemberID
    INTO @Deleted (ProgramCode,
                   [Value],
                   Tag)
    FROM ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE AS HT
         JOIN ADMIN_API_Master_Members_List AS MML ON HT.MemberID = MML.MemberID
    WHERE MML.[DBID] = @DBID
      --AND LEN(Pending) > 0; --Changed this to below to be SARGable, as only a string with the value '' will have a length of 0.
      AND Pending != '';

    INSERT INTO ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE (ProgramCode,
                                                           MemberID,
                                                           DBID,
                                                           PMID)
    SELECT D.ProgramCode,
           D.Tag,
           @DBID,
           SS.Value
    FROM @Deleted AS D
         CROSS APPLY STRING_SPLIT(D.[Value], ',') AS SS;

END;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Using a Cursor in a Stored Procudure

Body:
I have the following code extremely slow code in a MS SQL 2016 Stored Procedure (I think it is stuck in a never ending loop):

@DBID Integer
AS
BEGIN

DECLARE TagCursor CURSOR FOR SELECT MemberID
FROM           ADMIN_API_Master_Members_List
WHERE DBID= @DBID AND Len(Pending) > 0

DECLARE @ProgramCode VARCHAR(10)
DECLARE @Values VARCHAR(MAX)
DECLARE @tag nvarchar(10)

  OPEN TagCursor

      FETCH NEXT FROM TagCursor INTO @tag
      WHILE (@@FETCH_STATUS = 0)
      BEGIN

     SELECT @ProgramCode = Program_Code, @Values= Pending FROM  ADMIN_API_Master_Members_List WHERE MemberID= @tag

     DELETE FROM ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE
     WHERE  (MemberID =@tag)

     INSERT INTO ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE ( ProgramCode, MemberID, DBID, PMID)
     SELECT    @ProgramCode, @tag, @DBID ,  Value FROM STRING_SPLIT(@Values, ',')
     END

      CLOSE TagCursor
      DEALLOCATE TagCursor
END

This Procedure is only a maintenance process and does not get run very often but when it does it would be nice to only take a few seconds.  The purpose is to normalize in a Table one record for each comma seperated value in the ADMIN_API_Master_Members_List Table and put it into the ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE with the Program_Code and MemberID and DBID.

There are only about 150 records in the Master Table and the comma separated strings may have 5 values.  I am receptive to other solutions.

Thanks in advance

Body:
I haven't tested this, but like I mentioned in the comments, using a CURSOR is a bad idea; they are inherently slow as SQL Server excels at set based methods not iterative tasks (and a CURSOR is the latter).

I suspect that this achieves the answer you're after and avoids the CURSOR all together:

CREATE PROC YourProc @DBID integer
AS
BEGIN

    DECLARE @Deleted table (ProgramCode varchar(10),
                            [Value] varchar(MAX),
                            Tag nvarchar(10));

    DELETE HT
    OUTPUT deleted.Program_Code,
           deleted.Pending,
           deleted.MemberID
    INTO @Deleted (ProgramCode,
                   [Value],
                   Tag)
    FROM ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE AS HT
         JOIN ADMIN_API_Master_Members_List AS MML ON HT.MemberID = MML.MemberID
    WHERE MML.[DBID] = @DBID
      --AND LEN(Pending) > 0; --Changed this to below to be SARGable, as only a string with the value '' will have a length of 0.
      AND Pending != '';

    INSERT INTO ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE (ProgramCode,
                                                           MemberID,
                                                           DBID,
                                                           PMID)
    SELECT D.ProgramCode,
           D.Tag,
           @DBID,
           SS.Value
    FROM @Deleted AS D
         CROSS APPLY STRING_SPLIT(D.[Value], ',') AS SS;

END;


问:
type or namespace could not be found
hello i am doing windows 7 mobile application on Framework 4.
while creating object for class IPEndPoint giving error that type or namespace could not be found.please help me..</p>

答:
do you have

```<code>using System.Net;
</code>```

in the top of the class that uses IPEndPoint?

ContentLicense: CC BY-SA 3.0

Title: type or namespace could not be found

Body:
do you have

using System.Net;

in the top of the class that uses IPEndPoint?


问:
Laravel returning server error 500 on CentOS 7
As the title says, I have a VPS running on CentOS 7, I installed all the requisites for Laravel, PHP 7.3, but it still giving me 'Server Error 500'.

Note that this is a fresh installation of Laravel with composer.

My CentOS version is CentOS Linux release 7.2.1511 (Core)

PHP version is PHP 7.3.6 (cli)

I manually installed all the necessary modules from PHP

What I have already tried

I already did quite a lot of research:

Laravel giving 500 internal error on centos 7 with apache and php 7

I followed what the answer to that questions says and still the same for me.

I did also set up permissions correctly following this other post:

How to set up File Permissions for Laravel 5 (and others)

Also these ones

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

https://www.ionos.com/community/server-cloud-infrastructure/apache/how-to-fix-http-error-code-500-internal-server-error/

And a bunch of more articles I read on another websites.

These are the permissions for the project folder:

drwxr-xr-x 13 apache apache 4096 May 31 05:23 laravel

And for storage:

drwxr-xr-x  5 apache apache   4096 May 31 04:44 storage

Tried generating the key and got this:

```<code>[root@server laravel]# php artisan key:generate

   ErrorException  : file_get_contents(/var/www/laravel/.env): failed to open stream: No such file or directory

  at /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:96
     92|     {
     93|         file_put_contents($this->laravel->environmentFilePath(), preg_replace(
     94|             $this->keyReplacementPattern(),
     95|             'APP_KEY='.$key,
  >  96|             file_get_contents($this->laravel->environmentFilePath())
     97|         ));
     98|     }
     99|
    100|     /**

  Exception trace:

  1   file_get_contents("/var/www/laravel/.env")
      /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:96

  2   Illuminate\Foundation\Console\KeyGenerateCommand::writeNewEnvironmentFileWith("base64:soTdeaCmsY1ELnpJLCcYkBJjY6SWiLYwY+Mvoxl9wOw=")
      /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:80

  Please use the argument -v to see more details.
[root@server laravel]#

</code>```

答:
So, I fixed it configuring properly the .env and generating a key as @mdexp mentioned.
So for everyone having problems, check the links in my question and set everything correctly

Body:
As the title says, I have a VPS running on CentOS 7, I installed all the requisites for Laravel, PHP 7.3, but it still giving me 'Server Error 500'.

Note that this is a fresh installation of Laravel with composer.

My CentOS version is CentOS Linux release 7.2.1511 (Core)

PHP version is PHP 7.3.6 (cli)

I manually installed all the necessary modules from PHP

What I have already tried

I already did quite a lot of research:

Laravel giving 500 internal error on centos 7 with apache and php 7

I followed what the answer to that questions says and still the same for me.

I did also set up permissions correctly following this other post:

How to set up File Permissions for Laravel 5 (and others)

Also these ones

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

https://www.ionos.com/community/server-cloud-infrastructure/apache/how-to-fix-http-error-code-500-internal-server-error/

And a bunch of more articles I read on another websites.

These are the permissions for the project folder:

drwxr-xr-x 13 apache apache 4096 May 31 05:23 laravel

And for storage:

drwxr-xr-x  5 apache apache   4096 May 31 04:44 storage

Tried generating the key and got this:

[root@server laravel]# php artisan key:generate

   ErrorException  : file_get_contents(/var/www/laravel/.env): failed to open stream: No such file or directory

  at /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:96
     92|     {
     93|         file_put_contents($this->laravel->environmentFilePath(), preg_replace(
     94|             $this->keyReplacementPattern(),
     95|             'APP_KEY='.$key,
  >  96|             file_get_contents($this->laravel->environmentFilePath())
     97|         ));
     98|     }
     99|
    100|     /**

  Exception trace:

  1   file_get_contents("/var/www/laravel/.env")
      /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:96

  2   Illuminate\Foundation\Console\KeyGenerateCommand::writeNewEnvironmentFileWith("base64:soTdeaCmsY1ELnpJLCcYkBJjY6SWiLYwY+Mvoxl9wOw=")
      /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:80

  Please use the argument -v to see more details.
[root@server laravel]#


问:
unmarshal json field is int or string
I have an app where the type is

```<code>type Person struct {
  Name string `json:"name"`
  Age  int    `json:"age"`
}
</code>```

But we have legacy clients that send the Age field as either a string or an integer, so...

```<code>{
  "name": "Joe",
  "age": "42"
}
</code>```

OR

```<code>{
  "name": "Joe",
  "age": 42
}
</code>```

I know I can annotate the "age" field with ",string" if it's a string that I want coerced into an integer, but what if the field could be either one?

答:
Check out "json - raw Message" in the docs, from there on out you can try to parse it however you want. Example below and on GoPlayground</p>

```<code>package main

import (
    "encoding/json"
    "fmt"
    "log"
    "strconv"
    "unicode/utf8"
)

type Person struct {
    Name string          `json:"name"`
    Age  json.RawMessage `json:"age"`
}

func main() {
    var j = []byte(`{"name": "Joe","age": "42"}`)
    var j2 = []byte(`{"name": "Joe","age": 42}`)
    stringOrInt(j)
    stringOrInt(j2)
}

func stringOrInt(bytes []byte) {
    var p Person
    err := json.Unmarshal(bytes, &p)
    if err != nil {
        log.Fatal(err)
    }

    if utf8.Valid(p.Age) {
        i, err := strconv.Atoi(string(p.Age))
        if err != nil {
            fmt.Println("got int " + strconv.Itoa(i))
        } else {
            fmt.Println("got string")
        }
    } else {
        fmt.Println("whoops")
    }
}

</code>```

Title: unmarshal json field is int or string

Body:
I have an app where the type is

type Person struct {
  Name string `json:"name"`
  Age  int    `json:"age"`
}

But we have legacy clients that send the Age field as either a string or an integer, so...

{
  "name": "Joe",
  "age": "42"
}

OR

{
  "name": "Joe",
  "age": 42
}

I know I can annotate the "age" field with ",string" if it's a string that I want coerced into an integer, but what if the field could be either one?

Body:
Check out "json - raw Message" in the docs, from there on out you can try to parse it however you want. Example below and on GoPlayground

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "strconv"
    "unicode/utf8"
)

type Person struct {
    Name string          `json:"name"`
    Age  json.RawMessage `json:"age"`
}

func main() {
    var j = []byte(`{"name": "Joe","age": "42"}`)
    var j2 = []byte(`{"name": "Joe","age": 42}`)
    stringOrInt(j)
    stringOrInt(j2)
}

func stringOrInt(bytes []byte) {
    var p Person
    err := json.Unmarshal(bytes, &p)
    if err != nil {
        log.Fatal(err)
    }

    if utf8.Valid(p.Age) {
        i, err := strconv.Atoi(string(p.Age))
        if err != nil {
            fmt.Println("got int " + strconv.Itoa(i))
        } else {
            fmt.Println("got string")
        }
    } else {
        fmt.Println("whoops")
    }
}


问:
Is there a way to access entity value metadata in Watson Assistant using the JSON editor or SPEL
I'm attempting to define some relationships between entity values, using metadata.

I've uploaded metadata to an entity value using the Watson API v1. When I list the entities through the same API I can see the metadata. I have not been able to access the metadata from Watson Assistant though.

As a test I changed the entity value and checked through Watson Assistant it was changed, so I know I'm working with the correct workspace. I've also checked the entity using the JSON editor to verify it was defined and tried assigning the entity to a context variable.

I've tried several methods including:
@Room.building, @Room.metadata.building, entities['Room']?metadata?.building, entities['Room']?.building (all within  the < ? tags). Using @Room and entities['Room']?.value returns the entity value correctly. It's accessing the metadata where it fails.

The metadata for building should not be returning null, but I"m either receiving a null or, depending on how I'm attempting to retrieve the value, a SPEL exception - no property on undefined.

答: Unfortunately, it is not possible to access metadata defined on user entities in the WA runtime at this moment. The metadata are only returned when making the direct API call. You could use cloud functions call though to get the metadata in WA although that is not ideal either.


问:
Constraint Layout not wrap content properly
Anyone know why this isn't wrapping content properly? Something to do with the gradient and the way the label_view is constrained is causing it to match parent somehow?

thanks

https://pastebin.com/R85CBFPL

```<code>
    <ImageView
            android:id="@+id/gradient"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="@drawable/hero_gradient"
            app:layout_constraintTop_toTopOf="@id/gradient_guide"
            app:layout_constraintBottom_toBottomOf="@id/image_view"
            android:contentDescription="@null"/>

    <androidx.constraintlayout.widget.Guideline
            android:id="@+id/left_margin"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:orientation="vertical"
            app:layout_constraintGuide_begin="8dp"/>

    <androidx.constraintlayout.widget.Guideline
            android:id="@+id/right_margin"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:orientation="vertical"
            app:layout_constraintGuide_end="8dp"/>

    <TextView
            android:layout_marginTop="50dp"
            android:id="@+id/label_view"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:textSize="12sp"
            android:gravity="center"
            tools:text="TEST TEXT"
            android:textColor="@color/pink"
            app:layout_constraintTop_toBottomOf="@id/gradient"
            app:layout_constraintBottom_toTopOf="@+id/gradient"
            app:layout_constraintStart_toStartOf="@id/left_margin"
            app:layout_constraintEnd_toEndOf="@id/right_margin"
            android:paddingBottom="4dp"/>
</code>```

Thats just a snippet of the offending parties.

答:
I must really be having a slow day. I was backwardly setting the centre.

I was doing

```<code>app:layout_constraintTop_toBottomOf="@id/gradient"
app:layout_constraintBottom_toTopOf="@+id/gradient"
</code>```

But I should be doing

```<code>app:layout_constraintTop_toTopOf="@id/gradient"
app:layout_constraintBottom_toBottomOf="@id/gradient"
</code>```

Body:
Anyone know why this isn't wrapping content properly? Something to do with the gradient and the way the label_view is constrained is causing it to match parent somehow?

thanks

https://pastebin.com/R85CBFPL

    <ImageView
            android:id="@+id/gradient"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="@drawable/hero_gradient"
            app:layout_constraintTop_toTopOf="@id/gradient_guide"
            app:layout_constraintBottom_toBottomOf="@id/image_view"
            android:contentDescription="@null"/>

    <androidx.constraintlayout.widget.Guideline
            android:id="@+id/left_margin"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:orientation="vertical"
            app:layout_constraintGuide_begin="8dp"/>

    <androidx.constraintlayout.widget.Guideline
            android:id="@+id/right_margin"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:orientation="vertical"
            app:layout_constraintGuide_end="8dp"/>

    <TextView
            android:layout_marginTop="50dp"
            android:id="@+id/label_view"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:textSize="12sp"
            android:gravity="center"
            tools:text="TEST TEXT"
            android:textColor="@color/pink"
            app:layout_constraintTop_toBottomOf="@id/gradient"
            app:layout_constraintBottom_toTopOf="@+id/gradient"
            app:layout_constraintStart_toStartOf="@id/left_margin"
            app:layout_constraintEnd_toEndOf="@id/right_margin"
            android:paddingBottom="4dp"/>

Thats just a snippet of the offending parties.

Body:
I must really be having a slow day. I was backwardly setting the centre.

I was doing

app:layout_constraintTop_toBottomOf="@id/gradient"
app:layout_constraintBottom_toTopOf="@+id/gradient"

But I should be doing

app:layout_constraintTop_toTopOf="@id/gradient"
app:layout_constraintBottom_toBottomOf="@id/gradient"


问:
UnhandledPromiseRejectionWarning when adding a new record to DB
I am trying to add new records to my MongoDB database. The records come in the form of an array, and then, for each record, I add it as a new item to MongoDB.
The problem is that every time I try to add some records (30-50 records) I get this message:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()

followed by this one:

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

This is the snippet I use for adding records:

```<code>// update the blacklist with a new entry
router.post("/updateBlacklist", async (req, res) => {
  req.body.product_id.forEach(async element => {
    const blacklistItem = new Blacklist({ product_id: element });
    try {
      const savedItem = await blacklistItem.save();
      res.json(savedItem);
    } catch (err) {
      console.log(err);
      res.json({ message: err });
    }
  });
});
</code>```

The same warning appears also when I try to download some photos using this function:

```<code>router.post("/product_ids", async (req, res) => {
  await downloadPhotos(req.body.items_id);
});
</code>```

the function I call inside this route:

```<code>const axios = require("axios");
const download = require("./utils/download");

const downloadPhotos = async itemsIDs => {
  try {
    console.log(itemsIDs.length);
    await itemsIDs.forEach(ID => {
      axios
        .get(
          `https://${process.env.SHOPIFY_API_KEY}:${
            process.env.SHOPIFY_PASSWORD
          }@blablabla.myshopify.com/admin/products/${ID}/images.json?fields=id, src`
        )
        .then((req, res) => {
          console.log(req.data.images[0].src);
          download(req.data.images[0].src, req.data.images[0].id, 3000);
        });
    });
  } catch (err) {
    console.log(err);
  }
};
</code>```

and the download function:

```<code>const Fs = require("fs");
const Path = require("path");
const Axios = require("axios");

async function downloadImage(url, filename, timeout) {
  const appDir = Path.dirname(require.main.filename);
  const path = Path.resolve(appDir, "images", `${filename}.jpg`);

  const writer = Fs.createWriteStream(path);

  const response = await Axios({
    url,
    method: "GET",
    responseType: "stream",
    timeout: timeout
  });

  response.data.pipe(writer);

  return new Promise((resolve, reject) => {
    writer.on("finish", resolve);
    writer.on("error", reject);
  });
}

module.exports = downloadImage;
</code>```

What am I doing wrong in this approach?

答:
This error:

```<code>UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
</code>```

It's because of these lines:

```<code>res.json(savedItem);
res.json({ message: err });
</code>```

You're running these lines several times, because they are inside the loop, you can't respond a request more than once because the connection it's closed after the first call.

Try with this:

```<code>router.post("/updateBlacklist", async (req, res) => {
  const savedList = [];
  req.body.product_id.forEach(async element => {
    const blacklistItem = new Blacklist({ product_id: element });
    try {
      const savedItem = await blacklistItem.save();
      savedList.push(savedItem)
    } catch (err) {
      console.log(err);
      savedList.push({ message: err });
    }
  });
  res.json(savedItem);
});
</code>```

UPDATE (suggestion):

```<code>router.post("/updateBlacklist", async (req, res) => {
  const items = req.body.product_id.map(element =>
     new Blacklist({ product_id: element })
  });
  const result = await Blacklist.insertMany(items); // not sure about the syntax
  res.json(result);
});
</code>```

Body:
I am trying to add new records to my MongoDB database. The records come in the form of an array, and then, for each record, I add it as a new item to MongoDB.
The problem is that every time I try to add some records (30-50 records) I get this message:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()

followed by this one:

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

This is the snippet I use for adding records:

// update the blacklist with a new entry
router.post("/updateBlacklist", async (req, res) => {
  req.body.product_id.forEach(async element => {
    const blacklistItem = new Blacklist({ product_id: element });
    try {
      const savedItem = await blacklistItem.save();
      res.json(savedItem);
    } catch (err) {
      console.log(err);
      res.json({ message: err });
    }
  });
});

The same warning appears also when I try to download some photos using this function:

router.post("/product_ids", async (req, res) => {
  await downloadPhotos(req.body.items_id);
});

the function I call inside this route:

const axios = require("axios");
const download = require("./utils/download");

const downloadPhotos = async itemsIDs => {
  try {
    console.log(itemsIDs.length);
    await itemsIDs.forEach(ID => {
      axios
        .get(
          `https://${process.env.SHOPIFY_API_KEY}:${
            process.env.SHOPIFY_PASSWORD
          }@blablabla.myshopify.com/admin/products/${ID}/images.json?fields=id, src`
        )
        .then((req, res) => {
          console.log(req.data.images[0].src);
          download(req.data.images[0].src, req.data.images[0].id, 3000);
        });
    });
  } catch (err) {
    console.log(err);
  }
};

and the download function:

const Fs = require("fs");
const Path = require("path");
const Axios = require("axios");

async function downloadImage(url, filename, timeout) {
  const appDir = Path.dirname(require.main.filename);
  const path = Path.resolve(appDir, "images", `${filename}.jpg`);

  const writer = Fs.createWriteStream(path);

  const response = await Axios({
    url,
    method: "GET",
    responseType: "stream",
    timeout: timeout
  });

  response.data.pipe(writer);

  return new Promise((resolve, reject) => {
    writer.on("finish", resolve);
    writer.on("error", reject);
  });
}

module.exports = downloadImage;

What am I doing wrong in this approach?

Body:
This error:

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

It's because of these lines:

res.json(savedItem);
res.json({ message: err });

You're running these lines several times, because they are inside the loop, you can't respond a request more than once because the connection it's closed after the first call.

Try with this:

router.post("/updateBlacklist", async (req, res) => {
  const savedList = [];
  req.body.product_id.forEach(async element => {
    const blacklistItem = new Blacklist({ product_id: element });
    try {
      const savedItem = await blacklistItem.save();
      savedList.push(savedItem)
    } catch (err) {
      console.log(err);
      savedList.push({ message: err });
    }
  });
  res.json(savedItem);
});

UPDATE (suggestion):

router.post("/updateBlacklist", async (req, res) => {
  const items = req.body.product_id.map(element =>
     new Blacklist({ product_id: element })
  });
  const result = await Blacklist.insertMany(items); // not sure about the syntax
  res.json(result);
});


问:
DAX: how to select max per date & per month
I have a table that keeps Date and Quantity, I need to define MAX Quantity each Month at Date level.

Here is an example:

```<code>Date           Quantity Max Quantity per Month
01.02.19    20 351  40 952
02.02.19    14 176  40 952
03.02.19    25 218  40 952
23.02.19    13 244  40 952
24.02.19    14 021  40 952
25.02.19    33 173  40 952
26.02.19    21 233  40 952
01.04.19    11 855  40 952
24.04.19    19 113  40 952
25.04.19    40 952  40 952
26.04.19    37 460  40 952
</code>```

Here MAX Qty in February is 33 173, in April 40 952
But my current measure displays a total max of 40 952

Here is DAX used:

```<code>Max Quantity per Month =
CALCULATE(MAXX (
    SUMMARIZE (
        'Table1',
        'Date'[Year Month],
        'Table1'[Date],
        "Qty", [Quantity]
    ),
    [MAX_Qty]
), ALLEXCEPT('Table1', 'Table1'[Date], 'Date'[Year Month]))
</code>```

What correct DAX should be to display different value per month?

答:
You can use:</p>

```<code>Max Quantity per Month =
CALCULATE (
    MAX ( Table1[Quantity] ),
    FILTER (
        Table1,
        MONTH ( Table1[Date] ) = MONTH ( EARLIER ( Table1[Date] ) )
            && YEAR ( Table1[Date] ) = YEAR ( EARLIER ( Table1[Date] ) )
    )
)
</code>```

Body:
I have a table that keeps Date and Quantity, I need to define MAX Quantity each Month at Date level.

Here is an example:

Date           Quantity Max Quantity per Month
01.02.19    20 351  40 952
02.02.19    14 176  40 952
03.02.19    25 218  40 952
23.02.19    13 244  40 952
24.02.19    14 021  40 952
25.02.19    33 173  40 952
26.02.19    21 233  40 952
01.04.19    11 855  40 952
24.04.19    19 113  40 952
25.04.19    40 952  40 952
26.04.19    37 460  40 952

Here MAX Qty in February is 33 173, in April 40 952
But my current measure displays a total max of 40 952

Here is DAX used:

Max Quantity per Month =
CALCULATE(MAXX (
    SUMMARIZE (
        'Table1',
        'Date'[Year Month],
        'Table1'[Date],
        "Qty", [Quantity]
    ),
    [MAX_Qty]
), ALLEXCEPT('Table1', 'Table1'[Date], 'Date'[Year Month]))

What correct DAX should be to display different value per month?

Body:
You can use:

Max Quantity per Month =
CALCULATE (
    MAX ( Table1[Quantity] ),
    FILTER (
        Table1,
        MONTH ( Table1[Date] ) = MONTH ( EARLIER ( Table1[Date] ) )
            && YEAR ( Table1[Date] ) = YEAR ( EARLIER ( Table1[Date] ) )
    )
)


问:
Get latest entry by date (year) and add Value to field from this row
I will do the following:

Run a Query that return me the latest record from current year take a field from that record.

This is may Tabel I used for this:

```<code>ID(int,PK)    FremdID(int)    Erstellung(datetime)      Number(int)
1             10              2019-05-31 09:15:41.003   1
2             11              2019-05-31 09:15:42.154   3
</code>```

So if I run the query it should return Row with index 2 because we are in year 2019 and that is the latest entry from 2019.

If we are now in 2020 then the query should not return any row becuase there is no entry for 2020.

答:
I would recommend:

```<code>SELECT TOP(1) t.*
FROM #Table t
WHERE Erstellung >= DATEFROMPARTS(YEAR(GETDATE()), 1, 1)
ORDER BY Erstellung DESC;
</code>```

I recommend this because it is index compatible.  It can take advantage of an index on (Erstellung DESC).

If you use a function like YEAR(Erstellung) in the WHERE clause, the index will not be used.

Body:
I will do the following:

Run a Query that return me the latest record from current year take a field from that record.

This is may Tabel I used for this:

ID(int,PK)    FremdID(int)    Erstellung(datetime)      Number(int)
1             10              2019-05-31 09:15:41.003   1
2             11              2019-05-31 09:15:42.154   3

So if I run the query it should return Row with index 2 because we are in year 2019 and that is the latest entry from 2019.

If we are now in 2020 then the query should not return any row becuase there is no entry for 2020.

Body:
I would recommend:

SELECT TOP(1) t.*
FROM #Table t
WHERE Erstellung >= DATEFROMPARTS(YEAR(GETDATE()), 1, 1)
ORDER BY Erstellung DESC;

I recommend this because it is index compatible.  It can take advantage of an index on (Erstellung DESC).

If you use a function like YEAR(Erstellung) in the WHERE clause, the index will not be used.


问:
Using Rscript with an .Rnw file AND commandArgs()
I have an .Rnw file, containing R code chunks and LaTeX commands. So far, I have been developing and testing this code in Rstudio: clicking on "compile PDF" to obtain some output files and a PDF file generated.

I would now like to use commandArgs() to be able to give my .Rnw one single argument: a YAML file. This file contains all sorts of parameters that are needed by the script.

To give some context:

My .Rnw script is a pipeline script which was designed to be as "generic" as possible.

My .Rnw script requires a number of parameters each time - these will be the parameters varying between each project. To supply these parameters, I currently (already) use a YAML configuration file. This means the first thing my .Rnw script does is import the YAML file, and then it starts doing things.

My problem is: can I used "Rscript", "commandArgs()" and knitr all together. I was hoping that my addind some commandArgs() to my .Rnw script, I would be able to run everything (i.e. give argument on command line to supply YAML file and compile PDF) like so:

```<code>Rscript script.Rnw params.yaml
</code>```

However, I have getting this error about a "\", which I strongly suspect is something to do with the fact I'm using a .Rnw file (and the very first thing in it a LaTeX command). I then saw potential solution on other posts such as:

```<code> Rscript -e "library(knitr); knit('script.Rnw')"
 pdflatex script.tex
</code>```

However, this also fails - unsurprisingly I suppose because I haven't given it my configuration YAML file.

I realise my design is likely flawed: by using commandAgrs() AND knitr together, I am making things quite complicated. I also realise that knitr may have not be truly designed for making reports for scripts that are used as pipelines (at least that's my impression). The reason I want to use it is so that for each project, a quick PDF can be generated with all the results.

I would appreciate any advice. Here is a sample of my code:

```<code>\documentclass[12pt, a4paper]{article}

\usepackage[utf8]{inputenc}
\usepackage{hyperref}
\hypersetup{
colorlinks   = true, %Colours links instead of ugly boxes
urlcolor     = blue, %Colour for external hyperlinks
linkcolor    = blue, %Colour of internal links
citecolor   = blue %Colour of citations
 }
\usepackage{caption}
\setlength{\parindent}{0pt}
\usepackage{authblk}
\usepackage[nomarkers, nolists]{endfloat} %Positions figures at the end of the document and add no list of names (requires that chunk have fig.cap option)
\usepackage{soul} % Allows underline lines to be broken (use \ul{} instead of \underline{})

\usepackage{helvet} %Set up Arial as font
\renewcommand{\familydefault}{\sfdefault}

\newcommand{\Rfunction}[1]{{\texttt{#1}}}
\newcommand{\Rpackage}[1]{{\textit{#1}}}

\title{\textbf{Report}}
\author{Author}
\date{\today}

\begin{document}

\maketitle

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in table of contents
\tableofcontents
\endgroup

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in list of figures
\listoffigures
\endgroup

\newpage
\section{Introduction}
This report blah blah blah

\newpage
\section{Results}

<<importing-lib, echo=FALSE, message=FALSE, cache=TRUE>>=

###################################################
# Obtain command-line YAML file and set directory #
###################################################

#!/usr/bin/env Rscript
args= commandArgs(trailingOnly=TRUE)

if (length(args) == 0) {
 stop("this script requires a configuration file (.yaml) as input")

 } else if (length(args) > 1) {
  stop("this script requires only one input: a configuration file (.yaml)")

}

params <-  yaml.load_file(args[1])

setwd(params$workdir)

if (dir.exists(file.path(params$workdir, "results")) == FALSE) {
  dir.create(file.path(params$workdir, "results","edgeR"), recursive = TRUE)
  dir.create(file.path(params$workdir, "results", "gsea", "input_files"), recursive = TRUE)
}

print("Hello!")
@

\end{document}
</code>```

答:
Ok so I have found 2 ways in which it seems to work:

Method 1: using command line knitr() and pdflatex

In this case, everything is one script (called script.Rnw) still but it looks like so:

```<code>\documentclass[12pt, a4paper]{article}

\usepackage[utf8]{inputenc}
\usepackage{hyperref}
\hypersetup{
colorlinks   = true, %Colours links instead of ugly boxes
urlcolor     = blue, %Colour for external hyperlinks
linkcolor    = blue, %Colour of internal links
citecolor   = blue %Colour of citations
 }
\usepackage{caption}
\setlength{\parindent}{0pt}
\usepackage{authblk}
\usepackage[nomarkers, nolists]{endfloat} %Positions figures at the end of the document and add no list of names (requires that chunk have fig.cap option)
\usepackage{soul} % Allows underline lines to be broken (use \ul{} instead of \underline{})

\usepackage{helvet} %Set up Arial as font
\renewcommand{\familydefault}{\sfdefault}

\newcommand{\Rfunction}[1]{{\texttt{#1}}}
\newcommand{\Rpackage}[1]{{\textit{#1}}}

\title{\textbf{Test report}}
\date{\today}

\begin{document}

\maketitle

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in table of contents
\tableofcontents
\endgroup

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in list of figures
\listoffigures
\endgroup

\newpage
\section{Introduction}
This is the introduction.

\newpage
\section{Results}

This is the results.

<<importing-lib, echo=FALSE, message=FALSE>>=

###################################################
# Obtain command-line YAML file and set directory #
###################################################

#!/usr/bin/env Rscript
args= commandArgs(trailingOnly=TRUE)

if (length(args) == 0) {
  stop("this script requires a configuration file (.yaml) as input")

  # } else if (length(args) > 1) {
  # stop("this script requires only one input: a configuration file (.yaml)")

}

library(yaml)
params <- yaml.load_file(args[1])

dir <- getwd()

if (dir.exists(file.path(dir, "results")) == FALSE) {
  dir.create(file.path(dir, "results","part1"), recursive = TRUE)
  dir.create(file.path(dir, "results", "part2", "input_files"), recursive = TRUE)
}

print("Hello!")
print(params$project)
@

\newpage
\section{End}

This is the end!

\end{document}
</code>```

To run the pipeline:

```<code>Rscript -e "library(knitr); knit('script.Rnw')" params.yaml && pdflatex script.tex
</code>```

Method 2: separating code into a .Rnw file and .R launch file

The script.Rnw looks like so:

```<code>\documentclass[12pt, a4paper]{article}

\usepackage[utf8]{inputenc}
\usepackage{hyperref}
\hypersetup{
colorlinks   = true, %Colours links instead of ugly boxes
urlcolor     = blue, %Colour for external hyperlinks
linkcolor    = blue, %Colour of internal links
citecolor   = blue %Colour of citations
 }
\usepackage{caption}
\setlength{\parindent}{0pt}
\usepackage{authblk}
\usepackage[nomarkers, nolists]{endfloat} %Positions figures at the end of the document and add no list of names (requires that chunk have fig.cap option)
\usepackage{soul} % Allows underline lines to be broken (use \ul{} instead of \underline{})

\usepackage{helvet} %Set up Arial as font
\renewcommand{\familydefault}{\sfdefault}

\newcommand{\Rfunction}[1]{{\texttt{#1}}}
\newcommand{\Rpackage}[1]{{\textit{#1}}}

\title{\textbf{Test report}}
\date{\today}

\begin{document}

\maketitle

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in table of contents
\tableofcontents
\endgroup

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in list of figures
\listoffigures
\endgroup

\newpage
\section{Introduction}
This is the introduction.

\newpage
\section{Results}

This is the results.

<<first-chunk, echo=FALSE, message=FALSE>>=

print("Hello!")
print(params$project)
@

\newpage
\section{End}

This is the end!

\end{document}
</code>```

The launch.R script looks like so:

```<code>#!/usr/bin/env Rscript

library(yaml)
library(knitr)

args= commandArgs(trailingOnly=TRUE)

if (length(args) == 0) {
  stop("this script requires a configuration file (.yaml) as input")

  # } else if (length(args) > 1) {
  # stop("this script requires only one input: a configuration file (.yaml)")

}

params <- yaml.load_file(args[1])

dir <- getwd()

if (dir.exists(file.path(dir, "results")) == FALSE) {
  dir.create(file.path(dir, "results","edgeR"), recursive = TRUE)
  dir.create(file.path(dir, "results", "gsea", "input_files"), recursive = TRUE)
}

knit2pdf('script.Rnw')
</code>```

To run the script:

```<code>Rscript launch.R params.yaml
</code>```

One difference between the methods: method 1 generates more files (*tex, *toc, *out, *log, *aux), presumably because it's technically 2 commands. Method 2 only generates a .tex and a .pdf file.

Body:
I have an .Rnw file, containing R code chunks and LaTeX commands. So far, I have been developing and testing this code in Rstudio: clicking on "compile PDF" to obtain some output files and a PDF file generated.

I would now like to use commandArgs() to be able to give my .Rnw one single argument: a YAML file. This file contains all sorts of parameters that are needed by the script.

To give some context:

My .Rnw script is a pipeline script which was designed to be as "generic" as possible.

My .Rnw script requires a number of parameters each time - these will be the parameters varying between each project. To supply these parameters, I currently (already) use a YAML configuration file. This means the first thing my .Rnw script does is import the YAML file, and then it starts doing things.

My problem is: can I used "Rscript", "commandArgs()" and knitr all together. I was hoping that my addind some commandArgs() to my .Rnw script, I would be able to run everything (i.e. give argument on command line to supply YAML file and compile PDF) like so:

Rscript script.Rnw params.yaml

However, I have getting this error about a "\", which I strongly suspect is something to do with the fact I'm using a .Rnw file (and the very first thing in it a LaTeX command). I then saw potential solution on other posts such as:

 Rscript -e "library(knitr); knit('script.Rnw')"
 pdflatex script.tex

However, this also fails - unsurprisingly I suppose because I haven't given it my configuration YAML file.

I realise my design is likely flawed: by using commandAgrs() AND knitr together, I am making things quite complicated. I also realise that knitr may have not be truly designed for making reports for scripts that are used as pipelines (at least that's my impression). The reason I want to use it is so that for each project, a quick PDF can be generated with all the results.

I would appreciate any advice. Here is a sample of my code:

\documentclass[12pt, a4paper]{article}

\usepackage[utf8]{inputenc}
\usepackage{hyperref}
\hypersetup{
colorlinks   = true, %Colours links instead of ugly boxes
urlcolor     = blue, %Colour for external hyperlinks
linkcolor    = blue, %Colour of internal links
citecolor   = blue %Colour of citations
 }
\usepackage{caption}
\setlength{\parindent}{0pt}
\usepackage{authblk}
\usepackage[nomarkers, nolists]{endfloat} %Positions figures at the end of the document and add no list of names (requires that chunk have fig.cap option)
\usepackage{soul} % Allows underline lines to be broken (use \ul{} instead of \underline{})

\usepackage{helvet} %Set up Arial as font
\renewcommand{\familydefault}{\sfdefault}

\newcommand{\Rfunction}[1]{{\texttt{#1}}}
\newcommand{\Rpackage}[1]{{\textit{#1}}}

\title{\textbf{Report}}
\author{Author}
\date{\today}

\begin{document}

\maketitle

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in table of contents
\tableofcontents
\endgroup

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in list of figures
\listoffigures
\endgroup

\newpage
\section{Introduction}
This report blah blah blah

\newpage
\section{Results}

<<importing-lib, echo=FALSE, message=FALSE, cache=TRUE>>=

###################################################
# Obtain command-line YAML file and set directory #
###################################################

#!/usr/bin/env Rscript
args= commandArgs(trailingOnly=TRUE)

if (length(args) == 0) {
 stop("this script requires a configuration file (.yaml) as input")

 } else if (length(args) > 1) {
  stop("this script requires only one input: a configuration file (.yaml)")

}

params <-  yaml.load_file(args[1])

setwd(params$workdir)

if (dir.exists(file.path(params$workdir, "results")) == FALSE) {
  dir.create(file.path(params$workdir, "results","edgeR"), recursive = TRUE)
  dir.create(file.path(params$workdir, "results", "gsea", "input_files"), recursive = TRUE)
}

print("Hello!")
@

\end{document}

Body:
Ok so I have found 2 ways in which it seems to work:

Method 1: using command line knitr() and pdflatex

In this case, everything is one script (called script.Rnw) still but it looks like so:

\documentclass[12pt, a4paper]{article}

\usepackage[utf8]{inputenc}
\usepackage{hyperref}
\hypersetup{
colorlinks   = true, %Colours links instead of ugly boxes
urlcolor     = blue, %Colour for external hyperlinks
linkcolor    = blue, %Colour of internal links
citecolor   = blue %Colour of citations
 }
\usepackage{caption}
\setlength{\parindent}{0pt}
\usepackage{authblk}
\usepackage[nomarkers, nolists]{endfloat} %Positions figures at the end of the document and add no list of names (requires that chunk have fig.cap option)
\usepackage{soul} % Allows underline lines to be broken (use \ul{} instead of \underline{})

\usepackage{helvet} %Set up Arial as font
\renewcommand{\familydefault}{\sfdefault}

\newcommand{\Rfunction}[1]{{\texttt{#1}}}
\newcommand{\Rpackage}[1]{{\textit{#1}}}

\title{\textbf{Test report}}
\date{\today}

\begin{document}

\maketitle

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in table of contents
\tableofcontents
\endgroup

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in list of figures
\listoffigures
\endgroup

\newpage
\section{Introduction}
This is the introduction.

\newpage
\section{Results}

This is the results.

<<importing-lib, echo=FALSE, message=FALSE>>=

###################################################
# Obtain command-line YAML file and set directory #
###################################################

#!/usr/bin/env Rscript
args= commandArgs(trailingOnly=TRUE)

if (length(args) == 0) {
  stop("this script requires a configuration file (.yaml) as input")

  # } else if (length(args) > 1) {
  # stop("this script requires only one input: a configuration file (.yaml)")

}

library(yaml)
params <- yaml.load_file(args[1])

dir <- getwd()

if (dir.exists(file.path(dir, "results")) == FALSE) {
  dir.create(file.path(dir, "results","part1"), recursive = TRUE)
  dir.create(file.path(dir, "results", "part2", "input_files"), recursive = TRUE)
}

print("Hello!")
print(params$project)
@

\newpage
\section{End}

This is the end!

\end{document}

To run the pipeline:

Rscript -e "library(knitr); knit('script.Rnw')" params.yaml && pdflatex script.tex

Method 2: separating code into a .Rnw file and .R launch file

The script.Rnw looks like so:

\documentclass[12pt, a4paper]{article}

\usepackage[utf8]{inputenc}
\usepackage{hyperref}
\hypersetup{
colorlinks   = true, %Colours links instead of ugly boxes
urlcolor     = blue, %Colour for external hyperlinks
linkcolor    = blue, %Colour of internal links
citecolor   = blue %Colour of citations
 }
\usepackage{caption}
\setlength{\parindent}{0pt}
\usepackage{authblk}
\usepackage[nomarkers, nolists]{endfloat} %Positions figures at the end of the document and add no list of names (requires that chunk have fig.cap option)
\usepackage{soul} % Allows underline lines to be broken (use \ul{} instead of \underline{})

\usepackage{helvet} %Set up Arial as font
\renewcommand{\familydefault}{\sfdefault}

\newcommand{\Rfunction}[1]{{\texttt{#1}}}
\newcommand{\Rpackage}[1]{{\textit{#1}}}

\title{\textbf{Test report}}
\date{\today}

\begin{document}

\maketitle

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in table of contents
\tableofcontents
\endgroup

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in list of figures
\listoffigures
\endgroup

\newpage
\section{Introduction}
This is the introduction.

\newpage
\section{Results}

This is the results.

<<first-chunk, echo=FALSE, message=FALSE>>=

print("Hello!")
print(params$project)
@

\newpage
\section{End}

This is the end!

\end{document}

The launch.R script looks like so:

#!/usr/bin/env Rscript

library(yaml)
library(knitr)

args= commandArgs(trailingOnly=TRUE)

if (length(args) == 0) {
  stop("this script requires a configuration file (.yaml) as input")

  # } else if (length(args) > 1) {
  # stop("this script requires only one input: a configuration file (.yaml)")

}

params <- yaml.load_file(args[1])

dir <- getwd()

if (dir.exists(file.path(dir, "results")) == FALSE) {
  dir.create(file.path(dir, "results","edgeR"), recursive = TRUE)
  dir.create(file.path(dir, "results", "gsea", "input_files"), recursive = TRUE)
}

knit2pdf('script.Rnw')

To run the script:

Rscript launch.R params.yaml

One difference between the methods: method 1 generates more files (*tex, *toc, *out, *log, *aux), presumably because it's technically 2 commands. Method 2 only generates a .tex and a .pdf file.


问:
Hide grid items with JavaScript
I have a 2 x 2 CSS grid. Each grid item briefly describes a service (small business website) and each grid item has a button to learn more about said service. When a user clicks one of the four buttons to learn more, I would like that grid item to expand to take up the entire 2x2 grid (this I have working) and for the other 3 grid items to disappear (this I am having trouble with). Here is an example: https://jsfiddle.net/L7fatdmh/ , note that only the first grid item has JS applied to it at the moment.

firstButton = document.getElementById("firstButton");
firstButton.onclick = function() {
  squaresGrid = document.getElementsByClassName("grid-squares");
  g1 = document.getElementById("g1");
  console.log(g1)
  g1.style.gridColumn = "1/3";
  g1.style.gridRow = "1/3";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.grid-squares {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows: 300px;
}</code>```

Service One

      lorem impsum

    <button id="firstButton">Learn More</button>

Service Two

      lorem impsum

    <button>Learn More</button>

Service Three

      lorem impsum

    <button>Learn More</button>

Service Four

      lorem impsum

    <button>Learn More</button>

```

As you can see in the jsFiddle example, the grid item does expand to fill the proper space, but all of the other grid items are still visible underneath. How can I hide these? Is initially hiding all grid-items and then displaying a specific item based on it's id (i.e g1 in the first grid item) the best option?

答:
You can select the elements that are not your event target and hide them.

Using your fiddle, if we add

gOther = document.querySelectorAll(".grid_item:not(#g1)");

for (g of gOther) {
 g.style.display = "none";
}
```

It would work, but for a real world scenario you would need to make this a little bit more complete and look for elements that are not your target.

Title: Hide grid items with JavaScript

Body:
I have a 2 x 2 CSS grid. Each grid item briefly describes a service (small business website) and each grid item has a button to learn more about said service. When a user clicks one of the four buttons to learn more, I would like that grid item to expand to take up the entire 2x2 grid (this I have working) and for the other 3 grid items to disappear (this I am having trouble with). Here is an example: https://jsfiddle.net/L7fatdmh/ , note that only the first grid item has JS applied to it at the moment.

firstButton = document.getElementById("firstButton");
firstButton.onclick = function() {
  squaresGrid = document.getElementsByClassName("grid-squares");
  g1 = document.getElementById("g1");
  console.log(g1)
  g1.style.gridColumn = "1/3";
  g1.style.gridRow = "1/3";
}

.grid-squares {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows: 300px;
}

Service One

      lorem impsum

    <button id="firstButton">Learn More</button>

Service Two

      lorem impsum

    <button>Learn More</button>

Service Three

      lorem impsum

    <button>Learn More</button>

Service Four

      lorem impsum

    <button>Learn More</button>

As you can see in the jsFiddle example, the grid item does expand to fill the proper space, but all of the other grid items are still visible underneath. How can I hide these? Is initially hiding all grid-items and then displaying a specific item based on it's id (i.e g1 in the first grid item) the best option?

Body:
You can select the elements that are not your event target and hide them.

Using your fiddle, if we add

gOther = document.querySelectorAll(".grid_item:not(#g1)");

for (g of gOther) {
 g.style.display = "none";
}

It would work, but for a real world scenario you would need to make this a little bit more complete and look for elements that are not your target.


问:
How to efficiently sync data between multiple clients with MySQL?
I am setting up an arduino based network that has multiple controllers (phones, web page, PC app) to configure a relay system (base). This network uses MySQL database to store and sync configuration between clients and the base. All clients and the base can manipulate configuration and clients should see real-time configuration of the base. It means if a client changes the configuration, all other clients and the base should see this change. How can I sync data in this network and avoid conflicts? Is there any efficient algorithms?

I used database server's timestamp to track changes. Whenever db changes, it saves timestamp. All clients get this timestamp and compare it to last fetched one. But the problem is when 2 or more clients access this database simultaneously, conflict occurs and I loose configuration changes of all clients except one.
Using timestamp doesn't seem to be a good idea. If the base goes offline, we can't save the changes made on the base during offline time. Because as soon as it gets back online, it fetches configuration from database.
Sorry for my poor English.

答:
If you have unreliably connected devices, and multiple clients modifying a common set of data, you inherently have a fairly complex application design.

One way you could do this is to store history in your table.

So, instead of

```<code>ID     config_1    config_2 ...  timestamp
----------------------------------------------
1          true         44         24-may-2019:20:00:02
2          false        88         26-may-2019:10:10:06
</code>```

You might do

```<code>ID     config_1    config_2 ...  timestamp
----------------------------------------------
1          true         44         24-may-2019:20:00:02
1          false        44         21-may-2019:11:34:34
1          false        22         10-oct-2018:19:22:22
2          false        88         26-may-2019:10:10:06
</code>```

In this case, you're not updating records so don't need to worry about locking - you simply insert new values, and "the last one wins".

Body:
If you have unreliably connected devices, and multiple clients modifying a common set of data, you inherently have a fairly complex application design.

One way you could do this is to store history in your table.

So, instead of

ID     config_1    config_2 ...  timestamp
----------------------------------------------
1          true         44         24-may-2019:20:00:02
2          false        88         26-may-2019:10:10:06

You might do

ID     config_1    config_2 ...  timestamp
----------------------------------------------
1          true         44         24-may-2019:20:00:02
1          false        44         21-may-2019:11:34:34
1          false        22         10-oct-2018:19:22:22
2          false        88         26-may-2019:10:10:06

In this case, you're not updating records so don't need to worry about locking - you simply insert new values, and "the last one wins".


答:
Try

```<code>dictToInsert[str(i)] = slMetadata[dic]
</code>```

instead of

```<code>dictToInsert[i] = slMetadata[dic]
</code>```

Title: Inserting list of dictionaries into mongodb and removing int keys

Body:
I have to insert a list of dictionaries having this syntax (I have more than 6500 dicts like these 3):

0: {208271891: {'bra': 'Solarmax',
             'bri': 4,
             'eur': 95.4,
             'max': 1980,
             'nam': '2000S',
             'pan': {'bra': 'Sanyo',
                     'bri': 3,
                     'eff': 16,
                     'h': 861,
                     'hea': 50,
                     'mni': 1,
                     'mnm': 'free standing',
                     'n': 7,
                     'nam': 'HDE1 230',
                     'slo': 35,
                     't': -0.3,
                     'w': 1610,
                     'wp': 230},
             'pha': 1,
             'rat': 0.81,
             'wp': 1610}},

1: {208271900: {'bra': 'Solarmax',
             'bri': 4,
             'eur': 95.4,
             'max': 1980,
             'nam': '2000S',
             'pan': {'bra': 'Sanyo',
                     'bri': 3,
                     'eff': 16,
                     'h': 861,
                     'hea': -40,
                     'mni': 1,
                     'mnm': 'free standing',
                     'n': 9,
                     'nam': 'HDE1 230',
                     'slo': 30,
                     't': -0.3,
                     'w': 1610,
                     'wp': 230},
             'pha': 1,
             'rat': 1.05,
             'wp': 2070}},

 2: {208271892: {'bra': 'Solarmax',
             'bri': 4,
             'eur': 95.4,
             'max': 1980,
             'nam': '2000S',
             'pan': {'bra': 'Sanyo',
                     'bri': 3,
                     'eff': 16,
                     'h': 861,
                     'hea': 50,
                     'mni': 1,
                     'mnm': 'free standing',
                     'n': 9,
                     'nam': 'HDE1 230',
                     'slo': 30,
                     't': -0.3,
                     'w': 1610,
                     'wp': 230},
             'pha': 1,
             'rat': 1.05,
             'wp': 2070}}

I tried to delete keys with dict.pop() and 'del' but got this error: 'TypeError: 'int' object does not support item deletion'.

slMetadata = {}

for row in metadatas: #metadatas coming from mysql

   mid = int(row['met_id'])
   slMetadata.update(mid = mid)

   bsInv = {
          mid:
             {
             'wp' : wp,
             'bra': str(row['invbraname']),
             'bri': int(row['inm_bra_id']),
             'nam': str(row['inm_name']),
             'pha': int(row['inm_phases']),
             'max': int(row['inm_maximal_power']),
             'eur': float(row['inm_euro_efficiency']),
             'pan':
                  {
                  'n'  : int(row['inv_pan_numbers']),
                  'hea': int(row['inv_pan_heading']),
                  'slo': int(row['inv_pan_slope']),
                  'mni': int(row['inv_mnt_id']),
                  'mnm': str(row['mnt_name']),
                  'bra': str(row['panbraname']),
                  'bri': int(row['pan_bra_id']),
                  'nam': str(row['pan_name']),
                  'wp' : int(row['pan_wc']),
                  'eff': int(row['efficiency']),
                  't'  : float(row['coefficient_p']),
                  'w'  : int(row['pan_width']),
                  'h'  : int(row['pan_height'])
                  }
             }
        }
i = 0
dictToInsert = {}
for dic in slMetadata:
    dictToInsert[i] = slMetadata[dic]
    i += 1

if len(dictToInsert) > 0:
   insertion = dbCollection.insert_many(dictToInsert)

What I want is to insert all these dicts into mongoDb but I have the error below : bson.errors.InvalidDocument: documents must have only string keys, key was 0.

Which I fully understand and know that I can't insert into mongoDb with 'int' key. But what is the alternative?

Thanks.

Body:
Try

dictToInsert[str(i)] = slMetadata[dic]

instead of

dictToInsert[i] = slMetadata[dic]


问:
Blocking launch of WPF Dialog from a different thread
We want to create and launch a modal dialog box over the main window. This process is initiated from a different thread - for some reason. This different thread calls the execute method - and must be blocked until the dialog box closes. The question is - how? On this code the execute won't be blocked. The Join() call also does not work as expected.

```<code>public void Execute()
{
    Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
    newWindowThread.SetApartmentState(ApartmentState.STA);
    newWindowThread.IsBackground = true;
    newWindowThread.Start();
    // newWindowThread.Join();
}

private void ThreadStartingPoint()
{
    this.ParameterDialog = new ParameterDialog();
    this.ParameterDialog.ShowDialog();
    System.Windows.Threading.Dispatcher.Run();
}
</code>```

Any idea how to implement this behavior? Thanks in advance!

答:
You should shutdown the dispatcher when the dialog window is closed:</p>

```<code>public void Execute()
{
    Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
    newWindowThread.SetApartmentState(ApartmentState.STA);
    newWindowThread.IsBackground = true;
    newWindowThread.Start();
    newWindowThread.Join();
}

private void ThreadStartingPoint()
{
    this.ParameterDialog = new ParameterDialog();
    this.ParameterDialog.Closed += ParameterDialog_Closed;
    this.ParameterDialog.ShowDialog();
    System.Windows.Threading.Dispatcher.Run();
}

private void ParameterDialog_Closed(object sender, EventArgs e)
{
    this.ParameterDialog.Closed -= ParameterDialog_Closed;
    Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
}
</code>```

Body:
We want to create and launch a modal dialog box over the main window. This process is initiated from a different thread - for some reason. This different thread calls the execute method - and must be blocked until the dialog box closes. The question is - how? On this code the execute won't be blocked. The Join() call also does not work as expected.

public void Execute()
{
    Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
    newWindowThread.SetApartmentState(ApartmentState.STA);
    newWindowThread.IsBackground = true;
    newWindowThread.Start();
    // newWindowThread.Join();
}

private void ThreadStartingPoint()
{
    this.ParameterDialog = new ParameterDialog();
    this.ParameterDialog.ShowDialog();
    System.Windows.Threading.Dispatcher.Run();
}

Any idea how to implement this behavior? Thanks in advance!

Body:
You should shutdown the dispatcher when the dialog window is closed:

public void Execute()
{
    Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
    newWindowThread.SetApartmentState(ApartmentState.STA);
    newWindowThread.IsBackground = true;
    newWindowThread.Start();
    newWindowThread.Join();
}

private void ThreadStartingPoint()
{
    this.ParameterDialog = new ParameterDialog();
    this.ParameterDialog.Closed += ParameterDialog_Closed;
    this.ParameterDialog.ShowDialog();
    System.Windows.Threading.Dispatcher.Run();
}

private void ParameterDialog_Closed(object sender, EventArgs e)
{
    this.ParameterDialog.Closed -= ParameterDialog_Closed;
    Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
}


问:
How to compare two arrays using tensorflow?
I need to compare two arrays and get either true or false,not elementwise result. My code is

```<code>X = tf.constant([0.05, 0.10], dtype=tf.float32, shape=[1, 2])
y = tf.constant([0.01, 0.99], dtype=tf.float32, shape=[1, 2])

equality = tf.equal(X, y)
</code>```

prints [False, False]

my requirement is to get true or false, not an array.

答:
I got solution.</p>

```<code>equality = tf.equal(X, y)
reduce_t = tf.reduce_all(equality)
print(sess.run(reduce_t))
</code>```

Body:
I need to compare two arrays and get either true or false,not elementwise result. My code is

X = tf.constant([0.05, 0.10], dtype=tf.float32, shape=[1, 2])
y = tf.constant([0.01, 0.99], dtype=tf.float32, shape=[1, 2])

equality = tf.equal(X, y)

prints [False, False]

my requirement is to get true or false, not an array.

Body:
I got solution.

equality = tf.equal(X, y)
reduce_t = tf.reduce_all(equality)
print(sess.run(reduce_t))


问:
How to remove columns based on a specific row with 0?
I have the data frame that looks like below:

```<code>Genes     Sample1    Sample2   Sample3   Sample4
A1BG         14         59        11        31
A2M           0        7708       7306       0
A2ML1        64         71       1317       3406
A4GALT      142          0       1195       700
AAAS        1821       1233        0        959
</code>```

I wanted to remove the columns based on a row (Gene: A2M) with 0. So, if any of the samples with 0 for the row A2M should be removed. And the output should look like below:

```<code>Genes     Sample2   Sample3
A1BG         59        11
A2M         7708       7306
A2ML1        71       1317
A4GALT        0       1195
AAAS        1233        0
</code>```

答:
We can use colSums, i.e.

```<code>df[colSums(df[df$Genes == 'A2M',] == 0) == 0]

#   Genes Sample2 Sample3
#1   A1BG      59      11
#2    A2M    7708    7306
#3  A2ML1      71    1317
#4 A4GALT       0    1195
#5   AAAS    1233       0
</code>```

Body:
I have the data frame that looks like below:

Genes     Sample1    Sample2   Sample3   Sample4
A1BG         14         59        11        31
A2M           0        7708       7306       0
A2ML1        64         71       1317       3406
A4GALT      142          0       1195       700
AAAS        1821       1233        0        959

I wanted to remove the columns based on a row (Gene: A2M) with 0. So, if any of the samples with 0 for the row A2M should be removed. And the output should look like below:

Genes     Sample2   Sample3
A1BG         59        11
A2M         7708       7306
A2ML1        71       1317
A4GALT        0       1195
AAAS        1233        0

Body:
We can use colSums, i.e.

df[colSums(df[df$Genes == 'A2M',] == 0) == 0]

#   Genes Sample2 Sample3
#1   A1BG      59      11
#2    A2M    7708    7306
#3  A2ML1      71    1317
#4 A4GALT       0    1195
#5   AAAS    1233       0


问:
With CSS, how to style a generic, global style?
Update: this question is about global style.  So solution such as #some-id .score is NOT a solution.

At first, I was styling as

```<code>.score { font-size: 32px; color: #777 }
</code>```

And the "score" is something that can happen any where, something of a global style.  But since other style actually might have:

```<code>#summary-panel { font-size: 13px }
</code>```

The one with id will override the one just having classes (the first CSS rule in this post).  (So if score is displayed within summary-panel then the font-size will be overridden to be 13px but the score style is supposed to be global and need a 32px style.) So I was tempted to use

```<code>.score { font-size: 32px !important; color: #777 !important }
</code>```

because the !important can act as the "second level" which override everything ordinary, and act as a global style.

Is this a good way or better way?  One catch is that if sometimes we might have a CSS issue with IE 7 (or IE 6), that we need a separate stylesheet such as ie.css, and in there, there might be also

```<code>#summary-panel { font-size: 12px !important }
</code>```

so in this case, the !important will be overridden because the one having an id will always win over just classes.  So is there a better way?

答:
Maybe this?

```<code>#summary-panel.score { font-size: 32px; }
</code>```

I guess I'm not sure how many styles you want to add or if the question is how to do this without adding any new styles, in which case I'd say there is not a better way.

Body:
Update: this question is about global style.  So solution such as #some-id .score is NOT a solution.

At first, I was styling as

.score { font-size: 32px; color: #777 }

And the "score" is something that can happen any where, something of a global style.  But since other style actually might have:

#summary-panel { font-size: 13px }

The one with id will override the one just having classes (the first CSS rule in this post).  (So if score is displayed within summary-panel then the font-size will be overridden to be 13px but the score style is supposed to be global and need a 32px style.) So I was tempted to use

.score { font-size: 32px !important; color: #777 !important }

because the !important can act as the "second level" which override everything ordinary, and act as a global style.

Is this a good way or better way?  One catch is that if sometimes we might have a CSS issue with IE 7 (or IE 6), that we need a separate stylesheet such as ie.css, and in there, there might be also

#summary-panel { font-size: 12px !important }

so in this case, the !important will be overridden because the one having an id will always win over just classes.  So is there a better way?

Body:
Maybe this?

#summary-panel.score { font-size: 32px; }

I guess I'm not sure how many styles you want to add or if the question is how to do this without adding any new styles, in which case I'd say there is not a better way.


问:
'for' loop terminating before termination condition is met
Edit: Solved

This is a program to rotate an array of size 'n' by 'd' towards the left.
For example: 1 2 3 4 5 6 7 for d=3 goes to 4 5 6 7 1 2 3. My problem is regarding the final loop in int main() that is being used to print the array. That loop is not printing the array upto all it's 'n' members.

I've tried printing the array for a specific 'n' for example n=7. It works in that case. Hence, I don't think there is any logical error in the rotleft() function.

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

void rotleft(int arr[],int d,int n)
{
    int temp[d];
    for(int i=0;i<d;i++)
    {
        temp[i]=arr[i];
    }
    for(int i=0;i<n-d;i++)
    {
        arr[i]=arr[i+d];
    }
    for(int i=n-d;i<n;i++)
    {
        arr[i]=temp[i-n+d];
    }

}

int main()
{
    int n,d,arr[n];

    cin>>n>>d;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    rotleft(arr,d,n);
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}
```

When I replaced 'n' by 7 in the final loop I got the accurate result, but for general 'n', it shows 4 5 6 instead of 4 5 6 7 1 2 3 (refer to above example).

答:
C++ does not support array of dynamic size yet. The size of array needs to be known at compile time. So as suggested already, use vector instead of array if your size is dynamic. </p>

<p>You may achieve the same result by using already existing library function: std::rotate(). However, if you are trying to learn to implement rotate yourself then, its fine. </p>

Body:
Edit: Solved

This is a program to rotate an array of size 'n' by 'd' towards the left.
For example: 1 2 3 4 5 6 7 for d=3 goes to 4 5 6 7 1 2 3. My problem is regarding the final loop in int main() that is being used to print the array. That loop is not printing the array upto all it's 'n' members.

I've tried printing the array for a specific 'n' for example n=7. It works in that case. Hence, I don't think there is any logical error in the rotleft() function.

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

void rotleft(int arr[],int d,int n)
{
    int temp[d];
    for(int i=0;i<d;i++)
    {
        temp[i]=arr[i];
    }
    for(int i=0;i<n-d;i++)
    {
        arr[i]=arr[i+d];
    }
    for(int i=n-d;i<n;i++)
    {
        arr[i]=temp[i-n+d];
    }

}

int main()
{
    int n,d,arr[n];

    cin>>n>>d;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    rotleft(arr,d,n);
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}

When I replaced 'n' by 7 in the final loop I got the accurate result, but for general 'n', it shows 4 5 6 instead of 4 5 6 7 1 2 3 (refer to above example).

Body:
C++ does not support array of dynamic size yet. The size of array needs to be known at compile time. So as suggested already, use vector instead of array if your size is dynamic.

You may achieve the same result by using already existing library function: std::rotate(). However, if you are trying to learn to implement rotate yourself then, its fine.


问:
How can i use multiple implements?
I'm making App with Android Studio.

I have a

```<code>public class MainActivity extends Activity implements View.OnClickListener, OnCheckedChangeListener
</code>```

And I need to add "AppCompatActivity" to the MainActivity.

I have searched on the Internet and I found only one can be used for extends.

So I Changed to

```<code>public class MainActivity extends Activity implements View.OnClickListener, OnCheckedChangeListener, AppCompatActivity
</code>```

This and AppCompatActivity has an error that "Interface expected here".

How can I solve this problem?

答:
The 'Interface expected here' occurs when you implement a class, not an interface.
AppCompatActivity is a class which you are not able to implement.

I don't know why you want to extend from Activity in addition toAppCompatActivity, AppCompatActivity inherits from Activity already.

```<code>AppCompatActivity > FragmentActivity > SupportActivity > Activity
</code>```

Just write:

```<code>public class MainActivity extends AppCompatActivity implements View.OnClickListener, OnCheckedChangeListener {
</code>```

There is no need to extend Activity for you when you do it like that.

Title: How can i use multiple implements?

Body:
I'm making App with Android Studio.

I have a

public class MainActivity extends Activity implements View.OnClickListener, OnCheckedChangeListener

And I need to add "AppCompatActivity" to the MainActivity.

I have searched on the Internet and I found only one can be used for extends.

So I Changed to

public class MainActivity extends Activity implements View.OnClickListener, OnCheckedChangeListener, AppCompatActivity

This and AppCompatActivity has an error that "Interface expected here".

How can I solve this problem?

Body:
The 'Interface expected here' occurs when you implement a class, not an interface.
AppCompatActivity is a class which you are not able to implement.

I don't know why you want to extend from Activity in addition toAppCompatActivity, AppCompatActivity inherits from Activity already.

AppCompatActivity > FragmentActivity > SupportActivity > Activity

Just write:

public class MainActivity extends AppCompatActivity implements View.OnClickListener, OnCheckedChangeListener {

There is no need to extend Activity for you when you do it like that.


问:
Is there a way to have currency conversions from Google Finance stick?
I need to find a way to automatically copy the output of the below GoogleFinance formula into another cell and make it stick, i.e. doesn't change when the exchange rate changes.

```<code>=A1*GOOGLEFINANCE("currency:AUDGBP")
</code>```

I was going to use something like =value(x) but this would change every time the above formula generated a new value, whereas I want something to stick as soon as it's output an answer.

答:
The GOOGLEFINANCE function has some optional parameters - one of them is the start date.

If you request the exchange rate for a particular date then it won't change later on.

```<code>=GOOGLEFINANCE("Currency:AUDGBP", "price", "05/31/2019")
</code>```

The output is a little different - a range with the date and value rather than a single cell, but the value for the exchange rate is correct and won't change.

You can then use the INDEX function to extract just the exchange rate

```<code>=INDEX(GOOGLEFINANCE("Currency:AUDGBP", "price", "05/31/2019"), 2, 2)
</code>```

As described here

Body:
I need to find a way to automatically copy the output of the below GoogleFinance formula into another cell and make it stick, i.e. doesn't change when the exchange rate changes.

=A1*GOOGLEFINANCE("currency:AUDGBP")

I was going to use something like =value(x) but this would change every time the above formula generated a new value, whereas I want something to stick as soon as it's output an answer.

Body:
The GOOGLEFINANCE function has some optional parameters - one of them is the start date.

If you request the exchange rate for a particular date then it won't change later on.

=GOOGLEFINANCE("Currency:AUDGBP", "price", "05/31/2019")

The output is a little different - a range with the date and value rather than a single cell, but the value for the exchange rate is correct and won't change.

You can then use the INDEX function to extract just the exchange rate

=INDEX(GOOGLEFINANCE("Currency:AUDGBP", "price", "05/31/2019"), 2, 2)

As described here


问:
Is there a way to classify a batch of images with the pretrained Inception-v3 network?
I'm trying to classify images with TensorFlow.

In the example code on GitHub is something like this:

```<code>predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data})
</code>```

Now, I'm looking for a solution for classifying multiple images in one go, because I'd like to compute the classification on my GPU, and I don't want to move the images to the GPU one by one, as that decreases performance.

A loop over all images around the sess.run(...) didn't do what I wanted: Every image was still sent to the GPU individually.

```<code>with tf.Session() as sess:
    softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
    for image in images:
        predictions = sess.run(softmax_tensor, {'DecodeJpeg:0': image})
</code>```

答:
Faced with the same task. The valid solution is feed model with batches of images as described here: https://www.tensorflow.org/tutorials/load_data/images

You create a pipeline using tf.data package and feed.
Take a note that in the tutorial there is eager mode, while it is no problem to do the same in a 'normal' mode.

Body:
I'm trying to classify images with TensorFlow.

In the example code on GitHub is something like this:

predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data})

Now, I'm looking for a solution for classifying multiple images in one go, because I'd like to compute the classification on my GPU, and I don't want to move the images to the GPU one by one, as that decreases performance.

A loop over all images around the sess.run(...) didn't do what I wanted: Every image was still sent to the GPU individually.

with tf.Session() as sess:
    softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
    for image in images:
        predictions = sess.run(softmax_tensor, {'DecodeJpeg:0': image})


问:
VSCode c++ task.json include path and libraries
IntelliSense uses c_cpp_properties.json >> includePath to find the headers for auto-completion, but I noticed I still need to specify the include path inside the task.json >> tasks >> args to build.

I found in the documentation that the includePath is pretty much the same path I would specify in "-I":

The paths that you specify for this setting are the same paths that
  you would send to your compiler via the -I switch. When your source
  files are parsed, the IntelliSense engine will prepend these paths to
  the files specified by your #include directives while attempting to
  resolve them. These paths are not searched recursively.*

link

Am I setting up VSCode correctly by specifying all the libraries and the includes directories inside the args of the build taks ? Or should it be done differently ?

Can someone explain using different words what's the difference between the includePath and browse ? The explanation link is not totally clear to me

Here is an example of my c_cpp_properties.json:

```<code>{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**",
                "D:/github/dependencies/SDL2-2.0.8/include"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "clang-x64",
            "browse": {
                "path": [
                    "${workspaceFolder}/**"
                ]
            }
        }
    ],
    "version": 4
}
</code>```

and task.json:

```<code>{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "shell",
            "command": "g++",
            "args": [
                "-g",
                "main2.cpp",
                "-ID:\\github\\dependencies\\SDL2-2.0.8\\include",
                "-LD:\\github\\dependencies\\SDL2-2.0.8\\lib\\x64",
                "-lSDL2main","-lSDL2", "-lopengl32",
                "-o",
                "test-sdl"
            ]
        }
    ],
    "group": {
        "kind": "build",
        "isDefault": true
    },
    "problemMatcher":"$gcc"
}
</code>```

Is a simple question, but I am new to VSCode (sorry).

答:
I'm also new to VS Code. Additionally, I have never build larger C++ projects. At least for now, I solved the building like this. (SEE BELOW)

I ended up doing this in my tasks.json

```<code> "tasks": [
    {
        "type": "shell",
        "label": "g++ build active file",
        "command": "${workspaceFolder}/buildMysorcery.sh",
        "options": {
            "cwd": "/usr/bin"
        }
    },
</code>```

(Seems like you're not able to escape white-spaces within the args property, https://github.com/Microsoft/vscode/issues/36733),

I deleted the args property and set the command property to run a script(buildMysorcery.sh) which simply does

```<code>#!/bin/bash

g++ fullpathtodir/hello.cpp -Wall -g $(sdl2-config --cflags --libs) -o fullpathtodir/hello
</code>```

Replace the fullpathtodir with your paths.

Body:
IntelliSense uses c_cpp_properties.json >> includePath to find the headers for auto-completion, but I noticed I still need to specify the include path inside the task.json >> tasks >> args to build.

I found in the documentation that the includePath is pretty much the same path I would specify in "-I":

The paths that you specify for this setting are the same paths that
  you would send to your compiler via the -I switch. When your source
  files are parsed, the IntelliSense engine will prepend these paths to
  the files specified by your #include directives while attempting to
  resolve them. These paths are not searched recursively.*

link

Am I setting up VSCode correctly by specifying all the libraries and the includes directories inside the args of the build taks ? Or should it be done differently ?

Can someone explain using different words what's the difference between the includePath and browse ? The explanation link is not totally clear to me

Here is an example of my c_cpp_properties.json:

{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**",
                "D:/github/dependencies/SDL2-2.0.8/include"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "clang-x64",
            "browse": {
                "path": [
                    "${workspaceFolder}/**"
                ]
            }
        }
    ],
    "version": 4
}

and task.json:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "shell",
            "command": "g++",
            "args": [
                "-g",
                "main2.cpp",
                "-ID:\\github\\dependencies\\SDL2-2.0.8\\include",
                "-LD:\\github\\dependencies\\SDL2-2.0.8\\lib\\x64",
                "-lSDL2main","-lSDL2", "-lopengl32",
                "-o",
                "test-sdl"
            ]
        }
    ],
    "group": {
        "kind": "build",
        "isDefault": true
    },
    "problemMatcher":"$gcc"
}

Is a simple question, but I am new to VSCode (sorry).

Body:
I'm also new to VS Code. Additionally, I have never build larger C++ projects. At least for now, I solved the building like this. (SEE BELOW)

I ended up doing this in my tasks.json

 "tasks": [
    {
        "type": "shell",
        "label": "g++ build active file",
        "command": "${workspaceFolder}/buildMysorcery.sh",
        "options": {
            "cwd": "/usr/bin"
        }
    },

(Seems like you're not able to escape white-spaces within the args property, https://github.com/Microsoft/vscode/issues/36733),

I deleted the args property and set the command property to run a script(buildMysorcery.sh) which simply does

#!/bin/bash

g++ fullpathtodir/hello.cpp -Wall -g $(sdl2-config --cflags --libs) -o fullpathtodir/hello

Replace the fullpathtodir with your paths.


问:
EF 4.1 Code-First and ASP MVC 3 problem when editing entities
I coded my entities with and created DbContext. Then I used MVC Scaffolding to create simple CRUD form for one entity. So far so good, it works as advertised.
Now, I decided to replace scaffolding-generated DbContext with simple Service wrapper over DbContext. All it does is delegate to DbContext.

However, now I have the problem on the following line when tried to edit the entity:

```<code>service.Entry(Book).State = EntityState.Modified;
</code>```

“An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key”

I managed to resolve it like this:

```<code>PropertyInfo[] infos = typeof(Book).GetProperties();
foreach (PropertyInfo info in infos)
            {
                info.SetValue(internalBook, info.GetValue(book, null), null);
            }
</code>```

Basically, I get the entity again and copy properties from entity that was handed to me by View. I have also noted that when I obtain the entity, it is proxy, and the one handed to me is not.

What could be the problem?

Here is my service class:

```<code> public class BookService
{

    private DbContext context;
    private DbSet<Book> set;

    public BookService(DbContext context, DbSet<Book> set) {
        this.context = context;
        this.set = set;
    }

    public IQueryable<Book> Query
    {
        get { return set; }
    }

    public virtual void Add(Book entity)
    {
        set.Add(entity);
    }

    public virtual void Remove(Book entity)
    {
        set.Remove(entity);
    }

    public virtual void SaveChanges() {
        context.SaveChanges();
    }

    public List<Book> All() {
        List<Book> books = set.ToList();
        return books;
    }

    public DbEntityEntry<Book> Entry(Book book) {
        return context.Entry(book);
    }
}
</code>```

Here is the Edit action  Controller code. I have commented the original, scaffolding-generated code:

```<code>    [HttpPost]
    public ActionResult Edit(Book book)
    {
        Book internalBook = service.Query.Single(b => b.Id == book.Id);
        if (ModelState.IsValid)
        {
            PropertyInfo[] infos = typeof(Book).GetProperties();
            foreach (PropertyInfo info in infos)
            {
                info.SetValue(internalBook, info.GetValue(book, null), null);
            }
            service.Entry(internalBook).State = EntityState.Modified;
            service.SaveChanges();

            //context.Entry(book).State = EntityState.Modified;
            //context.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(book);
    }
</code>```

答:
You can't attach the book because you have loaded it in the same context. General approach is this:</p>

```<code>[HttpPost]
public ActionResult Edit(Book book)
{
    Book internalBook = service.Query.Single(b => b.Id == book.Id);
    if (ModelState.IsValid)
    {
        service.Entry(internalBook).CurrentValues.SetValues(book);
        service.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(book);
}
</code>```

Body:
I coded my entities with and created DbContext. Then I used MVC Scaffolding to create simple CRUD form for one entity. So far so good, it works as advertised.
Now, I decided to replace scaffolding-generated DbContext with simple Service wrapper over DbContext. All it does is delegate to DbContext.

However, now I have the problem on the following line when tried to edit the entity:

service.Entry(Book).State = EntityState.Modified;

“An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key”

I managed to resolve it like this:

PropertyInfo[] infos = typeof(Book).GetProperties();
foreach (PropertyInfo info in infos)
            {
                info.SetValue(internalBook, info.GetValue(book, null), null);
            }

Basically, I get the entity again and copy properties from entity that was handed to me by View. I have also noted that when I obtain the entity, it is proxy, and the one handed to me is not.

What could be the problem?

Here is my service class:

 public class BookService
{

    private DbContext context;
    private DbSet<Book> set;

    public BookService(DbContext context, DbSet<Book> set) {
        this.context = context;
        this.set = set;
    }

    public IQueryable<Book> Query
    {
        get { return set; }
    }

    public virtual void Add(Book entity)
    {
        set.Add(entity);
    }

    public virtual void Remove(Book entity)
    {
        set.Remove(entity);
    }

    public virtual void SaveChanges() {
        context.SaveChanges();
    }

    public List<Book> All() {
        List<Book> books = set.ToList();
        return books;
    }

    public DbEntityEntry<Book> Entry(Book book) {
        return context.Entry(book);
    }
}

Here is the Edit action  Controller code. I have commented the original, scaffolding-generated code:

    [HttpPost]
    public ActionResult Edit(Book book)
    {
        Book internalBook = service.Query.Single(b => b.Id == book.Id);
        if (ModelState.IsValid)
        {
            PropertyInfo[] infos = typeof(Book).GetProperties();
            foreach (PropertyInfo info in infos)
            {
                info.SetValue(internalBook, info.GetValue(book, null), null);
            }
            service.Entry(internalBook).State = EntityState.Modified;
            service.SaveChanges();

            //context.Entry(book).State = EntityState.Modified;
            //context.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(book);
    }

Body:
You can't attach the book because you have loaded it in the same context. General approach is this:

[HttpPost]
public ActionResult Edit(Book book)
{
    Book internalBook = service.Query.Single(b => b.Id == book.Id);
    if (ModelState.IsValid)
    {
        service.Entry(internalBook).CurrentValues.SetValues(book);
        service.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(book);
}