问:
x++ script that do not return correct count
I have a x++ script which aims to count records from a select query and later on be updated.

This is the original question for reference: convert SQL Query with Join to X++ Dynamics AX scripting

Initially, I have a SQL Query counterpart of it and it is resulting to 50 rows / records, when I convert it to X++ , it is not counting or extracting the same number of records,

Here is is the x++ script

```<code>static void Job(Args _args)
{

    Table1 table1;
    Table2 table2;
    Table3 table3;
    Table4 table4;
    Table5 table5;
    int i = 0;
    while select forUpdate table1
       join table2 where table1.field1 == table2.field1
       join table3 where table1.field2 == table3.field2
       join table4 where table3.field3 == table4.field3
       join table5 where table3.category == table5.recid
       && table1.location  == 'asia' && table2.modtye == 2
       && table3.discount == 'sample'
       && table4.name ==  'hello'
       &&(table5.name == 'one' || table5.name == 'two' || table5.name == 'three')
    {
            if (table1)
            {
                 i = i + 1;
            }
    }
    info(strfmt("Total : %1",i));
}
</code>```

Pls help, where did i go wrong it think it's with this part

```<code>if (table1)
</code>```

I also tried trimming down the codes to know where the problem arise,

```<code> while select forUpdate table1
           join table2 where table1.field1 == table2.field1
           && table1.location  == 'asia' && table2.modtye == 2
</code>```

This part dont return result already... when I include the

```<code> && table1.location  == 'asia' && table2.modtye == 2
</code>```

So i think, the problem is there, but what is wrong with the code?

I based my codes actually from this tutorial link

https://community.dynamics.com/ax/b/dynamicsaxtipoftheday/archive/2014/09/05/quickly-update-data-through-x-scripts

答:
I suggest a simple explanation, maybe the SQL returns rows from a several companies or partitions?

AX by default returns row for the current partition and company curext() only.

If you use the crosscompany option to the select it will scan cross companies:

```<code>while select crosscompany table1 ...
</code>```

You do not need to test whether table1 is found, if not found it will not enter the loop.

Also, if your sole purpose is to count the number of records it is wasteful to count manually, a single select will do:

```<code>select firstOnly /*crosscompany*/ count(RecId) from table1
   exists join table2 where table1.field1 == table2.field1
   exists join table3 where table1.field2 == table3.field2
   exists join table4 where table3.field3 == table4.field3
   exists join table5 where table3.category == table5.recid
     && table1.location  == 'asia' && table2.modtye == 2
     && table3.discount == 'sample'
     && table4.name ==  'hello'
     &&(table5.name == 'one' || table5.name == 'two' || table5.name == 'three');
info(strfmt("Total : %1", table1.RecId));
</code>```

Body:
I have a x++ script which aims to count records from a select query and later on be updated.

This is the original question for reference: convert SQL Query with Join to X++ Dynamics AX scripting

Initially, I have a SQL Query counterpart of it and it is resulting to 50 rows / records, when I convert it to X++ , it is not counting or extracting the same number of records,

Here is is the x++ script

static void Job(Args _args)
{

    Table1 table1;
    Table2 table2;
    Table3 table3;
    Table4 table4;
    Table5 table5;
    int i = 0;
    while select forUpdate table1
       join table2 where table1.field1 == table2.field1
       join table3 where table1.field2 == table3.field2
       join table4 where table3.field3 == table4.field3
       join table5 where table3.category == table5.recid
       && table1.location  == 'asia' && table2.modtye == 2
       && table3.discount == 'sample'
       && table4.name ==  'hello'
       &&(table5.name == 'one' || table5.name == 'two' || table5.name == 'three')
    {
            if (table1)
            {
                 i = i + 1;
            }
    }
    info(strfmt("Total : %1",i));
}

Pls help, where did i go wrong it think it's with this part

if (table1)

I also tried trimming down the codes to know where the problem arise,

 while select forUpdate table1
           join table2 where table1.field1 == table2.field1
           && table1.location  == 'asia' && table2.modtye == 2

This part dont return result already... when I include the

 && table1.location  == 'asia' && table2.modtye == 2

So i think, the problem is there, but what is wrong with the code?

I based my codes actually from this tutorial link

https://community.dynamics.com/ax/b/dynamicsaxtipoftheday/archive/2014/09/05/quickly-update-data-through-x-scripts

Body:
I suggest a simple explanation, maybe the SQL returns rows from a several companies or partitions?

AX by default returns row for the current partition and company curext() only.

If you use the crosscompany option to the select it will scan cross companies:

while select crosscompany table1 ...

You do not need to test whether table1 is found, if not found it will not enter the loop.

Also, if your sole purpose is to count the number of records it is wasteful to count manually, a single select will do:

select firstOnly /*crosscompany*/ count(RecId) from table1
   exists join table2 where table1.field1 == table2.field1
   exists join table3 where table1.field2 == table3.field2
   exists join table4 where table3.field3 == table4.field3
   exists join table5 where table3.category == table5.recid
     && table1.location  == 'asia' && table2.modtye == 2
     && table3.discount == 'sample'
     && table4.name ==  'hello'
     &&(table5.name == 'one' || table5.name == 'two' || table5.name == 'three');
info(strfmt("Total : %1", table1.RecId));


来源: stackexchange

问:
NSDate date returns 2h less than it should
When i call <code>[NSDate date]</code> it returns 2 hours less than it should. I've checked my computer clock settings and they are all ok. I've checked settings in iPhone and time zone and clock are all OK. Even simulator shows correct time on top toolbar. But when I try to log current date it shows 2 hours less than it should. I ran out of ideas where to look. </p>

答:
All dates returned by [NSDate date] are in the GMT time zone.

When you use any NSDateFormatter, just set the time zone and it will print out the correct time.

ContentLicense: CC BY-SA 3.0

Body: When i call [NSDate date] it returns 2 hours less than it should. I've checked my computer clock settings and they are all ok. I've checked settings in iPhone and time zone and clock are all OK. Even simulator shows correct time on top toolbar. But when I try to log current date it shows 2 hours less than it should. I ran out of ideas where to look.


问:
How to increment string within a certain range
I have a string like '"F01" le code le "F16"' I want to parse this string to get a new string contains "F01", "F02, "F03" ... until "F16".

I tired to parse the string by quotes and hope to loop through the first code till the last code. And then tried to increment the code via chr() and ord(). But can't seem to figure it out.

import re
s = '"F01" le code le "F16"'

s_q = re.findall('"([^"]*)"', s)

first_code = s_q[0]
last_code = s_q[1]
ch_for_increment = s_q[0][-1:]
ch_for_the_rest = s_q[0][:-1]
print(ch_for_the_rest + chr(ord(ch) + 1))
```

答:
You are almost there.
After extracting the start and end of range from s_q, you can use range to generate your list like so.

```<code>import re
s = '"F01" le code le "F16"'

s_q = re.findall('"([^"]*)"', s)
#['F01', 'F16']

#Extract the first and last index of range from list
first_code = int(s_q[0][1:])
#1
last_code = int(s_q[1][1:])
#16

#Create the result list
li = ['F{:02d}'.format(item) for item in range(first_code, last_code+1)]

#Get the final string with quotes
result = '"{}"'.format('" "'.join(li))

print(result)
</code>```

The output will be

```<code>"F01" "F02" "F03" "F04" "F05" "F06" "F07" "F08" "F09" "F10" "F11" "F12" "F13" "F14" "F15" "F16"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You are almost there.
After extracting the start and end of range from s_q, you can use range to generate your list like so.

import re
s = '"F01" le code le "F16"'

s_q = re.findall('"([^"]*)"', s)
#['F01', 'F16']

#Extract the first and last index of range from list
first_code = int(s_q[0][1:])
#1
last_code = int(s_q[1][1:])
#16

#Create the result list
li = ['F{:02d}'.format(item) for item in range(first_code, last_code+1)]

#Get the final string with quotes
result = '"{}"'.format('" "'.join(li))

print(result)

The output will be

"F01" "F02" "F03" "F04" "F05" "F06" "F07" "F08" "F09" "F10" "F11" "F12" "F13" "F14" "F15" "F16"


问:
converted_model.tflite does not encode a valid TensorFlowLite model: Could not open file_path. The model is not a valid Flatbuffer file
I am trying to load converted_tflite.tflite from the assets directory.

It's giving me an error java.lang.IllegalArgumentException: Contents of /file:/android_asset/converted_model.tflite does not encode a valid TensorFlowLite model: Could not open '/file:/android_asset/converted_model.tflite'.The model is not a valid Flatbuffer file

```<code>File file = new File("file:///android_asset/converted_model.tflite");
        try (Interpreter interpreter = new Interpreter(file)) {
            interpreter.run(inputData, output);
            Log.d("TF LOG", output);
        }catch(Exception e){
            e.printStackTrace();
}
</code>```

What I tried based on the stackoverflow answers

```<code>aaptOptions {
    noCompress "tflite"
}
</code>```

tensoflow-lite nighty version

```<code>implementation 'org.tensorflow:tensorflow-lite:0.1.2-nightly'
</code>```

答:
I used tensorflow-nighty build gradle version 0.1.2

```<code>    implementation 'org.tensorflow:tensorflow-lite:0.1.2-nightly'
</code>```

To load the model

```<code>/** Memory-map the model file in Assets. */
private static MappedByteBuffer loadModelFile(AssetManager assets, String modelFilename)
        throws IOException {
    AssetFileDescriptor fileDescriptor = assets.openFd(modelFilename);
    FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
    FileChannel fileChannel = inputStream.getChannel();
    long startOffset = fileDescriptor.getStartOffset();
    long declaredLength = fileDescriptor.getDeclaredLength();
    return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
}
</code>```

Body:
I am trying to load converted_tflite.tflite from the assets directory.

It's giving me an error java.lang.IllegalArgumentException: Contents of /file:/android_asset/converted_model.tflite does not encode a valid TensorFlowLite model: Could not open '/file:/android_asset/converted_model.tflite'.The model is not a valid Flatbuffer file

File file = new File("file:///android_asset/converted_model.tflite");
        try (Interpreter interpreter = new Interpreter(file)) {
            interpreter.run(inputData, output);
            Log.d("TF LOG", output);
        }catch(Exception e){
            e.printStackTrace();
}

What I tried based on the stackoverflow answers

aaptOptions {
    noCompress "tflite"
}

tensoflow-lite nighty version

implementation 'org.tensorflow:tensorflow-lite:0.1.2-nightly'

Body:
I used tensorflow-nighty build gradle version 0.1.2

    implementation 'org.tensorflow:tensorflow-lite:0.1.2-nightly'

To load the model

/** Memory-map the model file in Assets. */
private static MappedByteBuffer loadModelFile(AssetManager assets, String modelFilename)
        throws IOException {
    AssetFileDescriptor fileDescriptor = assets.openFd(modelFilename);
    FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
    FileChannel fileChannel = inputStream.getChannel();
    long startOffset = fileDescriptor.getStartOffset();
    long declaredLength = fileDescriptor.getDeclaredLength();
    return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
}


问:
Laravel Relation returning null result
My Laravel relation is returning a null result.  Can anyone help what i am doing wrong.

Model code is :

```<code>public function title()
{
    $branch_id=session()->get('lbranch','0');
    return $this->hasOne('App\Accounts','code','supp_code')
        ->select('title')->where('branchid','=',$branch_id);
}
</code>```

and Controller code is :

```<code>   $data = Purchase::with('title')
       ->where('purchases.branchid',$branch_id)
       ->select('purchases.*',
           DB::raw('(CASE
                WHEN purchases.posted = "1" THEN "Posted"
                ELSE "Unposted"
                END) AS status'))
       ->latest()->get();
</code>```

the queries generated are :

```<code>select `purchases`.*, (CASE
     WHEN purchases.posted = "1" THEN "Posted"
     ELSE "Unposted"
     END) AS status from `purchases`
     where `purchases`.`branchid` = 22 order by `created_at` desc

select `title` from `accounts` where `branchid` = 22 and `accounts`.`code` in (100)
</code>```

UPDATE :
If I use join, the following query is working fine :

```<code>$data = DB::table('purchases')
    ->where('purchases.branchid',$branch_id)
    ->where('accounts.branchid',$branch_id)
    ->leftjoin('accounts','purchases.supp_code','=','accounts.code')
    ->select('purchases.*',
        DB::raw('(CASE
            WHEN purchases.posted = "1" THEN "Posted"
            ELSE "Unposted"
            END) AS status'),
        'accounts.title')
    ->latest()->get();
</code>```

答:
It seems you have issue in your relationship definition. Please do confirm the Model name for the account. It should be Account instead of Accounts. But still you should confirm in your application.

```<code>public function title()
{
    ---
    return $this->hasOne('App\Accounts','code','supp_code')
        ---;
}
</code>```

Should be

```<code>public function title()
{
    ---
    return $this->hasOne('App\Account','code','supp_code')
        ---;
}
</code>```

However I try to run your code and it working fine for me.

Here is what I have tried.

App\Models\Purchase.php

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Purchase extends Model
{
    /**
     *  get model table name.
     *
     *  @var string
     */
    public $table = "purchases";

    public function title()
    {
        $branch_id=22;
        return $this->hasOne('App\Models\Account','code','supp_code')
            ->select('title')->where('branchid','=',$branch_id);
    }

}
</code>```

App\Models\Account.php

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Account extends Model
{
    /**
     *  get model table name.
     *
     *  @var string
     */
    public $table = "accounts";

}
</code>```

in route file.

```<code><?php

Route::get('/', function(){

    $branch_id = 22;

    $data = Purchase::with('title')
    ->where('purchases.branchid',$branch_id)
    ->select('purchases.*',
        \DB::raw('(CASE
             WHEN purchases.posted = "1" THEN "Posted"
             ELSE "Unposted"
             END) AS status'))
    ->latest()->get();

    dd($data->toArray());

    $data = \DB::table('purchases')
    ->where('purchases.branchid',$branch_id)
    ->where('accounts.branchid',$branch_id)
    ->leftjoin('accounts','purchases.supp_code','=','accounts.code')
    ->select('purchases.*',
        \DB::raw('(CASE
            WHEN purchases.posted = "1" THEN "Posted"
            ELSE "Unposted"
            END) AS status'),
        'accounts.title')
    ->latest()->get();

    dd($data);
});
</code>```

Both query working for me. And returning the desire result.

Query1

```<code>array:2 [▼
  0 => {#436 ▼
    +"id": 6
    +"refno": 21
    +"supp_code": 100
    +"total": 41241
    +"posted": 1
    +"date": "2019-05-25 22:53:00"
    +"branchid": 22
    +"created_at": "2019-05-25 22:53:00"
    +"updated_at": "2019-05-25 22:53:00"
    +"status": "Posted"
    +"title": "test"
  }
  1 => {#438 ▼
    +"id": 3
    +"refno": null
    +"supp_code": 100
    +"total": 3114
    +"posted": null
    +"date": "2019-05-25 22:53:00"
    +"branchid": 22
    +"created_at": "2019-05-25 22:53:00"
    +"updated_at": "2019-05-25 22:53:00"
    +"status": "Unposted"
    +"title": "test"
  }
]
</code>```

Query2

```<code>array:2 [▼
  0 => {#436 ▼
    +"id": 3
    +"refno": null
    +"supp_code": 100
    +"total": 3114
    +"posted": null
    +"date": "2019-05-25 22:53:00"
    +"branchid": 22
    +"created_at": "2019-05-25 22:53:00"
    +"updated_at": "2019-05-25 22:53:00"
    +"status": "Unposted"
    +"title": "test"
  }
  1 => {#438 ▼
    +"id": 6
    +"refno": 21
    +"supp_code": 100
    +"total": 41241
    +"posted": 1
    +"date": "2019-05-25 22:53:00"
    +"branchid": 22
    +"created_at": "2019-05-25 22:53:00"
    +"updated_at": "2019-05-25 22:53:00"
    +"status": "Posted"
    +"title": "test"
  }
]
</code>```

Database SQL

```<code>CREATE TABLE `accounts` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `code` int(11) DEFAULT NULL,
  `title` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `branchid` int(11) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `accounts` VALUES (3,100,'test',22,NULL,NULL),(4,2,'testsetestes',34,NULL,NULL),(5,2,'testest seat',456,NULL,NULL),(6,3,'testse aeta ',22,NULL,NULL);

CREATE TABLE `purchases` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `refno` int(11) DEFAULT NULL,
  `supp_code` int(11) DEFAULT NULL,
  `total` int(11) DEFAULT NULL,
  `posted` int(11) DEFAULT NULL,
  `date` timestamp NULL DEFAULT NULL,
  `branchid` int(11) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `purchases` VALUES (3,NULL,100,3114,NULL,'2019-05-25 22:53:00',22,'2019-05-25 22:53:00','2019-05-25 22:53:00'),(4,23,101,4324,1,'2019-05-25 22:53:00',23,'2019-05-25 22:53:00','2019-05-25 22:53:00'),(5,22,101,32424,0,'2019-05-25 22:53:00',21,'2019-05-25 22:53:00','2019-05-25 22:53:00'),(6,21,100,41241,1,'2019-05-25 22:53:00',22,'2019-05-25 22:53:00','2019-05-25 22:53:00');
</code>```

Edits:

Tryied running your code.. here is the changes suggested.

PurchaseController

```<code>public function index()
    {
        //
        $branch_id = 22;

        $data = Purchase::with('account')
            ->where('purchases.branchid',$branch_id)
            ->select('purchases.*',
                \DB::raw('(CASE
             WHEN purchases.posted = "1" THEN "Posted"
             ELSE "Unposted"
             END) AS status'))
            ->latest()->get();

        dd($data->toArray());

        /*$data = \DB::table('purchases')
            ->where('purchases.branchid',$branch_id)
            ->where('accounts.branchid',$branch_id)
            ->leftjoin('accounts','purchases.supp_code','=','accounts.code')
            ->select('purchases.*',
                \DB::raw('(CASE
            WHEN purchases.posted = "1" THEN "Posted"
            ELSE "Unposted"
            END) AS status'),
                'accounts.title')
            ->latest()->get();

        dd($data);*/
    }
</code>```

Purchage Model

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Purchase extends Model
{
    //
    public $table = "purchases";

    public function account()
    {
        $branch_id=22;

        return $this->hasOne('App\Account','code','supp_code')
            ->where('branchid', $branch_id);
    }
}
</code>```

Result:

```<code>array:2 [▼
  0 => array:11 [▼
    "id" => 3
    "refno" => 24
    "supp_code" => 100
    "total" => 3114
    "posted" => null
    "date" => "2019-05-25 22:53:00"
    "branchid" => 22
    "created_at" => "2019-05-25 22:53:00"
    "updated_at" => "2019-05-25 22:53:00"
    "status" => "Unposted"
    "account" => array:6 [▼
      "id" => 3
      "code" => 100
      "title" => "test"
      "branchid" => 22
      "created_at" => null
      "updated_at" => null
    ]
  ]
  1 => array:11 [▼
    "id" => 6
    "refno" => 21
    "supp_code" => 100
    "total" => 41241
    "posted" => 1
    "date" => "2019-05-25 22:53:00"
    "branchid" => 22
    "created_at" => "2019-05-25 22:53:00"
    "updated_at" => "2019-05-25 22:53:00"
    "status" => "Posted"
    "account" => array:6 [▼
      "id" => 3
      "code" => 100
      "title" => "test"
      "branchid" => 22
      "created_at" => null
      "updated_at" => null
    ]
  ]
]
</code>```

Title: Laravel Relation returning null result

Body:
My Laravel relation is returning a null result.  Can anyone help what i am doing wrong.

Model code is :

public function title()
{
    $branch_id=session()->get('lbranch','0');
    return $this->hasOne('App\Accounts','code','supp_code')
        ->select('title')->where('branchid','=',$branch_id);
}

and Controller code is :

   $data = Purchase::with('title')
       ->where('purchases.branchid',$branch_id)
       ->select('purchases.*',
           DB::raw('(CASE
                WHEN purchases.posted = "1" THEN "Posted"
                ELSE "Unposted"
                END) AS status'))
       ->latest()->get();

the queries generated are :

select `purchases`.*, (CASE
     WHEN purchases.posted = "1" THEN "Posted"
     ELSE "Unposted"
     END) AS status from `purchases`
     where `purchases`.`branchid` = 22 order by `created_at` desc

select `title` from `accounts` where `branchid` = 22 and `accounts`.`code` in (100)

UPDATE :
If I use join, the following query is working fine :

$data = DB::table('purchases')
    ->where('purchases.branchid',$branch_id)
    ->where('accounts.branchid',$branch_id)
    ->leftjoin('accounts','purchases.supp_code','=','accounts.code')
    ->select('purchases.*',
        DB::raw('(CASE
            WHEN purchases.posted = "1" THEN "Posted"
            ELSE "Unposted"
            END) AS status'),
        'accounts.title')
    ->latest()->get();

Body:
It seems you have issue in your relationship definition. Please do confirm the Model name for the account. It should be Account instead of Accounts. But still you should confirm in your application.

public function title()
{
    ---
    return $this->hasOne('App\Accounts','code','supp_code')
        ---;
}

Should be

public function title()
{
    ---
    return $this->hasOne('App\Account','code','supp_code')
        ---;
}

However I try to run your code and it working fine for me.

Here is what I have tried.

App\Models\Purchase.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Purchase extends Model
{
    /**
     *  get model table name.
     *
     *  @var string
     */
    public $table = "purchases";

    public function title()
    {
        $branch_id=22;
        return $this->hasOne('App\Models\Account','code','supp_code')
            ->select('title')->where('branchid','=',$branch_id);
    }

}

App\Models\Account.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Account extends Model
{
    /**
     *  get model table name.
     *
     *  @var string
     */
    public $table = "accounts";

}

in route file.

<?php

Route::get('/', function(){

    $branch_id = 22;

    $data = Purchase::with('title')
    ->where('purchases.branchid',$branch_id)
    ->select('purchases.*',
        \DB::raw('(CASE
             WHEN purchases.posted = "1" THEN "Posted"
             ELSE "Unposted"
             END) AS status'))
    ->latest()->get();

    dd($data->toArray());

    $data = \DB::table('purchases')
    ->where('purchases.branchid',$branch_id)
    ->where('accounts.branchid',$branch_id)
    ->leftjoin('accounts','purchases.supp_code','=','accounts.code')
    ->select('purchases.*',
        \DB::raw('(CASE
            WHEN purchases.posted = "1" THEN "Posted"
            ELSE "Unposted"
            END) AS status'),
        'accounts.title')
    ->latest()->get();

    dd($data);
});

Both query working for me. And returning the desire result.

Query1

array:2 [▼
  0 => {#436 ▼
    +"id": 6
    +"refno": 21
    +"supp_code": 100
    +"total": 41241
    +"posted": 1
    +"date": "2019-05-25 22:53:00"
    +"branchid": 22
    +"created_at": "2019-05-25 22:53:00"
    +"updated_at": "2019-05-25 22:53:00"
    +"status": "Posted"
    +"title": "test"
  }
  1 => {#438 ▼
    +"id": 3
    +"refno": null
    +"supp_code": 100
    +"total": 3114
    +"posted": null
    +"date": "2019-05-25 22:53:00"
    +"branchid": 22
    +"created_at": "2019-05-25 22:53:00"
    +"updated_at": "2019-05-25 22:53:00"
    +"status": "Unposted"
    +"title": "test"
  }
]

Query2

array:2 [▼
  0 => {#436 ▼
    +"id": 3
    +"refno": null
    +"supp_code": 100
    +"total": 3114
    +"posted": null
    +"date": "2019-05-25 22:53:00"
    +"branchid": 22
    +"created_at": "2019-05-25 22:53:00"
    +"updated_at": "2019-05-25 22:53:00"
    +"status": "Unposted"
    +"title": "test"
  }
  1 => {#438 ▼
    +"id": 6
    +"refno": 21
    +"supp_code": 100
    +"total": 41241
    +"posted": 1
    +"date": "2019-05-25 22:53:00"
    +"branchid": 22
    +"created_at": "2019-05-25 22:53:00"
    +"updated_at": "2019-05-25 22:53:00"
    +"status": "Posted"
    +"title": "test"
  }
]

Database SQL

CREATE TABLE `accounts` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `code` int(11) DEFAULT NULL,
  `title` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `branchid` int(11) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `accounts` VALUES (3,100,'test',22,NULL,NULL),(4,2,'testsetestes',34,NULL,NULL),(5,2,'testest seat',456,NULL,NULL),(6,3,'testse aeta ',22,NULL,NULL);

CREATE TABLE `purchases` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `refno` int(11) DEFAULT NULL,
  `supp_code` int(11) DEFAULT NULL,
  `total` int(11) DEFAULT NULL,
  `posted` int(11) DEFAULT NULL,
  `date` timestamp NULL DEFAULT NULL,
  `branchid` int(11) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `purchases` VALUES (3,NULL,100,3114,NULL,'2019-05-25 22:53:00',22,'2019-05-25 22:53:00','2019-05-25 22:53:00'),(4,23,101,4324,1,'2019-05-25 22:53:00',23,'2019-05-25 22:53:00','2019-05-25 22:53:00'),(5,22,101,32424,0,'2019-05-25 22:53:00',21,'2019-05-25 22:53:00','2019-05-25 22:53:00'),(6,21,100,41241,1,'2019-05-25 22:53:00',22,'2019-05-25 22:53:00','2019-05-25 22:53:00');

Edits:

Tryied running your code.. here is the changes suggested.

PurchaseController

public function index()
    {
        //
        $branch_id = 22;

        $data = Purchase::with('account')
            ->where('purchases.branchid',$branch_id)
            ->select('purchases.*',
                \DB::raw('(CASE
             WHEN purchases.posted = "1" THEN "Posted"
             ELSE "Unposted"
             END) AS status'))
            ->latest()->get();

        dd($data->toArray());

        /*$data = \DB::table('purchases')
            ->where('purchases.branchid',$branch_id)
            ->where('accounts.branchid',$branch_id)
            ->leftjoin('accounts','purchases.supp_code','=','accounts.code')
            ->select('purchases.*',
                \DB::raw('(CASE
            WHEN purchases.posted = "1" THEN "Posted"
            ELSE "Unposted"
            END) AS status'),
                'accounts.title')
            ->latest()->get();

        dd($data);*/
    }

Purchage Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Purchase extends Model
{
    //
    public $table = "purchases";

    public function account()
    {
        $branch_id=22;

        return $this->hasOne('App\Account','code','supp_code')
            ->where('branchid', $branch_id);
    }
}

Result:

array:2 [▼
  0 => array:11 [▼
    "id" => 3
    "refno" => 24
    "supp_code" => 100
    "total" => 3114
    "posted" => null
    "date" => "2019-05-25 22:53:00"
    "branchid" => 22
    "created_at" => "2019-05-25 22:53:00"
    "updated_at" => "2019-05-25 22:53:00"
    "status" => "Unposted"
    "account" => array:6 [▼
      "id" => 3
      "code" => 100
      "title" => "test"
      "branchid" => 22
      "created_at" => null
      "updated_at" => null
    ]
  ]
  1 => array:11 [▼
    "id" => 6
    "refno" => 21
    "supp_code" => 100
    "total" => 41241
    "posted" => 1
    "date" => "2019-05-25 22:53:00"
    "branchid" => 22
    "created_at" => "2019-05-25 22:53:00"
    "updated_at" => "2019-05-25 22:53:00"
    "status" => "Posted"
    "account" => array:6 [▼
      "id" => 3
      "code" => 100
      "title" => "test"
      "branchid" => 22
      "created_at" => null
      "updated_at" => null
    ]
  ]
]


问:
JSONDecodeError with Scrapy: Expecting value: line 1 column 1 (char 0)
I am using requests in order to fetch and parse some data scraped using Scrapy with Scrapyrt (real time scraping).

This is how I do it:

```<code>#pass spider to requests parameters #
params = {
        'spider_name': spider,
        'start_requests':True
        }
# scrape items
response = requests.get('http://scrapyrt:9080/crawl.json', params)
print ('RESPONSE JSON',response.json())
data = response.json()
</code>```

As per Scrapy documentation, with 'start_requests' parameter set as True, the spider automatically requests urls and passes the response to the parse method which is the default method used for parsing requests.

start_requests

type: boolean

optional

Whether spider should execute Scrapy.Spider.start_requests method. start_requests are executed by default when you run Scrapy Spider normally without ScrapyRT, but this method is NOT executed in API by default. By default we assume that spider is expected to crawl ONLY url provided in parameters without making any requests to start_urls defined in Spider class. start_requests argument overrides this behavior. If this argument is present API will execute start_requests Spider method.

But the setup is not working. Log:

```<code>[2019-05-19 06:11:14,835: DEBUG/ForkPoolWorker-4] Starting new HTTP connection (1): scrapyrt:9080
[2019-05-19 06:11:15,414: DEBUG/ForkPoolWorker-4] http://scrapyrt:9080 "GET /crawl.json?spider_name=precious_tracks&start_requests=True HTTP/1.1" 500 7784
[2019-05-19 06:11:15,472: ERROR/ForkPoolWorker-4] Task project.api.routes.background.scrape_allmusic[87dbd825-dc1c-4789-8ee0-4151e5821798] raised unexpected: JSONDecodeError('Expecting value: line 1 column 1 (char 0)',)
Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/celery/app/trace.py", line 382, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/usr/lib/python3.6/site-packages/celery/app/trace.py", line 641, in __protected_call__
    return self.run(*args, **kwargs)
  File "/usr/src/app/project/api/routes/background.py", line 908, in scrape_allmusic
    print ('RESPONSE JSON',response.json())
  File "/usr/lib/python3.6/site-packages/requests/models.py", line 897, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

答:
The error was due to a bug with Twisted 19.2.0, a scrapyrt dependency, which assumed response to be of wrong type.

Once I installed Twisted==18.9.0, it worked.

Body:
I am using requests in order to fetch and parse some data scraped using Scrapy with Scrapyrt (real time scraping).

This is how I do it:

#pass spider to requests parameters #
params = {
        'spider_name': spider,
        'start_requests':True
        }
# scrape items
response = requests.get('http://scrapyrt:9080/crawl.json', params)
print ('RESPONSE JSON',response.json())
data = response.json()

As per Scrapy documentation, with 'start_requests' parameter set as True, the spider automatically requests urls and passes the response to the parse method which is the default method used for parsing requests.

start_requests

type: boolean

optional

Whether spider should execute Scrapy.Spider.start_requests method. start_requests are executed by default when you run Scrapy Spider normally without ScrapyRT, but this method is NOT executed in API by default. By default we assume that spider is expected to crawl ONLY url provided in parameters without making any requests to start_urls defined in Spider class. start_requests argument overrides this behavior. If this argument is present API will execute start_requests Spider method.

But the setup is not working. Log:

[2019-05-19 06:11:14,835: DEBUG/ForkPoolWorker-4] Starting new HTTP connection (1): scrapyrt:9080
[2019-05-19 06:11:15,414: DEBUG/ForkPoolWorker-4] http://scrapyrt:9080 "GET /crawl.json?spider_name=precious_tracks&start_requests=True HTTP/1.1" 500 7784
[2019-05-19 06:11:15,472: ERROR/ForkPoolWorker-4] Task project.api.routes.background.scrape_allmusic[87dbd825-dc1c-4789-8ee0-4151e5821798] raised unexpected: JSONDecodeError('Expecting value: line 1 column 1 (char 0)',)
Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/celery/app/trace.py", line 382, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/usr/lib/python3.6/site-packages/celery/app/trace.py", line 641, in __protected_call__
    return self.run(*args, **kwargs)
  File "/usr/src/app/project/api/routes/background.py", line 908, in scrape_allmusic
    print ('RESPONSE JSON',response.json())
  File "/usr/lib/python3.6/site-packages/requests/models.py", line 897, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)


问:
Blocking locks created due to inactive session in last 2 months
How to find the details of blocking locks due to inactive session for last 2 months ? Please help with a PL -sql code</p>

答:
```<code>select * from dba_dml_locks where session_id = :p_sid;

select * from dba_ddl_locks where session_id = :p_sid;
</code>```


问:
VPS hosting and root access
I've got rather poor knowledge of *nix virtualization capabilities and trying to clarify one thing. If one has root on host machine, does it always mean that he has root on all VMs of that host? If yes, then could there be a bogus setup where this is not true?

I'm asking cause I heard two different answers to that question from two different admins. One said that he has root to everything, another claimed that he don't and he needs my password.

Please share your experience with VPS hosting providers, do they have roots to your environment?

It's not that I'm afraid to lose the data, just want to have some insights and words to google for ;-)
Thanks everyone!

答:
Ultimately, having root on the VM host is the same as having physical access to a regular machine.  They can't just "login" to the VM as root (well, you can with some virtualisation technologies like OpenVZ) but they can get into the VM's filesystem, change the root password (or install something to capture the password) and go from there.

You need to have exactly the same trust in your VPS hosting service provider as you do with your colo provider, because they have exactly the same level of access and ability to do bad things to your service.

OwnerDisplayName: clorz

ContentLicense: CC BY-SA 2.5

Title: VPS hosting and root access

LastEditorDisplayName: clorz

OwnerDisplayName: womble


问:
What does the "declare a static final serialVersionUID" warning mean and how to fix?

Possible Duplicate:

  What does it mean: The serializable class does not declare a static final serialVersionUID field?

Java compiler warning: The serializable class [*****] does not declare a static final serialVersionUID field of type long.

Why? How to fix it?

答:
Declare it like that:

```<code>private static final long serialVersionUID = -4673040337179571462L;
</code>```

Its required by serializable interface.

Body:
Declare it like that:

private static final long serialVersionUID = -4673040337179571462L;

Its required by serializable interface.


问:
POST an item to JSON server db- Angular
I'm trying to POST an Item to my db in my json server. I'm sending the POST request from Angular. When I do so, I get the following error:

Note: when I do the get in a the GET end point it works fine. I'm very new on the server side

POST ERROR 404:
  Http failure response for http://localhost:3000/addMember: 404 Not Found

SERVER.JS

```<code>const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
....

app.use(cors());
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.disable('x-powered-by');
app.use(xssFilter());
app.use(nosniff());
app.set('etag', false);
app.use(
  helmet({
    noCache: true
  })
);
app.use(
  hsts({
    maxAge: 15552000 // 180 days in seconds
  })
);

app.use(
  express.static(path.join(__dirname, 'dist/softrams-racing'), {
    etag: false
  })
);

app.get('/api/members', (req, res) => {
  request('http://localhost:3000/members', (err, response, body) => {
    if (response.statusCode <= 500) {
      res.send(body);
    }
  });
});

// TODO: Dropdown!
app.get('/api/teams', (req, res) => {
  request('http://localhost:3000/teams', (err, response, body) => {
    if (response.statusCode <= 500) {
      res.send(body);
    }
  });
});

    // Submit Form!
    app.post('/api/members', function(request, response) {
  request.post('http://localhost:3000/members', (err, response, body) => {
    if (response.statusCode <= 500) {
      req.send(body);
    }
  });
});

  app.get('*', (req, res) => {
      res.sendFile(path.join(__dirname, 'dist/softrams-racing/index.html'));
    });

    app.listen('8000', () => {
      console.log('Vrrrum Vrrrum! Server starting!');
    });
</code>```

ANGULAR

```<code>addMember(memberForm: Member) {
    this.http.post(`${this.api}/addMember`, memberForm).subscribe(
      data => {
        console.log('POST Request is successful ', data);
      },
      error => {
        console.log('Error', error);
      }
    );
  }
</code>```

UPDATE:
in my console i see this POST /addMember 404 12.105 ms - 2 and If i go to http://localhost:3000/addMember directly in the browser I see an empty object {} and if I go here http://localhost:3000/ I see this message To access and modify resources, you can use any HTTP method GET POST PUT PATCH DELETE OPTIONS

答:
The issue here is that you are making your POST request to a route which your JSON server does not handle.  Change the URL to http://localhost:3000/members, and it should work fine!

(The routes on a json-server correspond to the elements in your db.json file.)

Title: POST an item to JSON server db- Angular

Body:
I'm trying to POST an Item to my db in my json server. I'm sending the POST request from Angular. When I do so, I get the following error:

Note: when I do the get in a the GET end point it works fine. I'm very new on the server side

POST ERROR 404:
  Http failure response for http://localhost:3000/addMember: 404 Not Found

SERVER.JS

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
....

app.use(cors());
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.disable('x-powered-by');
app.use(xssFilter());
app.use(nosniff());
app.set('etag', false);
app.use(
  helmet({
    noCache: true
  })
);
app.use(
  hsts({
    maxAge: 15552000 // 180 days in seconds
  })
);

app.use(
  express.static(path.join(__dirname, 'dist/softrams-racing'), {
    etag: false
  })
);

app.get('/api/members', (req, res) => {
  request('http://localhost:3000/members', (err, response, body) => {
    if (response.statusCode <= 500) {
      res.send(body);
    }
  });
});

// TODO: Dropdown!
app.get('/api/teams', (req, res) => {
  request('http://localhost:3000/teams', (err, response, body) => {
    if (response.statusCode <= 500) {
      res.send(body);
    }
  });
});

    // Submit Form!
    app.post('/api/members', function(request, response) {
  request.post('http://localhost:3000/members', (err, response, body) => {
    if (response.statusCode <= 500) {
      req.send(body);
    }
  });
});

  app.get('*', (req, res) => {
      res.sendFile(path.join(__dirname, 'dist/softrams-racing/index.html'));
    });

    app.listen('8000', () => {
      console.log('Vrrrum Vrrrum! Server starting!');
    });

ANGULAR

addMember(memberForm: Member) {
    this.http.post(`${this.api}/addMember`, memberForm).subscribe(
      data => {
        console.log('POST Request is successful ', data);
      },
      error => {
        console.log('Error', error);
      }
    );
  }

UPDATE:
in my console i see this POST /addMember 404 12.105 ms - 2 and If i go to http://localhost:3000/addMember directly in the browser I see an empty object {} and if I go here http://localhost:3000/ I see this message To access and modify resources, you can use any HTTP method GET POST PUT PATCH DELETE OPTIONS


问:
Is it possible to use a bean generated from the same class
I'm trying to use a bean generated from the same class. E.g:

public class Test {
  ...

  @Bean
  public Dog dog() {
    ...
    return dog;
  }

  @Bean
  public DogHouse dogHouse() {
    Dog d = dog(); // Is this right? Can I inject dog bean here?
    ...
    return dogHouse;
  }
}
```

Two requirements I got to obey:

Use the result of dog() in dogHouse()

Keep dog() and dogHouse() in the same java class

Is this possible? If it is, how should I inject the dog Bean in Test class? Thanks.

答:
```<code>@Bean
  public DogHouse dogHouse() {
    Dog d = dog();
    ...
    return dogHouse;
  }
</code>```

When @Bean have dependencies on one another, then to resolve this dependency one bean method can call the other one. In your case calling dog() inside dogHouse() is perfectly fine.

Body:
I'm trying to use a bean generated from the same class. E.g:

public class Test {
  ...

  @Bean
  public Dog dog() {
    ...
    return dog;
  }

  @Bean
  public DogHouse dogHouse() {
    Dog d = dog(); // Is this right? Can I inject dog bean here?
    ...
    return dogHouse;
  }
}

Two requirements I got to obey:

Use the result of dog() in dogHouse()

Keep dog() and dogHouse() in the same java class

Is this possible? If it is, how should I inject the dog Bean in Test class? Thanks.

Body:
@Bean
  public DogHouse dogHouse() {
    Dog d = dog();
    ...
    return dogHouse;
  }

When @Bean have dependencies on one another, then to resolve this dependency one bean method can call the other one. In your case calling dog() inside dogHouse() is perfectly fine.


问:
ERROR: Manifest merger failed : Attribute application@appComponentFactory value
Hello friend I am using GitHub color picker library  here library dependency
implementation 'petrov.kristiyan:colorpicker-library:1.1.10'

Library link  https://github.com/kristiyanP/colorpicker

When I tried to integrate this library in my project I am getting this error please help me?

```<code>  ERROR: Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
        is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
        Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:8:5-35:19 to override.

here is my mainfest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="bible.swordof.God">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE_EXTERNAL_STORAGE" />

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".Favourite"></activity>
            <activity android:name=".ALLVERSE" />
            <activity android:name=".Verse" />
            <activity android:name=".Chapters" />
            <activity android:name=".splashsacreen">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>

            <meta-data
                android:name="com.google.android.gms.ads.APPLICATION_ID"
                android:value="ca-app-pub-3940256099942544~3347511713" />

            <activity
                android:name=".MainActivity"
                android:label="@string/app_name"
                android:theme="@style/AppTheme.NoActionBar" />
        </application>

    </manifest>
</code>```

答:
It is conflicting with migration to the AndroidX use below :</p>

```<code>implementation 'petrov.kristiyan:colorpicker-library:1.1.5'
</code>```

Body:
Hello friend I am using GitHub color picker library  here library dependency
implementation 'petrov.kristiyan:colorpicker-library:1.1.10'

Library link  https://github.com/kristiyanP/colorpicker

When I tried to integrate this library in my project I am getting this error please help me?

  ERROR: Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
        is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
        Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:8:5-35:19 to override.

here is my mainfest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="bible.swordof.God">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE_EXTERNAL_STORAGE" />

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".Favourite"></activity>
            <activity android:name=".ALLVERSE" />
            <activity android:name=".Verse" />
            <activity android:name=".Chapters" />
            <activity android:name=".splashsacreen">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>

            <meta-data
                android:name="com.google.android.gms.ads.APPLICATION_ID"
                android:value="ca-app-pub-3940256099942544~3347511713" />

            <activity
                android:name=".MainActivity"
                android:label="@string/app_name"
                android:theme="@style/AppTheme.NoActionBar" />
        </application>

    </manifest>

Body:
It is conflicting with migration to the AndroidX use below :

implementation 'petrov.kristiyan:colorpicker-library:1.1.5'


问:
How remember that a React hooks component is unmounted, so can avoid state changes?
With old class based React.js code, I can do like this, to remember that a component has been unmounted:

```<code>  componentWillUnmount: function() {
    this.isGone = true;
  },

  loadUsers: function() {
    Server.loadUsers(..., (response) => {
      if (this.isGone) return;
      ...
    });
  }
</code>```

How can one do the same thing, with hooks based components?

Here's a sample hooks function component, where I'm unsure about how to remember that it's been unmounted, so I can return before calling any setSomeState:

```<code>export const GroupMembers = React.createFactory(function(props) {

  const [membersOrNull, setMembers] = React.useState(null);
  let isGone = false;  // ? (se [222] below

  React.useEffect(() => {
    Server.listGroupMembers(someGroupId, (response) => {
     if (/* is unmounted ?? */) return;
     setMembers(response.members);
    });
    return () => { /* how remember is unmounted?
                      would isGone = true; work? */ };
  }, []);

  ...

  return ..., Button({ title: "Remove all members", onClick: () => {
    Server.removeAllMembers(someGroupId, () => {
     if (/* is unmounted ?? */) return;
     setMembers([]);
    });
  }});
</code>```

I suppose I cannot use const [isGone, setGone] = useState(false) because I shouldn't try to access the state (read isGone) after has been unmounted. And if I [222] add a local let isGone = false inside the function, it seems to me that various callbacks created inside the function, will refer to different "instances" of this local variable, depending on in which different GroupMembers(..) invokation the different callbacks were created? or am I mistaken and this works? — Maybe I could create an outer wrapper function with a local let isGone = false, however, this adds another wrapping function and indentation :- /

答:
just use local variable accessed through closure

```<code>React.useEffect(() => {
  let isActual = true;
  Server.listGroupMembers(someGroupId, (response) => {
     if (!isActual) return;
     setMembers(response.members);
  });
  return () => {isActual = false;};
}, []);
</code>```

in this case flag would be updated on unmounting only. but in general case(with some unempty dependencies for useEffect) it will use as well. So in case of sequential renderings you could be sure you never process older request.

PS most universal way is cancelling request when it's possible.

Body:
With old class based React.js code, I can do like this, to remember that a component has been unmounted:

  componentWillUnmount: function() {
    this.isGone = true;
  },

  loadUsers: function() {
    Server.loadUsers(..., (response) => {
      if (this.isGone) return;
      ...
    });
  }

How can one do the same thing, with hooks based components?

Here's a sample hooks function component, where I'm unsure about how to remember that it's been unmounted, so I can return before calling any setSomeState:

export const GroupMembers = React.createFactory(function(props) {

  const [membersOrNull, setMembers] = React.useState(null);
  let isGone = false;  // ? (se [222] below

  React.useEffect(() => {
    Server.listGroupMembers(someGroupId, (response) => {
     if (/* is unmounted ?? */) return;
     setMembers(response.members);
    });
    return () => { /* how remember is unmounted?
                      would isGone = true; work? */ };
  }, []);

  ...

  return ..., Button({ title: "Remove all members", onClick: () => {
    Server.removeAllMembers(someGroupId, () => {
     if (/* is unmounted ?? */) return;
     setMembers([]);
    });
  }});

I suppose I cannot use const [isGone, setGone] = useState(false) because I shouldn't try to access the state (read isGone) after has been unmounted. And if I [222] add a local let isGone = false inside the function, it seems to me that various callbacks created inside the function, will refer to different "instances" of this local variable, depending on in which different GroupMembers(..) invokation the different callbacks were created? or am I mistaken and this works? — Maybe I could create an outer wrapper function with a local let isGone = false, however, this adds another wrapping function and indentation :- /

Body:
just use local variable accessed through closure

React.useEffect(() => {
  let isActual = true;
  Server.listGroupMembers(someGroupId, (response) => {
     if (!isActual) return;
     setMembers(response.members);
  });
  return () => {isActual = false;};
}, []);

in this case flag would be updated on unmounting only. but in general case(with some unempty dependencies for useEffect) it will use as well. So in case of sequential renderings you could be sure you never process older request.

PS most universal way is cancelling request when it's possible.


问:
why is XLinq reformatting my XML?
I am using XLinq (XML to Linq) to parse a xml document and one part of the document deals with representing rich-text and uses the xml:space="preserve" attribute to preserve whitespace within the rich-text element.

The issue I'm experiencing is that when I have a element inside the rich-text which only contains a sub-element but no text, XLinq reformats the xml and puts the element on its own line. This, of course, causes additional white space to be created which changes the original content.

Example:

```<code><rich-text xml:space="preserve">
    <text-run><br/></text-run>
</rich-text>
</code>```

results in:

```<code><rich-text xml:space="preserve">
    <text-run>
        <br/>
    </text-run>
</rich-text>
</code>```

If I add a space or any other text before the
 in the original xml like so

```<code><rich-text xml:space="preserve">
    <text-run> <br/></text-run>
</rich-text>
</code>```

the parser doesn't reformat the xml

```<code><rich-text xml:space="preserve">
    <text-run> <br/></text-run>
</rich-text>
</code>```

How can I prevent the xml parser from reformatting my element?

Is this reformatting normal for XML parsing or is this just an unwanted side effect of the XLinq parser?

EDIT:
I am parsing the document like this:

```<code>using (var reader = System.Xml.XmlReader.Create(stream))
    return XElement.Load(reader);
</code>```

I am not using any custom XmlReaderSettings or LoadOptions

The problem occurs when I use the .Value property on the text-run XElement to get the text value of the element. Instead of receiving \n which would be the correct output from the original xml, I will receive

\n    \n

Note the additional whitespace and line break due to the reformatting! The reformatting can also be observed when inspecting the element in the debugger or calling .ToString().

答:
Have you tried this:

```<code>yourXElement.ToString(SaveOptions.DisableFormatting)
</code>```

This should solve your problem.

btw - you should also do a similar thing on load:

```<code>XElement.Parse(sr, LoadOptions.PreserveWhitespace);
</code>```

Title: why is XLinq reformatting my XML?

Body:
I am using XLinq (XML to Linq) to parse a xml document and one part of the document deals with representing rich-text and uses the xml:space="preserve" attribute to preserve whitespace within the rich-text element.

The issue I'm experiencing is that when I have a element inside the rich-text which only contains a sub-element but no text, XLinq reformats the xml and puts the element on its own line. This, of course, causes additional white space to be created which changes the original content.

Example:

<rich-text xml:space="preserve">
    <text-run>
</text-run>
</rich-text>

results in:

<rich-text xml:space="preserve">
    <text-run>

    </text-run>
</rich-text>

If I add a space or any other text before the
 in the original xml like so

<rich-text xml:space="preserve">
    <text-run>
</text-run>
</rich-text>

the parser doesn't reformat the xml

<rich-text xml:space="preserve">
    <text-run>
</text-run>
</rich-text>

How can I prevent the xml parser from reformatting my element?

Is this reformatting normal for XML parsing or is this just an unwanted side effect of the XLinq parser?

EDIT:
I am parsing the document like this:

using (var reader = System.Xml.XmlReader.Create(stream))
    return XElement.Load(reader);

I am not using any custom XmlReaderSettings or LoadOptions

The problem occurs when I use the .Value property on the text-run XElement to get the text value of the element. Instead of receiving \n which would be the correct output from the original xml, I will receive

\n    \n

Note the additional whitespace and line break due to the reformatting! The reformatting can also be observed when inspecting the element in the debugger or calling .ToString().

Body:
Have you tried this:

yourXElement.ToString(SaveOptions.DisableFormatting)

This should solve your problem.

btw - you should also do a similar thing on load:

XElement.Parse(sr, LoadOptions.PreserveWhitespace);


问:
How to solve this CSS is not a function error
I have a small jQuery code but it gives me some errors. Can anybody help me with this error?

Code:

```<code><input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">
</code>```

JS

```<code>$(function() {
  var checkboxes = $("input[type=checkbox]")
      checkboxes.is(':checked').css('background-color', 'red')
      checkboxes.on('change', function() {
    var checkbox = $(this)
    checkbox.css('background-color', checkbox.is(':checked') ? 'blue' : 'transparent')
  })
})
</code>```

CSS

```<code>  input[type='checkbox'] {
   -webkit-appearance: none;
    width: 20px;
    height: 20px;
   background: grey;
 }

input[type='checkbox']:checked {
  background: red;}
</code>```

Also here is link:
    https://jsfiddle.net/3y9Lvobc/2/

Error in console is:

```<code> checkboxes.is(...).css is not a function
</code>```

答:
Rather than using is(:checked) property replace it with find(:checked) that will resolve the error. check the below jquery script

```<code>$(function()
{
      var checkboxes = $("input[type=checkbox]")
          checkboxes.find(':checked').css('background-color', 'red')
          checkboxes.on('change', function() {
        var checkbox = $(this)
        checkbox.css('background-color', checkbox.is(':checked') ? 'blue' : 'transparent')
      })
    })
</code>```

Check if this might help.

https://jsfiddle.net/gk6x8m5r/

Body:
I have a small jQuery code but it gives me some errors. Can anybody help me with this error?

Code:

<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">

JS

$(function() {
  var checkboxes = $("input[type=checkbox]")
      checkboxes.is(':checked').css('background-color', 'red')
      checkboxes.on('change', function() {
    var checkbox = $(this)
    checkbox.css('background-color', checkbox.is(':checked') ? 'blue' : 'transparent')
  })
})

CSS

  input[type='checkbox'] {
   -webkit-appearance: none;
    width: 20px;
    height: 20px;
   background: grey;
 }

input[type='checkbox']:checked {
  background: red;}

Also here is link:
    https://jsfiddle.net/3y9Lvobc/2/

Error in console is:

 checkboxes.is(...).css is not a function

Body:
Rather than using is(:checked) property replace it with find(:checked) that will resolve the error. check the below jquery script

$(function()
{
      var checkboxes = $("input[type=checkbox]")
          checkboxes.find(':checked').css('background-color', 'red')
          checkboxes.on('change', function() {
        var checkbox = $(this)
        checkbox.css('background-color', checkbox.is(':checked') ? 'blue' : 'transparent')
      })
    })

Check if this might help.

https://jsfiddle.net/gk6x8m5r/


问:
Is there a way to return select query results with few column's value as NULL (other than using REPLACE)?
I want to export a table in DB2 where in which I want to return few column vaues as NULL due to some restrictions.
I am looking for better alternatives to prepare the select query for export.

I can achieve it with the below select query. But the query is very long considering the table has many columns.

```<code>SELECT

COL1
,COL2
,COL3
,COL4

,REPLACE(COL5,NULL) AS COL5

,REPLACE(COL6,NULL) AS COL6

,COL7
,COL8
,COL9
,COL10
,COL11

,REPLACE(COL12,NULL) AS COL12

,COL13
,COL14
,COL15
,COL16
,COL17
,COL18

,REPLACE(COL19,NULL) AS COL19

,COL20

FROM
TABLE1
</code>```

Is there any better alternatives?

答:
Use the following way to set column null value</p>

```<code>SELECT
    COL1
    ,COL2
    ,COL3
    ,COL4
    ,NULL AS COL5,
    ,NULL AS COL6
FROM TABLE1
</code>```

Body:
I want to export a table in DB2 where in which I want to return few column vaues as NULL due to some restrictions.
I am looking for better alternatives to prepare the select query for export.

I can achieve it with the below select query. But the query is very long considering the table has many columns.

SELECT

COL1
,COL2
,COL3
,COL4

,REPLACE(COL5,NULL) AS COL5

,REPLACE(COL6,NULL) AS COL6

,COL7
,COL8
,COL9
,COL10
,COL11

,REPLACE(COL12,NULL) AS COL12

,COL13
,COL14
,COL15
,COL16
,COL17
,COL18

,REPLACE(COL19,NULL) AS COL19

,COL20

FROM
TABLE1

Is there any better alternatives?

Body:
Use the following way to set column null value

SELECT
    COL1
    ,COL2
    ,COL3
    ,COL4
    ,NULL AS COL5,
    ,NULL AS COL6
FROM TABLE1


问:
How to remove CSS animation from element in vanilla JS
I've got a square grid of n x n smaller square div elements that I want to illuminate in a sequence with a CSS background color animation. I have a function to generate a random array for the sequence. The trouble I'm having is that once a certain square has been illuminated once, if it occurs again within the array it won't illuminate a second time. I believe it's because once the element has been assigned the CSS animation, the animation can't trigger again on that element, and I can't figure a way to make it work. It's for a Responsive Web Apps course I'm taking, and the assessment stipulates that we're only to use vanilla JS, and that all elements must be created in JS and appended to a blank  in our index.html.

Each flash according to the sequence is triggered through a setTimeout function that loops through all elements in the array increasing it's timer by 1s for each loop (the animation length is 1s also).

Defining containers and child divs:

```<code>function createGameContainer(n, width, height) {
    var container = document.createElement('div');

    //CSS styling
    container.style.margin = '50px auto'
    container.style.width = width;
    container.style.height = height;
    container.style.display = 'grid';

    // loop generates string to create necessary number of grid columns based on the width of the grid of squares
    var columns = '';
    for (i = 0; i < n; i++) {
        columns += ' calc(' + container.style.width + '/' + n.toString() + ')'
    }
    container.style.gridTemplateColumns = columns;

    container.style.gridRow = 'auto auto';

    // gap variable to reduce column and row gap for larger grid sizes
    // if n is ever set to less than 2, gap is hardcoded to 20 to avoid taking square root of 0 or a negative value
    var gap;
    if (n > 1) {
        gap = 20/Math.sqrt(n-1);
    } else {
        gap = 20;
    }

    container.style.gridColumnGap = gap.toString() + 'px';
    container.style.gridRowGap = gap.toString() + 'px';

    container.setAttribute('id', 'game-container');

    document.body.appendChild(container);
}

/*
function to create individual squares to be appended to parent game container
*/
function createSquare(id) {
    var square = document.createElement('div');

    //CSS styling
    square.style.backgroundColor = '#333';
    //square.style.padding = '20px';
    square.style.borderRadius = '5px';
    square.style.display = 'flex';
    square.style.alignItems = 'center';
    //set class and square id
    square.setAttribute('class', 'square');
    square.setAttribute('id', id);

    return square;
}
/*
function to create game container and and squares and append squares to parent container
parameter n denotes dimensions of game grid - n x n grid
*/

function createGameWindow(n, width, height) {
    window.dimension = n;
    createGameContainer(n, width, height);

    /*
    loop creates n**2 number of squares to fill game container and assigns an id to each square from 0 at the top left square to (n**2)-1 at the bottom right square
    */
    for (i = 0; i < n**2; i++) {
        var x = createSquare(i);
        document.getElementById('game-container').appendChild(x);
    }
}
</code>```

The CSS animation:

```<code>@keyframes flash {
    0% {
        background: #333;
    }

    50% {
        background: orange
    }

    100% {
        background: #333;
    }
}

.flashing {
    animation: flash 1s;
}

</code>```

The code to generate the array:

```<code>function generateSequence(sequenceLength) {
    var sequence = [];
    for (i = 0; i < sequenceLength; i++) {
        var random = Math.floor(Math.random() * (dimension**2));
        // the following loop ensures each element in the sequence is different than the previous element
        while (sequence[i-1] == random) {
            random = Math.floor(Math.random() * (dimension**2));
        }
        sequence[i] = random;
    };

    return sequence;
}
</code>```

Code to apply animation to square:

```<code>function flash(index, delay) {
    setTimeout( function() {
        flashingSquare = document.getElementById(index);
        flashingSquare.style.animation = 'flashOne 1s';
        flashingSquare.addEventListener('animationend', function() {
            flashingSquare.style.animation = '';
    }, delay);
}
</code>```

I've also tried removing and adding a class again to try and reset the animation:

```<code>function flash(index, delay) {
    setTimeout( function() {
        flashingSquare = document.getElementById(index);
        flashingSquare.classList.remove('flashing');
        flashingSquare.classList.add('flashing');
    }, delay);
}
</code>```

And the function to generate and display the sequence:

```<code>function displaySequence(sequenceLength) {
    var sequence = generateSequence(sequenceLength);

    i = 0;
    while (i < sequence.length) {
        index = sequence[i].toString();
        flash(index, i*1000);

        i++;
    }
}
</code>```

Despite many different attempts and a bunch of research I can't figure a way to get the animations to trigger multiple times on the same element.

答:
Try this one:

```<code>function flash(index, delay){
    setTimeout( function() {
        flashingSquare = document.getElementById(index);
        flashingSquare.classList.add('flashing');
        flashingSquare.addEventListener('animationend', function() {
                flashingSquare.classList.remove('flashing');
        }, delay);
    });
}
</code>```

Don't remove the animation, remove the class.

Remove the class direct AFTER the animation is done. So the browser have time to handle everything to do so. And when you add the class direct BEFORE you want the animation, the browser can trigger all needed steps to do so.

Your attempt to remove and add the class was good but to fast. I think the browser and the DOM optimize your steps and do nothing.

Body:
I've got a square grid of n x n smaller square div elements that I want to illuminate in a sequence with a CSS background color animation. I have a function to generate a random array for the sequence. The trouble I'm having is that once a certain square has been illuminated once, if it occurs again within the array it won't illuminate a second time. I believe it's because once the element has been assigned the CSS animation, the animation can't trigger again on that element, and I can't figure a way to make it work. It's for a Responsive Web Apps course I'm taking, and the assessment stipulates that we're only to use vanilla JS, and that all elements must be created in JS and appended to a blank  in our index.html.

Each flash according to the sequence is triggered through a setTimeout function that loops through all elements in the array increasing it's timer by 1s for each loop (the animation length is 1s also).

Defining containers and child divs:

function createGameContainer(n, width, height) {
    var container = document.createElement('div');

    //CSS styling
    container.style.margin = '50px auto'
    container.style.width = width;
    container.style.height = height;
    container.style.display = 'grid';

    // loop generates string to create necessary number of grid columns based on the width of the grid of squares
    var columns = '';
    for (i = 0; i < n; i++) {
        columns += ' calc(' + container.style.width + '/' + n.toString() + ')'
    }
    container.style.gridTemplateColumns = columns;

    container.style.gridRow = 'auto auto';

    // gap variable to reduce column and row gap for larger grid sizes
    // if n is ever set to less than 2, gap is hardcoded to 20 to avoid taking square root of 0 or a negative value
    var gap;
    if (n > 1) {
        gap = 20/Math.sqrt(n-1);
    } else {
        gap = 20;
    }

    container.style.gridColumnGap = gap.toString() + 'px';
    container.style.gridRowGap = gap.toString() + 'px';

    container.setAttribute('id', 'game-container');

    document.body.appendChild(container);
}

/*
function to create individual squares to be appended to parent game container
*/
function createSquare(id) {
    var square = document.createElement('div');

    //CSS styling
    square.style.backgroundColor = '#333';
    //square.style.padding = '20px';
    square.style.borderRadius = '5px';
    square.style.display = 'flex';
    square.style.alignItems = 'center';
    //set class and square id
    square.setAttribute('class', 'square');
    square.setAttribute('id', id);

    return square;
}
/*
function to create game container and and squares and append squares to parent container
parameter n denotes dimensions of game grid - n x n grid
*/

function createGameWindow(n, width, height) {
    window.dimension = n;
    createGameContainer(n, width, height);

    /*
    loop creates n**2 number of squares to fill game container and assigns an id to each square from 0 at the top left square to (n**2)-1 at the bottom right square
    */
    for (i = 0; i < n**2; i++) {
        var x = createSquare(i);
        document.getElementById('game-container').appendChild(x);
    }
}

The CSS animation:

@keyframes flash {
    0% {
        background: #333;
    }

    50% {
        background: orange
    }

    100% {
        background: #333;
    }
}

.flashing {
    animation: flash 1s;
}

The code to generate the array:

function generateSequence(sequenceLength) {
    var sequence = [];
    for (i = 0; i < sequenceLength; i++) {
        var random = Math.floor(Math.random() * (dimension**2));
        // the following loop ensures each element in the sequence is different than the previous element
        while (sequence[i-1] == random) {
            random = Math.floor(Math.random() * (dimension**2));
        }
        sequence[i] = random;
    };

    return sequence;
}

Code to apply animation to square:

function flash(index, delay) {
    setTimeout( function() {
        flashingSquare = document.getElementById(index);
        flashingSquare.style.animation = 'flashOne 1s';
        flashingSquare.addEventListener('animationend', function() {
            flashingSquare.style.animation = '';
    }, delay);
}

I've also tried removing and adding a class again to try and reset the animation:

function flash(index, delay) {
    setTimeout( function() {
        flashingSquare = document.getElementById(index);
        flashingSquare.classList.remove('flashing');
        flashingSquare.classList.add('flashing');
    }, delay);
}

And the function to generate and display the sequence:

function displaySequence(sequenceLength) {
    var sequence = generateSequence(sequenceLength);

    i = 0;
    while (i < sequence.length) {
        index = sequence[i].toString();
        flash(index, i*1000);

        i++;
    }
}

Despite many different attempts and a bunch of research I can't figure a way to get the animations to trigger multiple times on the same element.

Body:
Try this one:

function flash(index, delay){
    setTimeout( function() {
        flashingSquare = document.getElementById(index);
        flashingSquare.classList.add('flashing');
        flashingSquare.addEventListener('animationend', function() {
                flashingSquare.classList.remove('flashing');
        }, delay);
    });
}

Don't remove the animation, remove the class.

Remove the class direct AFTER the animation is done. So the browser have time to handle everything to do so. And when you add the class direct BEFORE you want the animation, the browser can trigger all needed steps to do so.

Your attempt to remove and add the class was good but to fast. I think the browser and the DOM optimize your steps and do nothing.


问:
Hibernate Search java spring, searching only entities that have ids as specified
I have a problem when i want to search in entities that have specific ids. I have fullTextQuery that i execute, it works all fine, bud when i want to say

ONLY SEARCH IN THESE ENTITIES (List of ids provided) :

```<code>+(title:slovakia~2 leadText:slovakia~2 body:slovakia~2 software:slovakia~2) +verified:true +eid:(113 | 112 | 3)
</code>```

Then i get 0 results, these entities are indexed and persisted, all should be working fine, yet it doesnt return any results.

Here is The entity property defined :

```<code>@Id
@GeneratedValue
@Field(name = "eid")
@FieldBridge(impl = LongBridge.class)
private long id;
</code>```

I have tried, Without field bridge, with TermVector.YES and also without any additional @Field.. annotation. All results either exception or just no results.

What is a proper way of searching in specific IDs?

For instance here is the working query:

Creation of query looks like this :

```<code>    return Optional.of(getQueryBuilder()
            .keyword()
            .onField("eid")
            .matching(stringBuilder.toString())
            .createQuery());
</code>```

答:
The syntax you tried to use, (113 | 112 | 3), is not correct in this context. Parameters to the keyword query are not interpreted, in particular operators are not supported.

Use a boolean junction that matches any of the provided IDs instead:

```<code>List<String> eids = ...;

QueryBuilder qb = getQueryBuilder();

BooleanJunction<?> idJunction = qb.bool();

for (String eid : eids) {
    idJunction.should(
            qb.keyword()
                .onField("eid")
                .matching(eid)
                .createQuery()
    );
}

return idJunction.createQuery();
</code>```

Note that, if you want to add other queries, you should not use the same junction. Use another junction that includes idJunction.createQuery() as one of its clauses.

Body:
I have a problem when i want to search in entities that have specific ids. I have fullTextQuery that i execute, it works all fine, bud when i want to say

ONLY SEARCH IN THESE ENTITIES (List of ids provided) :

+(title:slovakia~2 leadText:slovakia~2 body:slovakia~2 software:slovakia~2) +verified:true +eid:(113 | 112 | 3)

Then i get 0 results, these entities are indexed and persisted, all should be working fine, yet it doesnt return any results.

Here is The entity property defined :

@Id
@GeneratedValue
@Field(name = "eid")
@FieldBridge(impl = LongBridge.class)
private long id;

I have tried, Without field bridge, with TermVector.YES and also without any additional @Field.. annotation. All results either exception or just no results.

What is a proper way of searching in specific IDs?

For instance here is the working query:

Creation of query looks like this :

    return Optional.of(getQueryBuilder()
            .keyword()
            .onField("eid")
            .matching(stringBuilder.toString())
            .createQuery());

Body:
The syntax you tried to use, (113 | 112 | 3), is not correct in this context. Parameters to the keyword query are not interpreted, in particular operators are not supported.

Use a boolean junction that matches any of the provided IDs instead:

List<String> eids = ...;

QueryBuilder qb = getQueryBuilder();

BooleanJunction<?> idJunction = qb.bool();

for (String eid : eids) {
    idJunction.should(
            qb.keyword()
                .onField("eid")
                .matching(eid)
                .createQuery()
    );
}

return idJunction.createQuery();

Note that, if you want to add other queries, you should not use the same junction. Use another junction that includes idJunction.createQuery() as one of its clauses.


问:
How to calculating time difference
I'm trying to make a program where i put in to different times and get the difference in minute after clicking the "calculate" button. I'm not sure if my approach is correct, there may be some typo's.

I'v tried to make the different input values to number but it seems like there is another underlying problem which I can't see.

var hour1=document.getElementById("hour1");
var min1=document.getElementById("min1");
var hour2=document.getElementById("hour2");
var min2=document.getElementById("min2");

function calc(){
    var minutt1=Number(hour1)*60+Number(min1);
    var minutt2=Number(hour2)*60+Number(min2);
    var resultat=0;
    resultat = Number(minutt1) - Number(minutt2);
    document.getElementById("result").innerHTML="Time differance is:" + Number(resultat);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min1">
<button type="button" onclick="calc()">Regn ut</button>

<div id="result"></div></code>```

I expect getting a number which represents the time difference in minutes, but the actual output is "NaN".

答:
You need to get the value of hour1, min1, hour2, and min2. You also don't have an element min2:

```<code>var hour1=document.getElementById("hour1").value;
var min1=document.getElementById("min1").value;
var hour2=document.getElementById("hour2").value;
var min2=document.getElementById("min2").value;
</code>```

What your code was trying to do was multiply and subtract HTML elements (never a good idea).

var hour1 = document.getElementById("hour1").value;
var min1 = document.getElementById("min1").value;
var hour2 = document.getElementById("hour2").value;
var min2 = document.getElementById("min2").value;

function calc() {
  var minutt1 = Number(hour1) * 60 + Number(min1);
  var minutt2 = Number(hour2) * 60 + Number(min2);
  var resultat = 0;
  resultat = Number(minutt1) - Number(minutt2);
  document.getElementById("result").innerHTML = "Time differance is:" + Number(resultat);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min2">
<button type="button" onclick="calc()">Regn ut</button>

<div id="result"></div></code>```

Title: How to calculating time difference

Body:
I'm trying to make a program where i put in to different times and get the difference in minute after clicking the "calculate" button. I'm not sure if my approach is correct, there may be some typo's.

I'v tried to make the different input values to number but it seems like there is another underlying problem which I can't see.

var hour1=document.getElementById("hour1");
var min1=document.getElementById("min1");
var hour2=document.getElementById("hour2");
var min2=document.getElementById("min2");

function calc(){
    var minutt1=Number(hour1)*60+Number(min1);
    var minutt2=Number(hour2)*60+Number(min2);
    var resultat=0;
    resultat = Number(minutt1) - Number(minutt2);
    document.getElementById("result").innerHTML="Time differance is:" + Number(resultat);
}

<input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min1">
<button type="button" onclick="calc()">Regn ut</button>

I expect getting a number which represents the time difference in minutes, but the actual output is "NaN".

Body:
You need to get the value of hour1, min1, hour2, and min2. You also don't have an element min2:

var hour1=document.getElementById("hour1").value;
var min1=document.getElementById("min1").value;
var hour2=document.getElementById("hour2").value;
var min2=document.getElementById("min2").value;

What your code was trying to do was multiply and subtract HTML elements (never a good idea).

var hour1 = document.getElementById("hour1").value;
var min1 = document.getElementById("min1").value;
var hour2 = document.getElementById("hour2").value;
var min2 = document.getElementById("min2").value;

function calc() {
  var minutt1 = Number(hour1) * 60 + Number(min1);
  var minutt2 = Number(hour2) * 60 + Number(min2);
  var resultat = 0;
  resultat = Number(minutt1) - Number(minutt2);
  document.getElementById("result").innerHTML = "Time differance is:" + Number(resultat);
}

<input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min2">
<button type="button" onclick="calc()">Regn ut</button>

<div id="result"></div>


问:
Using intel inline assembler to code bigint add with carry
I would like to do a fast code for adding 64 bit numbers in big ints:

```<code>uint64_t ans[n];
uint64_t a[n], b[n]; // assume initialized values....
for (int i = 0; i < n; i++)
  ans[i] = a[i] + b[i];
</code>```

but the above does not work with carry.

I saw another question here that suggested using an if statement to check which is elegant:

```<code>ans[0] = a[0] + b[0];
int c = ans[0] < a[0];
for (int i = 0; i < n; i++) {
  ans[i] = a[i] + b[i] + c;
  c = ans[i] < a[i];
}
</code>```

However, I would like to learn how to embed inline (intel) assembly and do it faster.
I am sure there are 64 bit opcodes, the equivalent of:

```<code>add eax, ebx
adc ...
</code>```

but I don't know how to pass parameters to the assembler from the rest of the c++ code.

答:
I'm not entirely sure if this is what you were looking for, and my assembly skills are definitely not the best (lack of suffixes for example), but this uses ADC and should solve your problem.

Note the omission of the C++ for loop; we need to loop in asm because we need CF to survive across iterations.  (GCC6 has flag output constraints, but not flag inputs; there's no way to ask the compiler to pass FLAGS from one asm statement to another, and gcc would probably do it inefficiently with setc/cmp even if there was syntax for it.)

```<code>#include <cstdint>
#include <iostream>

#define N 4

int main(int argc, char *argv[]) {

  uint64_t ans[N];
  const uint64_t a[N] = {UINT64_MAX, UINT64_MAX, 0, 0};
  const uint64_t b[N] = {2, 1, 3, 1};

  const uint64_t i = N;
  asm volatile (
      "xor %%eax, %%eax\n\t"      // i=0  and clear CF
      "mov %3, %%rdi\n\t"         // N

      ".L_loop:\n\t"

      "mov (%%rax,%1), %%rdx\n\t" // rdx = a[i]

      "adc (%%rax,%2), %%rdx\n\t" // rdx += b[i] + carry

      "mov %%rdx, (%%rax, %0)\n\t"// ans[i] = a[i] + b[i]

      "lea 8(%%rax), %%rax\n\t"   // i += 8 bytes

      "dec %%rdi\n\t"             // --i

      "jnz .L_loop\n\t"   // if (rdi == 0) goto .L_loop;
      : /* Outputs (none) */
      : /* Inputs */ "r" (ans), "r" (a), "r" (b), "r" (i)
      : /* Clobbered */ "%rax", "%rbx", "%rdx", "%rdi", "memory"
  );

  // SHOULD OUTPUT 1 1 4 1
  for (int i = 0; i < N; ++i)
    std::cout << ans[i] << std::endl;

  return 0;
}
</code>```

In order to avoid setting the carry flag (CF), I needed to count down to 0 in order to avoid doing a CMP.  DEC does not set the carry flag, so it may be the perfect contender for this application. <s>However, I don't know how to index from the beginning of arrays any faster using %rdi than the extra instruction and register needed for inc %rax.</s>

The volatile and "memory" clobber are necessary because we only ask the compiler for pointer inputs, and don't tell it which memory we actually read and write.

On some older CPUs, notably Core2 / Nehalem, adc after inc will cause a partial-flag stall.  See Problems with ADC/SBB and INC/DEC in tight loops on some CPUs.  But on modern CPUs, this is efficient.

EDIT:
As pointed out by @PeterCordes, my inc %rax and scaling by 8 with lea was horribly inefficient (and stupid now that I think about it).  Now, it is simply lea 8(%rax), %rax.

Editor's note: we can save another instruction by using a negative index from the end of the array, counting up toward 0 with inc / jnz.

(This hard-codes the array size at 4.  You could maybe make this more flexible by asking for the array length as an immediate constant, and -i as an input.  Or asking for pointers to the end.)

```<code>// untested
  asm volatile (
      "mov   $-3, %[idx]\n\t"        // i=-3   (which we will scale by 8)

      "mov   (%[a]), %%rdx  \n\t"
      "add   (%[b]), %%rdx  \n\t"    // peel the first iteration so we don't have to zero CF first, and ADD is faster on some CPUs.
      "mov    %%rdx, (%0) \n\t"

      ".L_loop:\n\t"                        // do{
      "mov    8*4(%[a], %[idx], 8), %%rdx\n\t"   // rdx = a[i + len]
      "adc    8*4(%[b], %[idx], 8), %%rdx\n\t"   // rdx += b[i + len] + carry
      "mov    %%rdx,  8*4(%[ans], %[idx], 8)\n\t"  // ans[i] = rdx

      "inc    %[idx]\n\t"
      "jnz    .L_loop\n\t"                  // }while (++i);

      : /* Outputs, actually a read-write input */ [idx] "+&r" (i)
      : /* Inputs */ [ans] "r" (ans), [a] "r" (a), [b] "r" (b)
      : /* Clobbered */ "rdx", "memory"
  );
</code>```

The loop label should probably use %%= in case GCC duplicates this code, or use a numbered local label like 1:

Using a scaled-index addressing mode is no more expensive than a regular indexed addressing mode (2 registers) like we were using before.  Ideally we'd use a one-register addressing mode for either the adc or the store, maybe indexing the other two arrays relative to ans, by subtracting the pointers on input.

But then we'd need a separate LEA to increment by 8, because we still need to avoid destroying CF.  Still, on Haswell and later, indexed stores can't use the AGU on port 7, and Sandybridge/Ivybridge they un-laminate to 2 uops.  So for Intel SnB-family, avoiding an indexed store here would be good because we need 2x load + 1x store per iteration.  See Micro fusion and addressing modes

Earlier Intel CPUs (Core2 / Nehalem) will have partial-flag stalls on the above loop, so the above issues are irrelevant for them.

AMD CPUs are probably fine with the above loop.  Agner Fog's optimization and microarch guides don't mention any serious problems.

Unrolling a bit wouldn't hurt, though, for AMD or Intel.

Body:
I would like to do a fast code for adding 64 bit numbers in big ints:

uint64_t ans[n];
uint64_t a[n], b[n]; // assume initialized values....
for (int i = 0; i < n; i++)
  ans[i] = a[i] + b[i];

but the above does not work with carry.

I saw another question here that suggested using an if statement to check which is elegant:

ans[0] = a[0] + b[0];
int c = ans[0] < a[0];
for (int i = 0; i < n; i++) {
  ans[i] = a[i] + b[i] + c;
  c = ans[i] < a[i];
}

However, I would like to learn how to embed inline (intel) assembly and do it faster.
I am sure there are 64 bit opcodes, the equivalent of:

add eax, ebx
adc ...

but I don't know how to pass parameters to the assembler from the rest of the c++ code.

Body:
I'm not entirely sure if this is what you were looking for, and my assembly skills are definitely not the best (lack of suffixes for example), but this uses ADC and should solve your problem.

Note the omission of the C++ for loop; we need to loop in asm because we need CF to survive across iterations.  (GCC6 has flag output constraints, but not flag inputs; there's no way to ask the compiler to pass FLAGS from one asm statement to another, and gcc would probably do it inefficiently with setc/cmp even if there was syntax for it.)

#include <cstdint>
#include <iostream>

#define N 4

int main(int argc, char *argv[]) {

  uint64_t ans[N];
  const uint64_t a[N] = {UINT64_MAX, UINT64_MAX, 0, 0};
  const uint64_t b[N] = {2, 1, 3, 1};

  const uint64_t i = N;
  asm volatile (
      "xor %%eax, %%eax\n\t"      // i=0  and clear CF
      "mov %3, %%rdi\n\t"         // N

      ".L_loop:\n\t"

      "mov (%%rax,%1), %%rdx\n\t" // rdx = a[i]

      "adc (%%rax,%2), %%rdx\n\t" // rdx += b[i] + carry

      "mov %%rdx, (%%rax, %0)\n\t"// ans[i] = a[i] + b[i]

      "lea 8(%%rax), %%rax\n\t"   // i += 8 bytes

      "dec %%rdi\n\t"             // --i

      "jnz .L_loop\n\t"   // if (rdi == 0) goto .L_loop;
      : /* Outputs (none) */
      : /* Inputs */ "r" (ans), "r" (a), "r" (b), "r" (i)
      : /* Clobbered */ "%rax", "%rbx", "%rdx", "%rdi", "memory"
  );

  // SHOULD OUTPUT 1 1 4 1
  for (int i = 0; i < N; ++i)
    std::cout << ans[i] << std::endl;

  return 0;
}

In order to avoid setting the carry flag (CF), I needed to count down to 0 in order to avoid doing a CMP.  DEC does not set the carry flag, so it may be the perfect contender for this application. <s>However, I don't know how to index from the beginning of arrays any faster using %rdi than the extra instruction and register needed for inc %rax.</s>

The volatile and "memory" clobber are necessary because we only ask the compiler for pointer inputs, and don't tell it which memory we actually read and write.

On some older CPUs, notably Core2 / Nehalem, adc after inc will cause a partial-flag stall.  See Problems with ADC/SBB and INC/DEC in tight loops on some CPUs.  But on modern CPUs, this is efficient.

EDIT:
As pointed out by @PeterCordes, my inc %rax and scaling by 8 with lea was horribly inefficient (and stupid now that I think about it).  Now, it is simply lea 8(%rax), %rax.

Editor's note: we can save another instruction by using a negative index from the end of the array, counting up toward 0 with inc / jnz.

(This hard-codes the array size at 4.  You could maybe make this more flexible by asking for the array length as an immediate constant, and -i as an input.  Or asking for pointers to the end.)

// untested
  asm volatile (
      "mov   $-3, %[idx]\n\t"        // i=-3   (which we will scale by 8)

      "mov   (%[a]), %%rdx  \n\t"
      "add   (%[b]), %%rdx  \n\t"    // peel the first iteration so we don't have to zero CF first, and ADD is faster on some CPUs.
      "mov    %%rdx, (%0) \n\t"

      ".L_loop:\n\t"                        // do{
      "mov    8*4(%[a], %[idx], 8), %%rdx\n\t"   // rdx = a[i + len]
      "adc    8*4(%[b], %[idx], 8), %%rdx\n\t"   // rdx += b[i + len] + carry
      "mov    %%rdx,  8*4(%[ans], %[idx], 8)\n\t"  // ans[i] = rdx

      "inc    %[idx]\n\t"
      "jnz    .L_loop\n\t"                  // }while (++i);

      : /* Outputs, actually a read-write input */ [idx] "+&r" (i)
      : /* Inputs */ [ans] "r" (ans), [a] "r" (a), [b] "r" (b)
      : /* Clobbered */ "rdx", "memory"
  );

The loop label should probably use %%= in case GCC duplicates this code, or use a numbered local label like 1:

Using a scaled-index addressing mode is no more expensive than a regular indexed addressing mode (2 registers) like we were using before.  Ideally we'd use a one-register addressing mode for either the adc or the store, maybe indexing the other two arrays relative to ans, by subtracting the pointers on input.

But then we'd need a separate LEA to increment by 8, because we still need to avoid destroying CF.  Still, on Haswell and later, indexed stores can't use the AGU on port 7, and Sandybridge/Ivybridge they un-laminate to 2 uops.  So for Intel SnB-family, avoiding an indexed store here would be good because we need 2x load + 1x store per iteration.  See Micro fusion and addressing modes

Earlier Intel CPUs (Core2 / Nehalem) will have partial-flag stalls on the above loop, so the above issues are irrelevant for them.

AMD CPUs are probably fine with the above loop.  Agner Fog's optimization and microarch guides don't mention any serious problems.

Unrolling a bit wouldn't hurt, though, for AMD or Intel.


问:
insert a
 after each . in the value of the database
The value display in the database shows all value in the same paragraph. I want to insert a
 in my echo code so that any . (dot) is detected it will imply a
.

Below is my code:

```<code>while($row = $result->fetch_assoc()) {

        echo "   ". $row["news"]. "<br>";

    }
</code>```

答:
you can use below snippet for the same.

```<code>$str = str_replace(".",".<br/>",$str);
</code>```

It will replace every dot(.) with .

str_replace — Replace all occurrences of the search string with the replacement string

Syntax:

```<code>str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) : mixed
</code>```

In your example,

```<code>while ($row = $result->fetch_assoc()) {
    $row["news"] = str_replace(".",".<br/>",$row["news"]);
}
</code>```

Title: insert a <br> after each . in the value of the database

Body:
The value display in the database shows all value in the same paragraph. I want to insert a
 in my echo code so that any . (dot) is detected it will imply a
.

Below is my code:

while($row = $result->fetch_assoc()) {

        echo "   ". $row["news"]. "
";

    }

Body:
you can use below snippet for the same.

$str = str_replace(".",".<br/>",$str);

It will replace every dot(.) with .<br/>

str_replace — Replace all occurrences of the search string with the replacement string

Syntax:

str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) : mixed

In your example,

while ($row = $result->fetch_assoc()) {
    $row["news"] = str_replace(".",".<br/>",$row["news"]);
}


问:
Setting graph to the secondary Y axis
I am currently working on an application on winforms in C#.
I gather data and put it into Series. I would like to draw two lines from two types of data, both of them are in the format (date,someVar) for example.
The problem that I can't seem to solve is how to match a series of points in the graph to the secondary Y axis.
For example - please see the attached graph - The first is colored purple and the second one is red.
The Y axis of the first (purple) series ranges from 0 to 400.
The Y axis of the second (red) series ranges from 0 to 1.

Since the difference between the values is very large, the second (red) series appears to be a line.
I think that the problem is that both of the series are drawn according to the primary Y axis of the first (purple) series.
I have tried setting the second (red) series to the secondary Y axis, but it didn't work.

Any advice on how to solve the issue are welcome :)

Example of the issue

```<code>private void setupSeries()
{
arrayOfSeries[0]=new Series(varToDrawFromFirstComboBox,ViewType.Line);
arrayOfSeries[1]=new Series(varToDrawFromSecondComboBox,ViewType.Line);

chartY2.Text=varToDrawFromSecondComboBox
chatrY2.Dock=ChartTitleDockStylle.Right;
chatrY2.Font=...

chartY1.Text=varToDrawFromFirstComboBox
chatrY1.Dock=ChartTitleDockStylle.Left;
chatrY1.Font=....

chartTime.Text="Time"
chatrTime.Dock=ChartTitleDockStylle.Bottom;
chatrTime.Font=....

chart.Titles.AddRange(new ChartTitle[]{chartTime,chartY1,chartY2});
SecondaryAxisY myAxisY=new SecondaryAxisY();

((XYDiagram)chart.Diagram).SecondaryAxisY.Add(myAxisY);

xyDiagram.AxisX.DateTimeScaleOptions.MeasureUnit=DevExpress.XtraCharts.DateTimeMeasureUnit.Seconds;
}
</code>```

答:
To complete your chart layout initialization procedure, assign a newly created SecondaryAxisY element to the SeriesView.AxisY property of the second Series item.

```<code>    ((XYDiagram)chart.Diagram).SecondaryAxesY.Add(myAxisY);
    Series s2 = arrayOfSeries[1];
    ((LineSeriesView)s2.View).AxisY = myAxisY;
</code>```

See also: How to: Add Secondary Axes to a Chart

Title: Setting graph to the secondary Y axis

Body:
I am currently working on an application on winforms in C#.
I gather data and put it into Series. I would like to draw two lines from two types of data, both of them are in the format (date,someVar) for example.
The problem that I can't seem to solve is how to match a series of points in the graph to the secondary Y axis.
For example - please see the attached graph - The first is colored purple and the second one is red.
The Y axis of the first (purple) series ranges from 0 to 400.
The Y axis of the second (red) series ranges from 0 to 1.

Since the difference between the values is very large, the second (red) series appears to be a line.
I think that the problem is that both of the series are drawn according to the primary Y axis of the first (purple) series.
I have tried setting the second (red) series to the secondary Y axis, but it didn't work.

Any advice on how to solve the issue are welcome :)

Example of the issue

private void setupSeries()
{
arrayOfSeries[0]=new Series(varToDrawFromFirstComboBox,ViewType.Line);
arrayOfSeries[1]=new Series(varToDrawFromSecondComboBox,ViewType.Line);

chartY2.Text=varToDrawFromSecondComboBox
chatrY2.Dock=ChartTitleDockStylle.Right;
chatrY2.Font=...

chartY1.Text=varToDrawFromFirstComboBox
chatrY1.Dock=ChartTitleDockStylle.Left;
chatrY1.Font=....

chartTime.Text="Time"
chatrTime.Dock=ChartTitleDockStylle.Bottom;
chatrTime.Font=....

chart.Titles.AddRange(new ChartTitle[]{chartTime,chartY1,chartY2});
SecondaryAxisY myAxisY=new SecondaryAxisY();

((XYDiagram)chart.Diagram).SecondaryAxisY.Add(myAxisY);

xyDiagram.AxisX.DateTimeScaleOptions.MeasureUnit=DevExpress.XtraCharts.DateTimeMeasureUnit.Seconds;
}

Body:
To complete your chart layout initialization procedure, assign a newly created SecondaryAxisY element to the SeriesView.AxisY property of the second Series item.

    ((XYDiagram)chart.Diagram).SecondaryAxesY.Add(myAxisY);
    Series s2 = arrayOfSeries[1];
    ((LineSeriesView)s2.View).AxisY = myAxisY;

See also: How to: Add Secondary Axes to a Chart