问:
How to chain 3 laravel nested models
I am trying to chain 3 models together parent->child->child of child. So I can access it in an eloquent statement.

Parent Model:

```<code>class CertificationType extends Model
{
use SoftDeletes;

public $timestamps = true;

protected $table = 'certification_type';
protected $dates = ['deleted_at'];

protected $fillable = array('certification_type_name', 'fa_code', 'icon_image');
protected $hidden = ['created_at', 'updated_at',];

public function certification_type()
{
    return $this->hasMany('App\Certification');
    }

}
</code>```

Child Model

```<code>  class Certification extends Model
{
    protected $table = 'certification';
    public $timestamps = true;

    use SoftDeletes;

protected $dates = ['deleted_at'];

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = array('certification_type_id', 'certification_name', 'certication_date', 'certification_license_number', 'certification_course_length', 'certification_course_description', 'certification_course_topics_list_id');

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'created_at', 'updated_at',
];

public function certification_type()
{
    return $this->belongsTo('App\CertificationType',

'certification_type_id');
    }

    public function certification_course_topics_list()
    {
        return $this->hasMany('App\CertificationCourseTopicsList');
    }

}
</code>```

Child of Child Model

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class CertificationCourseTopicsList extends Model
{
    protected $table = 'certification_topics_list';
    public $timestamps = true;

    use SoftDeletes;

    protected $dates = ['deleted_at'];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = array('certification_id', 'certification_topic_description');

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'created_at', 'updated_at',
    ];

    public function certification_course_topics_list()
    {
        return $this->belongsToMany('App\Certification', 'certification_id');
    }
}
</code>```

The eloquent statement I am using is:

```<code>$CertificationTypes = App\CertificationType::orderBy('id',"asc")->with('certification_type')->get()->groupBy('id');
</code>```

What I have accomplished is CertificationType has a child of Certifications attached in the query. What I need is the 2nd child to be in the query as well:

CertificationType::orderBy('id',"asc")->with('certification_type')->get()->groupBy('id')->with('certification')->get()->groupBy('id');

I also tried:

```<code>CertificationType::orderBy('id',"asc")->with('certification_type, certifications')->get()->groupBy('id');
</code>```

That did not work: Call to undefined relationship [certification_type, certifications] on model [App\CertificationType].

Also tried:

```<code>CertificationType::orderBy('id',"asc")->with('certification_type', 'certifications')->get()->groupBy('id');
</code>```

That did not work: Call to undefined relationship [certifications] on model [App\CertificationType].

Any help would be appreciated!

答:
You need more order in code. I would make three models with proper relations as : belongsTo and hasMany. Then in each view you can use data from model with function of relation.

Example of proper model with relation:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}
</code>```

Read more here, that will save your time: https://laravel.com/docs/5.5/eloquent-relationships#one-to-many

Title: How to chain 3 laravel nested models

Body:
I am trying to chain 3 models together parent->child->child of child. So I can access it in an eloquent statement.

Parent Model:

class CertificationType extends Model
{
use SoftDeletes;

public $timestamps = true;

protected $table = 'certification_type';
protected $dates = ['deleted_at'];

protected $fillable = array('certification_type_name', 'fa_code', 'icon_image');
protected $hidden = ['created_at', 'updated_at',];

public function certification_type()
{
    return $this->hasMany('App\Certification');
    }

}

Child Model

  class Certification extends Model
{
    protected $table = 'certification';
    public $timestamps = true;

    use SoftDeletes;

protected $dates = ['deleted_at'];

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = array('certification_type_id', 'certification_name', 'certication_date', 'certification_license_number', 'certification_course_length', 'certification_course_description', 'certification_course_topics_list_id');

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'created_at', 'updated_at',
];

public function certification_type()
{
    return $this->belongsTo('App\CertificationType',

'certification_type_id');
    }

    public function certification_course_topics_list()
    {
        return $this->hasMany('App\CertificationCourseTopicsList');
    }

}

Child of Child Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class CertificationCourseTopicsList extends Model
{
    protected $table = 'certification_topics_list';
    public $timestamps = true;

    use SoftDeletes;

    protected $dates = ['deleted_at'];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = array('certification_id', 'certification_topic_description');

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'created_at', 'updated_at',
    ];

    public function certification_course_topics_list()
    {
        return $this->belongsToMany('App\Certification', 'certification_id');
    }
}

The eloquent statement I am using is:

$CertificationTypes = App\CertificationType::orderBy('id',"asc")->with('certification_type')->get()->groupBy('id');

What I have accomplished is CertificationType has a child of Certifications attached in the query. What I need is the 2nd child to be in the query as well:

CertificationType::orderBy('id',"asc")->with('certification_type')->get()->groupBy('id')->with('certification')->get()->groupBy('id');

I also tried:

CertificationType::orderBy('id',"asc")->with('certification_type, certifications')->get()->groupBy('id');

That did not work: Call to undefined relationship [certification_type, certifications] on model [App\CertificationType].

Also tried:

CertificationType::orderBy('id',"asc")->with('certification_type', 'certifications')->get()->groupBy('id');

That did not work: Call to undefined relationship [certifications] on model [App\CertificationType].

Any help would be appreciated!

Body:
You need more order in code. I would make three models with proper relations as : belongsTo and hasMany. Then in each view you can use data from model with function of relation.

Example of proper model with relation:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

Read more here, that will save your time: https://laravel.com/docs/5.5/eloquent-relationships#one-to-many


来源: stackexchange

问:
How to edit PostgreSQL stored procedure?
I'm slowly moving from MSSQL to PostgreSQL.

In MSSQL I could call editing of already saved procedure or function, and the administration shell (SQL Server Management Studio) showed me procedure's text, so I did not have to store its source code somewhere in text file.

How to do the same with PostgreSQL the convenient way? I'm using pgAdmin III.

答:
right click on the function in object tree (on the left side) -> Scripts -> Script CREATE

-or-

Execute new SQL query -> copy code of "create or replace function ..." to it

Then edit the script and do not forgot to execute it

ContentLicense: CC BY-SA 3.0


问:
Java 8, Lambda: Sorting within grouped Lists and merging all groups to a list
Based on the following answer: https://stackoverflow.com/a/30202075/8760211

How to sort each group by stud_id and then return a List with all Students as result of the grouping by stud_location and then sorting by stud_id)?

It would be great to have this as extension to the existing Lambda Expression:

```<code>Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));
</code>```

I need the Grouping based on the order of the Elements in the origin List.

```<code>First group: "New York"
Second group: "California"
Third group: "Los Angeles"

1726, "John", "New York"
4321, "Max", "California"
2234, "Andrew", "Los Angeles"
5223, "Michael", "New York"
7765, "Sam", "California"
3442, "Mark", "New York"
</code>```

The result would then look like the following:

```<code>List<Student> groupedAndSorted = ....

    1726, "John", "New York"
    3442, "Mark", "New York"
    5223, "Michael", "New York"
    4321, "Max", "California"
    7765, "Sam", "California"
    2234, "Andrew", "Los Angeles"
</code>```

I have tried the following:

```<code>studlistGrouped.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))
</code>```

But this doesn't work.

答:
You don't need to group by location, as the input and output have same datatype. You can just chain multiple Comparators and sort the input.

```<code>List<Student> groupedAndSorted = studlist.stream()
       .sorted(Comparator.comparing(Student::getStudLocation)
                .thenComparing(Comparator.comparing(Student::getStudId)))
                .thenComparing(Comparator.comparing(Student::getStudName)))
       .collect(Collectors.toList());
</code>```

As an offtopic, I would seggest that you change you data structure to use Lombok to auto-generate getters/setters/constructors https://projectlombok.org/features/Data . You should also use a more generic naming conversion, i.e. remove the "stud_" prefix of attributes.

```<code>import lombok.Data;
@Data
class Student {
    String id;
    String name;
    String location;
}
</code>```

Body:
Based on the following answer: https://stackoverflow.com/a/30202075/8760211

How to sort each group by stud_id and then return a List with all Students as result of the grouping by stud_location and then sorting by stud_id)?

It would be great to have this as extension to the existing Lambda Expression:

Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));

I need the Grouping based on the order of the Elements in the origin List.

First group: "New York"
Second group: "California"
Third group: "Los Angeles"

1726, "John", "New York"
4321, "Max", "California"
2234, "Andrew", "Los Angeles"
5223, "Michael", "New York"
7765, "Sam", "California"
3442, "Mark", "New York"

The result would then look like the following:

List<Student> groupedAndSorted = ....

    1726, "John", "New York"
    3442, "Mark", "New York"
    5223, "Michael", "New York"
    4321, "Max", "California"
    7765, "Sam", "California"
    2234, "Andrew", "Los Angeles"

I have tried the following:

studlistGrouped.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))

But this doesn't work.

Body:
You don't need to group by location, as the input and output have same datatype. You can just chain multiple Comparators and sort the input.

List<Student> groupedAndSorted = studlist.stream()
       .sorted(Comparator.comparing(Student::getStudLocation)
                .thenComparing(Comparator.comparing(Student::getStudId)))
                .thenComparing(Comparator.comparing(Student::getStudName)))
       .collect(Collectors.toList());

As an offtopic, I would seggest that you change you data structure to use Lombok to auto-generate getters/setters/constructors https://projectlombok.org/features/Data . You should also use a more generic naming conversion, i.e. remove the "stud_" prefix of attributes.

import lombok.Data;
@Data
class Student {
    String id;
    String name;
    String location;
}


问:
About IB,init,load view and view did load?
this is a quite general question but i want to understand this please -

I usually build my apps without using IB.

what are, the cons and pros of using IB vs. creating interface programmatically?

what oppressions/code fits the init method and what is for the loadView method?

is there any difference between loadView an ViewDidLoad or do i need to use only one of them?

thanks
shani

答:
One: Nibs are potentially a lot less work. If you have a huge block of early code consisting of lots of "create this label; set its font size to 14; place it at (12,12;128x96)" then you have a good candidate for loading from a nib instead.

Two: For objects in a nib, which init gets called at nib load, and related methods, can be nonobvious. The rules I've found are:

Objects of classes with direct IB support (UIViews, the builtin UIViewControllers) get created with initWithCoder:. This bypasses the normal designated initializer, because IB actually instantiated a real-live instance of that object while you were editing the nib (presumably with the normal designated initializer) and then serialized it. This has implications when you're subclassing those classes: only an instance of the UIKit base class got created and serialized in IB, so your initializers are bypassed completely. However, see below.

Objects instantiated with placeholders - The "NSObject" orange (or blue) cube - get created with normal init. This is because IB can't instantiate just any class; so it serializes a "placeholder object" into the nib, which then gets swapped for a fresh init-ed instance of the desired class at nib load. However:

Both of the above get awakeFromNib called. So you can do any special setup you like in there, if that object will always be created from a nib. With care, you can make a common setup method and call it from both awakeFromNib and your non-init initializers, to be able to use the class either from a nib or not.

of course none of the above applies to the "file's owner", which was created however you want and exists before the nib loads.

Three: In a UIViewController, loadView does the actual loading of the nib file (and provides a single empty view if there is no nib file.) Override if you want to create your views some other way. If you want to rearrange or add to what got loaded from the nib, viewDidLoad is a better place for that: there are circumstances where loadView never gets called but viewDidLoad still is. (e.g. when a VC and its view are both instantiated in the same nib; there's a reason apple recommends against this, even though it's handy sometimes.) viewDidLoad is also nicely balanced with viewDidUnload, so stuff allocated in viewDidLoad can and should be released in viewDidUnload.

Nibs are worth learning. Once you get the hang of it you'll love them; there's a reason they've stuck around since 1989.

ContentLicense: CC BY-SA 2.5


问:
Tensorflow training error in last step
I am trying to train my own model for tensorflow object detection, I followed this and this tutorials and in last step I tried to run this command

```<code>> python train.py --logtostderr --train_dir=training/ --
        pipeline_config_path=training/ssd_mobilenet_v1_pets.config
</code>```

but I get this error

```<code> > Traceback (most recent call last):
  File "train.py", line 163, in <module>
    tf.app.run()
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\platform\a
pp.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "train.py", line 91, in main
    FLAGS.pipeline_config_path)
  File "C:\Libraries\models-master\research\object_detection\utils\config_util.p
y", line 43, in get_configs_from_pipeline_file
    text_format.Merge(proto_str, pipeline_config)
  File "C:\Program Files\Python36\lib\site-packages\google\protobuf\text_format.
py", line 533, in Merge
    descriptor_pool=descriptor_pool)
  File "C:\Program Files\Python36\lib\site-packages\google\protobuf\text_format.
py", line 587, in MergeLines
    return parser.MergeLines(lines, message)
  File "C:\Program Files\Python36\lib\site-packages\google\protobuf\text_format.
py", line 620, in MergeLines
    self._ParseOrMerge(lines, message)
  File "C:\Program Files\Python36\lib\site-packages\google\protobuf\text_format.
py", line 635, in _ParseOrMerge
    self._MergeField(tokenizer, message)
  File "C:\Program Files\Python36\lib\site-packages\google\protobuf\text_format.
py", line 703, in _MergeField
    (message_descriptor.full_name, name))
google.protobuf.text_format.ParseError: 195:3 : Message type "object_detection.p
rotos.TrainEvalPipelineConfig" has no field named "shuffle".
</code>```

how can I solve it ?

答: I fix that problem with changing .config file. I used ssd_mobilenet_v1_coco.config instead of ssd_mobilenet_v1_pets.config</p>

Title: Tensorflow training error in last step

Body:
I am trying to train my own model for tensorflow object detection, I followed this and this tutorials and in last step I tried to run this command

> python train.py --logtostderr --train_dir=training/ --
        pipeline_config_path=training/ssd_mobilenet_v1_pets.config

but I get this error

 > Traceback (most recent call last):
  File "train.py", line 163, in <module>
    tf.app.run()
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\platform\a
pp.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "train.py", line 91, in main
    FLAGS.pipeline_config_path)
  File "C:\Libraries\models-master\research\object_detection\utils\config_util.p
y", line 43, in get_configs_from_pipeline_file
    text_format.Merge(proto_str, pipeline_config)
  File "C:\Program Files\Python36\lib\site-packages\google\protobuf\text_format.
py", line 533, in Merge
    descriptor_pool=descriptor_pool)
  File "C:\Program Files\Python36\lib\site-packages\google\protobuf\text_format.
py", line 587, in MergeLines
    return parser.MergeLines(lines, message)
  File "C:\Program Files\Python36\lib\site-packages\google\protobuf\text_format.
py", line 620, in MergeLines
    self._ParseOrMerge(lines, message)
  File "C:\Program Files\Python36\lib\site-packages\google\protobuf\text_format.
py", line 635, in _ParseOrMerge
    self._MergeField(tokenizer, message)
  File "C:\Program Files\Python36\lib\site-packages\google\protobuf\text_format.
py", line 703, in _MergeField
    (message_descriptor.full_name, name))
google.protobuf.text_format.ParseError: 195:3 : Message type "object_detection.p
rotos.TrainEvalPipelineConfig" has no field named "shuffle".

how can I solve it ?


问:
gradle: find to which project does a file belong
Let's consider this sample multi gradle project structure

```<code>build.gradle
|-- project-a
|   |-- build.gradle
|   +-- project-a-b
|       |--  src
|       |    |
|       |    +-- test.java
|       |
|       +-- build.gradle
+-- project-c
    |-- build.gradle
    +-- src
        +-- test2.java
</code>```

And let's say from git changelog I have changed files:

```<code>project-a/project-a-b/src/test.java
project-c/src/test2.java
</code>```

I need to find out to which project they belong

```<code>project-a/project-a-b/src/test.java -> project-a-b
project-c/src/test2.java -> project-c
</code>```

Is there something that gradle offers out of the box (e.g. give filename, get nearest project)? Googling did not help, but maybe the question was wrong.

I know I could just put filesystem in a tree structure and traverse it

答:
As mentioned it might depend on criteria for belongs to...

Given above example the owning project is named by the parent directory of the src directory. I.e. you can see it directly in your Git changeset/changelog.

Body:
Let's consider this sample multi gradle project structure

build.gradle
|-- project-a
|   |-- build.gradle
|   +-- project-a-b
|       |--  src
|       |    |
|       |    +-- test.java
|       |
|       +-- build.gradle
+-- project-c
    |-- build.gradle
    +-- src
        +-- test2.java

And let's say from git changelog I have changed files:

project-a/project-a-b/src/test.java
project-c/src/test2.java

I need to find out to which project they belong

project-a/project-a-b/src/test.java -> project-a-b
project-c/src/test2.java -> project-c

Is there something that gradle offers out of the box (e.g. give filename, get nearest project)? Googling did not help, but maybe the question was wrong.

I know I could just put filesystem in a tree structure and traverse it


问:
How to increase the height of UITableView dynamically as per TableViewCell?
If I want to change the height of UITableView as per the cell content changes i.e. the height of UITableViewCell increase as API response come different every time?
Please help me to find out a solution?</p>

答:
If your receiving response in array then you can increase the height with array counts by reload your table view tableView.reloadData() when you are receiving the responses.

```<code>override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

 if indexPath.section == 0 {
  switch indexPath.row {
  case 0:
    return 50
  case 1:
    return 60
  case 2:
    if array.count > 0{
      return (CGFloat(45* array.count))
    }else{
      return 0
    }
   default:
    return 0
   }
 }
}
</code>```

Body:
If your receiving response in array then you can increase the height with array counts by reload your table view tableView.reloadData() when you are receiving the responses.

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

 if indexPath.section == 0 {
  switch indexPath.row {
  case 0:
    return 50
  case 1:
    return 60
  case 2:
    if array.count > 0{
      return (CGFloat(45* array.count))
    }else{
      return 0
    }
   default:
    return 0
   }
 }
}


问:
Distribute iOS app for specific region/territory
I am about to release my App, just waiting for my Apple Developer to come in.

Can I decide the countries where my app will be available to download from? Or will I only be able to choose one single country/whole Europe/World?

Say I wanted to make my app available in Europe but not in Portugal - Is that possible?.......

答:
Follow my steps in iTunes store to update territory:

```<code>   1) Open Pricing and Availability
    2) Click on Edit on Availability

    You can tick mark only those territories in which you want your application.
</code>```

Body:
Follow my steps in iTunes store to update territory:

   1) Open Pricing and Availability
    2) Click on Edit on Availability

    You can tick mark only those territories in which you want your application.


问:
How best to do a JavaScript array with non-consecutive indexes?
I'm writing a Google Chrome extension, in JavaScript, and I want to use an array to store a bunch of objects, but I want the indexes to be specific non-consecutive ID numbers.

(This is because I need to be able to efficiently look up the values later, using an ID number that comes from another source outside my control.)

For example:

```<code>var myObjects = [] ;

myObjects[471] = {foo: "bar"} ;

myObjects[3119] = {hello: "goodbye"}
</code>```

When I do console.log(myObjects), in the console I see the entire array printed out, with all the thousands of 'missing' indexes showing undefined.

My question is: does this matter? Is this wasting any memory?

And even if it's not wasting memory, surely whenever I loop over the array, it wastes CPU if I have to manually skip over every missing value?

I tried using an object instead of an array, but it seems you can't use numbers as object keys. I'm hoping there's a better way to achieve this?

答:
I would simply use a constant prefix, to avoid such problems.

```<code>var myObjects = {};
myObjects['objectId_'+365] = {test: 3};
</code>```

will default to Js-Objects.

Body:
I'm writing a Google Chrome extension, in JavaScript, and I want to use an array to store a bunch of objects, but I want the indexes to be specific non-consecutive ID numbers.

(This is because I need to be able to efficiently look up the values later, using an ID number that comes from another source outside my control.)

For example:

var myObjects = [] ;

myObjects[471] = {foo: "bar"} ;

myObjects[3119] = {hello: "goodbye"}

When I do console.log(myObjects), in the console I see the entire array printed out, with all the thousands of 'missing' indexes showing undefined.

My question is: does this matter? Is this wasting any memory?

And even if it's not wasting memory, surely whenever I loop over the array, it wastes CPU if I have to manually skip over every missing value?

I tried using an object instead of an array, but it seems you can't use numbers as object keys. I'm hoping there's a better way to achieve this?

Body:
I would simply use a constant prefix, to avoid such problems.

var myObjects = {};
myObjects['objectId_'+365] = {test: 3};

will default to Js-Objects.


问:
IPC Connection in child-process library is not duplex
The following javascript represents the parent process:

```<code>this.sso = fork('./app/utils/SSOproxy.js', [], {
    stdio: [0, 1, 2, 'ipc']
});

//__handshake
this.sso.send({
    opcode:'ACK',
    params: [],
    ref: null
});
console.log('STEP_1');
//__main
process.on('message', ((msg)=>{
    switch (msg.opcode){
        case 'ACK':
            (msg.params[0] === 'ok')
                console.log('STEP_3');
            break;
</code>```

It shows a partial implementation of a simple handshake protocol.
And the child process' partial:

```<code>process.on('message', ((msg)=>{
switch (msg.opcode){
    //handshake
    case 'ACK':
        process.send({
            opcode:'ACK',
            params:['ok'],
            ref: null
        });
        console.log('STEP_2');
        break;
</code>```

My problem is that in the console (keep in mind both processes share all in/out/err streams) I do not observe STEP_3; and this is due to the absence of child to parent communication.
Any thoughts as to why this might be?

答:
I think you need listen child process (this.sso ) instead main process:

```<code>//__main
this.sso.on('message', ((msg)=>{
    switch (msg.opcode){
        case 'ACK':
            (msg.params[0] === 'ok')
                console.log('STEP_3');
            break;
</code>```

Body:
The following javascript represents the parent process:

this.sso = fork('./app/utils/SSOproxy.js', [], {
    stdio: [0, 1, 2, 'ipc']
});

//__handshake
this.sso.send({
    opcode:'ACK',
    params: [],
    ref: null
});
console.log('STEP_1');
//__main
process.on('message', ((msg)=>{
    switch (msg.opcode){
        case 'ACK':
            (msg.params[0] === 'ok')
                console.log('STEP_3');
            break;

It shows a partial implementation of a simple handshake protocol.
And the child process' partial:

process.on('message', ((msg)=>{
switch (msg.opcode){
    //handshake
    case 'ACK':
        process.send({
            opcode:'ACK',
            params:['ok'],
            ref: null
        });
        console.log('STEP_2');
        break;

My problem is that in the console (keep in mind both processes share all in/out/err streams) I do not observe STEP_3; and this is due to the absence of child to parent communication.
Any thoughts as to why this might be?

Body:
I think you need listen child process (this.sso ) instead main process:

//__main
this.sso.on('message', ((msg)=>{
    switch (msg.opcode){
        case 'ACK':
            (msg.params[0] === 'ok')
                console.log('STEP_3');
            break;


问:
Can I bind one element of class to another while initializing in one line?
I have a class (struct) like this:

```<code>type Question struct{
    Question string
    answerOne string
    answerTwo string
    answerCorrect string
}
</code>```

And I initialize it like this:

```<code>q1:=Question{
    Question:"What?",
    answerOne:"A",
    answerTwo:"B",
    answerCorrect: ? //I want this have similar value as `answerOne`
}
</code>```

While initilizing I want one of my values have similar value as another one. Is there any way to do that?

答:
You cannot by using only literals, but you could define a function.</p>

```<code>func NewQuestion() *Question {
    q := &Question{
        Question:  "What?",
        answerOne: "A",
        answerTwo: "B",
    }
    q.answerCorrect = q.answerOne
    return q
}

// ...

q1 := NewQuestion()
</code>```

Body:
I have a class (struct) like this:

type Question struct{
    Question string
    answerOne string
    answerTwo string
    answerCorrect string
}

And I initialize it like this:

q1:=Question{
    Question:"What?",
    answerOne:"A",
    answerTwo:"B",
    answerCorrect: ? //I want this have similar value as `answerOne`
}

While initilizing I want one of my values have similar value as another one. Is there any way to do that?

Body:
You cannot by using only literals, but you could define a function.

func NewQuestion() *Question {
    q := &Question{
        Question:  "What?",
        answerOne: "A",
        answerTwo: "B",
    }
    q.answerCorrect = q.answerOne
    return q
}

// ...

q1 := NewQuestion()


问:
How can I let the javascript catch a signal from node and prompt a window right after that?
I want to emit a signal from the app.js. The ejs file should catch it and prompt a window. The problem is I have to refresh the page to see the window. Also it seems it will be always shown if I refresh it again.

How can I let the window prompt immediately right after I send the signal from app.js? And only show once?

in the app.js

```<code>socket.emit('example_signal')
</code>```

in the sample.ejs file

```<code>socket.on('example_signal', function(){
    alert('hello world')
})
</code>```

it seems I found the cause of this problem. if I wrote

```<code>io.sockets.emit('example_signal')
</code>```

directly, then the signal will be caught immediately. If I wrote it as

```<code> io.sockets.on('connection', function (socket) {
    io.sockets.emit('example_signal')
 })
</code>```

it will somehow wait for the page refresh...

Hope it can help others who encounter the same problem

答:
```<code>io.sockets.on('connection', function (socket) {
    io.sockets.emit('example_signal')
})
</code>```

it will somehow wait for the page refresh...

Because that is what that code says:

When the browser connects to the socket, emit a signal

… and the browser will connect to the socket when the page loads.

Removing the event handler that waits for a new connection will, naturally, cause the line io.sockets.emit('example_signal') to run immediately instead of waiting for the event.

Body:
I want to emit a signal from the app.js. The ejs file should catch it and prompt a window. The problem is I have to refresh the page to see the window. Also it seems it will be always shown if I refresh it again.

How can I let the window prompt immediately right after I send the signal from app.js? And only show once?

in the app.js

socket.emit('example_signal')

in the sample.ejs file

socket.on('example_signal', function(){
    alert('hello world')
})

it seems I found the cause of this problem. if I wrote

io.sockets.emit('example_signal')

directly, then the signal will be caught immediately. If I wrote it as

 io.sockets.on('connection', function (socket) {
    io.sockets.emit('example_signal')
 })

it will somehow wait for the page refresh...

Hope it can help others who encounter the same problem

Body:
io.sockets.on('connection', function (socket) {
    io.sockets.emit('example_signal')
})

it will somehow wait for the page refresh...

Because that is what that code says:

When the browser connects to the socket, emit a signal

… and the browser will connect to the socket when the page loads.

Removing the event handler that waits for a new connection will, naturally, cause the line io.sockets.emit('example_signal') to run immediately instead of waiting for the event.


问:
Index find position for matching string
Consider following example

```<code>index_abcd = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
data = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
df = pd.DataFrame(data, index=index_abcd)
index_id= df.index
</code>```

I want to find the position of 'a' in the index "index_id". How do I do that. Trying

```<code>index_id.index('a')
</code>```

does not work (error 'Index' object has no attribute 'index'). Thanks a lot

答:
I suggest you to type :</p>

```<code>index_id.get_loc("a")
</code>```

Title: Index find position for matching string

Body:
Consider following example

index_abcd = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
data = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
df = pd.DataFrame(data, index=index_abcd)
index_id= df.index

I want to find the position of 'a' in the index "index_id". How do I do that. Trying

index_id.index('a')

does not work (error 'Index' object has no attribute 'index'). Thanks a lot

Body:
I suggest you to type :

index_id.get_loc("a")


问:
Difference between Return and Break statements
How does a return statement differ from break statement?.

If I have to exit an if condition, which one should I prefer, return or break?

答:
Break statement will break the whole loop and execute the code after loop  and Return will not execute the code after that return statement and execute the loop with next increment.

Break

```<code>for(int i=0;i<5;i++){
    print(i)
    if(i==2)
    {
      break;
    }
}
</code>```

output: 0 1

return

```<code>for(int i=0;i<5;i++)
{
   print(i)
   if(i==2)
   {
    return;
   }
}
</code>```

output: 0 1 3 4

Body:
Break statement will break the whole loop and execute the code after loop  and Return will not execute the code after that return statement and execute the loop with next increment.

Break

for(int i=0;i<5;i++){
    print(i)
    if(i==2)
    {
      break;
    }
}

output: 0 1

return

for(int i=0;i<5;i++)
{
   print(i)
   if(i==2)
   {
    return;
   }
}

output: 0 1 3 4


问:
Fedora phpMyAdmin error: The mbstring extension is missing
The mbstring extension is missing. Please check your PHP configuration

I have installed LAMP on Fedora following this tutorial with some change, The installation finished with no problem. But when I tried to access http://localhost/phpmyadmin, this error notify appear. I have already search on google and try all option on the thread linked above.

I changed php.ini configuration:

```<code>extension=mbstring.so
</code>```

where the extension dir is like this

```<code>extension_dir = "/usr/lib64/php/modules"
</code>```

This are the Extensions on /usr/lib64/php/modules

答:
From this article, I found out that we need restart php-fpm, this solution not mentioned on other tutorial/thread that I have been read.

just run:

```<code>systemctl restart php-fpm
</code>```

Body:
The mbstring extension is missing. Please check your PHP configuration

I have installed LAMP on Fedora following this tutorial with some change, The installation finished with no problem. But when I tried to access http://localhost/phpmyadmin, this error notify appear. I have already search on google and try all option on the thread linked above.

I changed php.ini configuration:

extension=mbstring.so

where the extension dir is like this

extension_dir = "/usr/lib64/php/modules"

This are the Extensions on /usr/lib64/php/modules

Body:
From this article, I found out that we need restart php-fpm, this solution not mentioned on other tutorial/thread that I have been read.

just run:

systemctl restart php-fpm


问:
Mixed-Content over https because an insecure XMLHttpRequest request
I know that something is calling over http instead of https, but actually I don't know how to fix this issue!

```<code>$.ajax({
    type: "GET",
    url: window.location.href.substring(0, location.href.lastIndexOf("/") + 1) + '/MyService.asmx/MyMethod';,
    data: 'param=' + JSON.stringify({ "myParam": value.trim() });,
    dataType: "text",
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    }, ...
</code>```

I even tried this way but no success:

```<code>Url: '//MyService.asmx/MyMethod';
</code>```

Given error is:
Mixed Content: The page at 'https://www.example.com/MyPage.aspx' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://www.example.com/MyService.asmx?param=paramValue'. This request has been blocked; the content must be served over HTTPS.

Any suggestion?

答:
There are several things that might trigger this error.

First of all, change the javascript that construts your url to

```<code>window.location.href.substring(0, location.href.lastIndexOf("/") + 1) + 'MyService.asmx/MyMethod'
</code>```

(remove slash before MyService.asmx and the semicolon at the end)

Try to console.log() the url this code produce and try if it's accessible via HTTPS in your browser. What might be happening is that if the url is unreachable there might be a redirect to non-https url. Also you can use browser debug tools (like chrome inspect  Network tab) to see what's happening with your request (look for status code, check the response headers etc.).

Body:
I know that something is calling over http instead of https, but actually I don't know how to fix this issue!

$.ajax({
    type: "GET",
    url: window.location.href.substring(0, location.href.lastIndexOf("/") + 1) + '/MyService.asmx/MyMethod';,
    data: 'param=' + JSON.stringify({ "myParam": value.trim() });,
    dataType: "text",
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    }, ...

I even tried this way but no success:

Url: '//MyService.asmx/MyMethod';

Given error is:
Mixed Content: The page at 'https://www.example.com/MyPage.aspx' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://www.example.com/MyService.asmx?param=paramValue'. This request has been blocked; the content must be served over HTTPS.

Any suggestion?

Body:
There are several things that might trigger this error.

First of all, change the javascript that construts your url to

window.location.href.substring(0, location.href.lastIndexOf("/") + 1) + 'MyService.asmx/MyMethod'

(remove slash before MyService.asmx and the semicolon at the end)

Try to console.log() the url this code produce and try if it's accessible via HTTPS in your browser. What might be happening is that if the url is unreachable there might be a redirect to non-https url. Also you can use browser debug tools (like chrome inspect  Network tab) to see what's happening with your request (look for status code, check the response headers etc.).


问:
MVC how to change dropdownlist item names
Been googling for a while, but I can't seem to get any closer.

I'm using MVC with an EF Database structure.

I want the dropdownlist items in the View to show up with different names than what they come up with.

Right now, the lambda query returns a list().
I want each item to get a string name depending on their current name.  Eventually, the selected field needs to be used in another lambda as the Byte that it was.

Edit

```<code>//view
<p>
@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<p>
    @Html.DropDownList("vbType", (SelectList)ViewBag.Type, "" , new { onchange = "form.submit();" })

....

//controller
var typeLst = new List<byte>();
var typeQry = from t in db.model1
       orderby t.TYPE
       select t.TYPE;
typeLst.AddRange(typeQry.Distinct());
ViewBag.vbType = new SelectList(typeLst);

....
</code>```

Thanks in advance.

答:
You can create a SelectListItem to display in your dropdownlist.

Example:

```<code>@Html.DropDownListFor(model => model.YearStartedToPay,
       Enumerable.Range(DateTime.Today.Year - 60, 61).OrderByDescending(x => int.Parse(x.ToString())).Select(n => new SelectListItem() { Text = n.ToString(), Value = n.ToString(), Selected = false }).ToList<SelectListItem>(),....)
</code>```

In this case, I'm creating an Enumerable, that will be your list returned from EF, ordering and selecting as a SelectListItem.

Body:
Been googling for a while, but I can't seem to get any closer.

I'm using MVC with an EF Database structure.

I want the dropdownlist items in the View to show up with different names than what they come up with.

Right now, the lambda query returns a list().
I want each item to get a string name depending on their current name.  Eventually, the selected field needs to be used in another lambda as the Byte that it was.

Edit

//view

@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{

    @Html.DropDownList("vbType", (SelectList)ViewBag.Type, "" , new { onchange = "form.submit();" })

....

//controller
var typeLst = new List<byte>();
var typeQry = from t in db.model1
       orderby t.TYPE
       select t.TYPE;
typeLst.AddRange(typeQry.Distinct());
ViewBag.vbType = new SelectList(typeLst);

....

Thanks in advance.

Body:
You can create a SelectListItem to display in your dropdownlist.

Example:

@Html.DropDownListFor(model => model.YearStartedToPay,
       Enumerable.Range(DateTime.Today.Year - 60, 61).OrderByDescending(x => int.Parse(x.ToString())).Select(n => new SelectListItem() { Text = n.ToString(), Value = n.ToString(), Selected = false }).ToList<SelectListItem>(),....)

In this case, I'm creating an Enumerable, that will be your list returned from EF, ordering and selecting as a SelectListItem.


问:
String URL to RouteValueDictionary
Is there as easy way to convert string URL to RouteValueDictionary collection? Some method like UrlToRouteValueDictionary(string url).

I need such method because I want to 'parse' URL according to my routes settings, modify some route values and using urlHelper.RouteUrl() generate string URL according to modified RouteValueDictionary  collection.

Thanks.

答:
I wouldn't rely on RouteTable.Routes.GetRouteData from previous examples because in that case you risk missing some values (for example if your query string parameters don't fully fit any of registered mapping routes). Also, my version doesn't require mocking a bunch of request/response/context objects.</p>

```<code>public static RouteValueDictionary UrlToRouteValueDictionary(string url)
{
    int queryPos = url.IndexOf('?');

    if (queryPos != -1)
    {
        string queryString = url.Substring(queryPos + 1);
        var valuesCollection = HttpUtility.ParseQueryString(queryString);
        return new RouteValueDictionary(valuesCollection.AllKeys.ToDictionary(k => k, k => (object)valuesCollection[k]));
    }

    return new RouteValueDictionary();
}
</code>```

Title: String URL to RouteValueDictionary

Body:
I wouldn't rely on RouteTable.Routes.GetRouteData from previous examples because in that case you risk missing some values (for example if your query string parameters don't fully fit any of registered mapping routes). Also, my version doesn't require mocking a bunch of request/response/context objects.

public static RouteValueDictionary UrlToRouteValueDictionary(string url)
{
    int queryPos = url.IndexOf('?');

    if (queryPos != -1)
    {
        string queryString = url.Substring(queryPos + 1);
        var valuesCollection = HttpUtility.ParseQueryString(queryString);
        return new RouteValueDictionary(valuesCollection.AllKeys.ToDictionary(k => k, k => (object)valuesCollection[k]));
    }

    return new RouteValueDictionary();
}


问:
Burp Tool configuration
I am trying to configure BURP Tool. Following things i have done:

1) Ran web-application using tomcat port no : 8080,
2) Changed network to proxy 127.0.0.1:8080 in tomcat, and installed burp certificate in authorities
3) In burp tool, the proxy -> options -> intercept is running.

When i try to run my application i am getting following error message.

Invalid client request received: Dropped request looping back to same Proxy listener.

Can someone help me on this? Thanks in advance!!

答:
Is Tomcat running on the the same system as Burp? If it is, you need to use a different port number.

What URL did you enter to your browser? The symptoms you describe look like you used http://127.0.0.1:8080 - which points to your proxy. Instead, you need to enter the URL for Tomcat, e.g. http://mytomcat:8080

Title: Burp Tool configuration


问:
Method expression is not of Function type
I have the following JavaScript file:

```<code>/*global $ */

function foo() {
    'use strict';
    var $tr = $('table tr'),
        $td = $tr.children('td');

    $td.html('Hello World');
}
</code>```

In PHPStorm, children gets underlined with a weak warning. Mousing over it reveals this message:

Method expression is not of Function type

This file is in the same directory as jquery.min.js (v. 1.11.0, if that matters).

How can I fix this?

Note that the above example is a minimalist example sufficient to reproduce the problem; it's not my actual code, but it will product the same result.

答:
Another solution would be to add jQuery as a library here:

Settings/Preferences dialog, click JavaScript under Languages and Frameworks, then click Libraries.

Body:
I have the following JavaScript file:

/*global $ */

function foo() {
    'use strict';
    var $tr = $('table tr'),
        $td = $tr.children('td');

    $td.html('Hello World');
}

In PHPStorm, children gets underlined with a weak warning. Mousing over it reveals this message:

Method expression is not of Function type

This file is in the same directory as jquery.min.js (v. 1.11.0, if that matters).

How can I fix this?

Note that the above example is a minimalist example sufficient to reproduce the problem; it's not my actual code, but it will product the same result.


问:
cannot "enable debugger" in server explorer for azure vm, visual studio 2017
What can be the reason I cannot enable debugger for some of my VM's in server explorer?

I try to follow this guide:

https://learn.microsoft.com/en-us/azure/vs-azure-tools-debug-cloud-services-virtual-machines

When I right click on the VM in Visual Studio Server Explorer I do not get the same options as in the tutorial:

This is the menu I expected to see (from the tutorial):

答:
This is because that your VMs are ARM VM, not Classic VM.

I did a test in my Lab, and found that  I cannot enable debugger on my ARM VM neither. But I can enable debug on a classic VM. (Pay attention to two different types the icon of VMs)

For a classic VM, you can enable debugger on it and then Attach debugger.

The official document doesn't clarify this feature is only for classic VM. But the icon for the screenshots are all for Classic VM.

So, we cannot enable Debugger on a ARM VM from Visual studio. If this feature is very important to you, you can post your idea in this Feedback Forum.

Hope this helps!


问:
One-liner Algorithm to Combine Arrays into Arrays of All Possible Value Combinations?
Not quite sure I have the question fully formed, but what I'm trying to do is basically this:

```<code># where the indices correspond to attributes fore example:
# [type, status]
x = %w(a b)
y = %w(c d)
combine(x, y) #=> [["a", "b"], ["a", "d"], ["c", "a"], ["c", "b"]]
</code>```

The order of the array is always the same, so the reverse of each, such as [b, a], are not included in the result.

What is this called and what's an efficient way to implement this?

I see Array#permutation, but that's not quite it...

This would hopefully work for any number of arrays and values: combine(*arrays)

Thanks!

Update

Here's a better example of what I'm looking for:

This (x | y).combination(x.length).to_a produces the following:

```<code>x = ["front_door", "open"]
y = ["back_door", "closed"]
(x | y).combination(x.length).to_a
=> [["front_door", "open"], ["front_door", "back_door"], ["front_door", "closed"], ["open", "back_door"], ["open", "closed"], ["back_door", "closed"]]
</code>```

The actual result I'm looking for is this:

```<code>=> [["front_door", "open"], ["front_door", "closed"], ["back_door", "open"], ["back_door", "closed"]]
</code>```

Or if it were a longer array:

```<code>x = ["house", "front_door", "open"]
y = ["building", "back_door", "closed"]
compute(x, y)
=> ["house", "front_door", "open"], ["house", "back_door", "open"], ["house", "front_door", "closed"], ["house", "back_door", "closed"], ["building", "front_door", "open"], ["building", "back_door", "open"], ["building", "front_door", "closed"], ["building", "back_door", "closed"]
</code>```

Any ideas?

答:
```
<code>
x.zip(y).reduce(:product).map(&:flatten)
</code>
```

And for several arrays:

```
<code>
x.zip(y,z,w).reduce(:product).map(&:flatten)
</code>
```

Body:
Not quite sure I have the question fully formed, but what I'm trying to do is basically this:

# where the indices correspond to attributes fore example:
# [type, status]
x = %w(a b)
y = %w(c d)
combine(x, y) #=> [["a", "b"], ["a", "d"], ["c", "a"], ["c", "b"]]

The order of the array is always the same, so the reverse of each, such as [b, a], are not included in the result.

What is this called and what's an efficient way to implement this?

I see Array#permutation, but that's not quite it...

This would hopefully work for any number of arrays and values: combine(*arrays)

Thanks!

Update

Here's a better example of what I'm looking for:

This (x | y).combination(x.length).to_a produces the following:

x = ["front_door", "open"]
y = ["back_door", "closed"]
(x | y).combination(x.length).to_a
=> [["front_door", "open"], ["front_door", "back_door"], ["front_door", "closed"], ["open", "back_door"], ["open", "closed"], ["back_door", "closed"]]

The actual result I'm looking for is this:

=> [["front_door", "open"], ["front_door", "closed"], ["back_door", "open"], ["back_door", "closed"]]

Or if it were a longer array:

x = ["house", "front_door", "open"]
y = ["building", "back_door", "closed"]
compute(x, y)
=> ["house", "front_door", "open"], ["house", "back_door", "open"], ["house", "front_door", "closed"], ["house", "back_door", "closed"], ["building", "front_door", "open"], ["building", "back_door", "open"], ["building", "front_door", "closed"], ["building", "back_door", "closed"]

Any ideas?

Body:
x.zip(y).reduce(:product).map(&:flatten)

And for several arrays:

x.zip(y,z,w).reduce(:product).map(&:flatten)


问:
move_uploaded_file doesn't work, no error
I am running running a script which moves an uploaded file with move_uploaded_file(). I have done this thousands of times but for some reason it's not working. I have confimred the following:

<form> using method="post" and correct enctype

correct file referenced from form

directory has permissions 777

all the memory_limit, max_execution_time, etc are set to super high settings to avoid timeouts

Basically, the script below returns with just Your image is too big.. I have also enabled ALL errors to display and still don't get an error. Any ideas?

```<code>$time = time();
$target_path = "/absolute/path/to/temp/directory/temp/";

$target_path = $target_path.$time.'.jpg';

if(move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {

} else{
        $error .= '<li>Your image is too big.</li>';
}
</code>```

Using 1and1 hosting with the php.ini hack :P

UPDATE 1

I would like to add that response from the script occurs exactly after 60 seconds.

UPDATE 2

We might be getting somewhere with this. Just print_r($_FILES) and this is the result of the array:

```<code>Array (
    [image] => Array (
        [name] => P2120267.JPG
        [type] =>
        [tmp_name] =>
        [error] => 1
        [size] => 0
    )
)
</code>```

So that leads me to believe that the file isn't be uploaded correctly to the server or something? I have checked and the post form is <form action="" method="post" enctype="multipart/form-data">. So, from what I can tell, the file isn't being uploaded to the server's temp area?

UPDATE 3

Noticed the [error] => 1 in the above array. This is apparently down to the filesize being larger than the upload_max_filesize. However, when i set this as 128M, I get a white screen of death after 60 seconds. The file I'm uploading is 2.5MB

Here is my php.ini file:

```<code>register_globals=off
memory_limit = 128M
max_execution_time=3600
post_max_size = 128M
upload_max_filesize= 128M
</code>```

UPDATE 4

With details above, it appears that I am getting a WSOD, but the image is being upoaded. So, how to stop the WSOD? I can't find any errors related anywhere.

UPDATE 5 - FOUND IT!

Shame on me for not giving you guys all the code. It looks like its to do with this line:

```<code>resizeImage($feedBurnerStatsSource, PHOTOMSGDIR.'temp/'.$time.'-tmp.jpg',$width,$height);
</code>```

In the following code:

```<code>function resizeImage($source, $destination = NULL,$wdt, $height = NULL){
    if(empty($height)){
            // Height is nit set so we are keeping the same aspect ratio.
            list($width, $height) = getimagesize($source);
            if($width > $height){
                    $w = $wdt;
                    $h = ($height / $width) * $w;
                    $w = $w;
            }else{
                    $w = $wdt;
                    $h = $w;
                    $w = ($width / $height) * $w;
            }
    }else{
            // Both width and Height are set.
            // this will reshape to the new sizes.
            $w = $wdt;
            $h = $height;
    }
    $source_image = @file_get_contents($source) or die('Could not open'.$source);
    $source_image = @imagecreatefromstring($source_image) or die($source.' is not a valid image');
    $sw = imagesx($source_image);
    $sh = imagesy($source_image);
    $ar = $sw/$sh;
    $tar = $w/$h;
    if($ar >= $tar){
            $x1 = round(($sw - ($sw * ($tar/$ar)))/2);
            $x2 = round($sw * ($tar/$ar));
            $y1 = 0;
            $y2 = $sh;
    }else{
            $x1 = 0;
            $y1 = 0;
            $x2 = $sw;
            $y2 = round($sw/$tar);
    }
    $slate = @imagecreatetruecolor($w, $h) or die('Invalid thumbnail dimmensions');
    imagecopyresampled($slate, $source_image, 0, 0, $x1, $y1, $w, $h, $x2, $y2);
    // If $destination is not set this will output the raw image to the browser and not save the file
    if(!$destination) header('Content-type: image/jpeg');
    @imagejpeg($slate, $destination, 75) or die('Directory permission problem');
    ImageDestroy($slate);
    ImageDestroy($source_image);
    if(!$destination) exit;
    return true;
}
</code>```

So, WSOD means that its some sort of die without a message. Any ideas?

答: I had same problem, but I wanted to overwrite a file, so I have to delete old file and than it works.</p>

Body:
I am running running a script which moves an uploaded file with move_uploaded_file(). I have done this thousands of times but for some reason it's not working. I have confimred the following:

<form> using method="post" and correct enctype

correct file referenced from form

directory has permissions 777

all the memory_limit, max_execution_time, etc are set to super high settings to avoid timeouts

Basically, the script below returns with just Your image is too big.. I have also enabled ALL errors to display and still don't get an error. Any ideas?

$time = time();
$target_path = "/absolute/path/to/temp/directory/temp/";

$target_path = $target_path.$time.'.jpg';

if(move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {

} else{
        $error .= '
Your image is too big.
';
}

Using 1and1 hosting with the php.ini hack :P

UPDATE 1

I would like to add that response from the script occurs exactly after 60 seconds.

UPDATE 2

We might be getting somewhere with this. Just print_r($_FILES) and this is the result of the array:

Array (
    [image] => Array (
        [name] => P2120267.JPG
        [type] =>
        [tmp_name] =>
        [error] => 1
        [size] => 0
    )
)

So that leads me to believe that the file isn't be uploaded correctly to the server or something? I have checked and the post form is <form action="" method="post" enctype="multipart/form-data">. So, from what I can tell, the file isn't being uploaded to the server's temp area?

UPDATE 3

Noticed the [error] => 1 in the above array. This is apparently down to the filesize being larger than the upload_max_filesize. However, when i set this as 128M, I get a white screen of death after 60 seconds. The file I'm uploading is 2.5MB

Here is my php.ini file:

register_globals=off
memory_limit = 128M
max_execution_time=3600
post_max_size = 128M
upload_max_filesize= 128M

UPDATE 4

With details above, it appears that I am getting a WSOD, but the image is being upoaded. So, how to stop the WSOD? I can't find any errors related anywhere.

UPDATE 5 - FOUND IT!

Shame on me for not giving you guys all the code. It looks like its to do with this line:

resizeImage($feedBurnerStatsSource, PHOTOMSGDIR.'temp/'.$time.'-tmp.jpg',$width,$height);

In the following code:

function resizeImage($source, $destination = NULL,$wdt, $height = NULL){
    if(empty($height)){
            // Height is nit set so we are keeping the same aspect ratio.
            list($width, $height) = getimagesize($source);
            if($width > $height){
                    $w = $wdt;
                    $h = ($height / $width) * $w;
                    $w = $w;
            }else{
                    $w = $wdt;
                    $h = $w;
                    $w = ($width / $height) * $w;
            }
    }else{
            // Both width and Height are set.
            // this will reshape to the new sizes.
            $w = $wdt;
            $h = $height;
    }
    $source_image = @file_get_contents($source) or die('Could not open'.$source);
    $source_image = @imagecreatefromstring($source_image) or die($source.' is not a valid image');
    $sw = imagesx($source_image);
    $sh = imagesy($source_image);
    $ar = $sw/$sh;
    $tar = $w/$h;
    if($ar >= $tar){
            $x1 = round(($sw - ($sw * ($tar/$ar)))/2);
            $x2 = round($sw * ($tar/$ar));
            $y1 = 0;
            $y2 = $sh;
    }else{
            $x1 = 0;
            $y1 = 0;
            $x2 = $sw;
            $y2 = round($sw/$tar);
    }
    $slate = @imagecreatetruecolor($w, $h) or die('Invalid thumbnail dimmensions');
    imagecopyresampled($slate, $source_image, 0, 0, $x1, $y1, $w, $h, $x2, $y2);
    // If $destination is not set this will output the raw image to the browser and not save the file
    if(!$destination) header('Content-type: image/jpeg');
    @imagejpeg($slate, $destination, 75) or die('Directory permission problem');
    ImageDestroy($slate);
    ImageDestroy($source_image);
    if(!$destination) exit;
    return true;
}

So, WSOD means that its some sort of die without a message. Any ideas?


问:
is this approach unidirectional or bidirectional
Consider following entities

UserDetails (with Vehicles)

```<code>@Entity
public class UserDetails {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
private String userName;

@OneToMany(mappedBy="user",cascade=CascadeType.ALL,orphanRemoval=true)
private List<Vehicle> vehicleList = new ArrayList<>();

//getter setters
}
</code>```

Vehicle

```<code>@Entity
public class Vehicle {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int vehicleId;
private String vehicleName;

@ManyToOne
@JoinColumn(name="user_id")
private UserDetails user;

//getter setters
}
</code>```

Why we should use the above @OneToMany code if we can achieve the same db tables using the code below? Is the use of @OneToMany here just giving a solution of accessing the vehicle from user side
and if i have no requirement of accessing the vehicle for any user , this is correct configuration?

And since it gives same table configuration as bi-directional, what
should we say it uni-directional or bi-directional approach? I think as per code we cannot access vehicle from user side but user from vehicle side so is it a kind of uni-directional?

UserDetails (without Vehicle)

```<code>@Entity
public class UserDetails {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
private String userName;

//getter setters
}
</code>```

Table UserDetails

```<code>mysql> select * from userdetails;
+--------+------------+
| userId | userName   |
+--------+------------+
|        | First User |
+--------+------------+
1 row in set (0.00 sec)
</code>```

Table Vehicle

```<code>mysql> select * from vehicle;
+-----------+-------------+---------+
| vehicleId | vehicleName | user_id |
+-----------+-------------+---------+
|         2 | karizma     |         |
|         3 | scooty-pep  |         |
+-----------+-------------+---------+
2 rows in set (0.00 sec)
</code>```

答:
Very good observations and questions.

Yes, you should question the @OneToMany if it is really needed. Question is how many elements will be on that list and how the elements will be used say on the UI. My rule of thumb is 10 elements.

Lets say you have a bank account and @OneToMany transactions. In the UI on some start page you show just the 10 latest and even in you go into History you get or want always a filtered list. You practically never want to see all transactions. But the @OneToMany collections does not give you any control - you can not filter, sort or paginate it. Just load all (or nothing in case of FetchType.LAZY).

It is much more flexible and better to remove the collection and load the entities via JPQL query:

```<code>@Query("SELECT v FROM Vehicle v WHERE v.userDetails = :userDetails")
List<Vehicle> getVehicles(UserDetails userDetails);
</code>```

Such a query you can paginate, sort, and filter additionally. Also you can JOIN FETCH specific attributes when needed by business case.

So all in all the Query approach gives you much more control and performance then the collection. Drawback of the Query approach is that you have to write a bit more code and also navigating the domain model is harder.

Body:
Consider following entities

UserDetails (with Vehicles)

@Entity
public class UserDetails {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
private String userName;

@OneToMany(mappedBy="user",cascade=CascadeType.ALL,orphanRemoval=true)
private List<Vehicle> vehicleList = new ArrayList<>();

//getter setters
}

Vehicle

@Entity
public class Vehicle {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int vehicleId;
private String vehicleName;

@ManyToOne
@JoinColumn(name="user_id")
private UserDetails user;

//getter setters
}

Why we should use the above @OneToMany code if we can achieve the same db tables using the code below? Is the use of @OneToMany here just giving a solution of accessing the vehicle from user side
and if i have no requirement of accessing the vehicle for any user , this is correct configuration?

And since it gives same table configuration as bi-directional, what
should we say it uni-directional or bi-directional approach? I think as per code we cannot access vehicle from user side but user from vehicle side so is it a kind of uni-directional?

UserDetails (without Vehicle)

@Entity
public class UserDetails {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
private String userName;

//getter setters
}

Table UserDetails

mysql> select * from userdetails;
+--------+------------+
| userId | userName   |
+--------+------------+
|        | First User |
+--------+------------+
1 row in set (0.00 sec)

Table Vehicle

mysql> select * from vehicle;
+-----------+-------------+---------+
| vehicleId | vehicleName | user_id |
+-----------+-------------+---------+
|         2 | karizma     |         |
|         3 | scooty-pep  |         |
+-----------+-------------+---------+
2 rows in set (0.00 sec)

Body:
Very good observations and questions.

Yes, you should question the @OneToMany if it is really needed. Question is how many elements will be on that list and how the elements will be used say on the UI. My rule of thumb is 10 elements.

Lets say you have a bank account and @OneToMany transactions. In the UI on some start page you show just the 10 latest and even in you go into History you get or want always a filtered list. You practically never want to see all transactions. But the @OneToMany collections does not give you any control - you can not filter, sort or paginate it. Just load all (or nothing in case of FetchType.LAZY).

It is much more flexible and better to remove the collection and load the entities via JPQL query:

@Query("SELECT v FROM Vehicle v WHERE v.userDetails = :userDetails")
List<Vehicle> getVehicles(UserDetails userDetails);

Such a query you can paginate, sort, and filter additionally. Also you can JOIN FETCH specific attributes when needed by business case.

So all in all the Query approach gives you much more control and performance then the collection. Drawback of the Query approach is that you have to write a bit more code and also navigating the domain model is harder.


问:
How to achieve print with "Fit sheet on one page" using javascript
I have tried to print the table of data within one page. Which having 200 or 300 rows. It should be printed in in single page like Online MS Excel print option -> Fit Sheet on One Page. How can i achieve this it is possible?

I have tried the below code,

```<code>var tble = document.createElement("table");
tble.id = "tble";
document.body.appendChild(tble);
var trtd = "<tr><td>123</td></tr>"
for (var i = 0; i < 300; i++) {
  $("#tble").append(trtd);
}
var divs = "<div id='printing'></div>";
$("#printing").append($("#tble"));

$("#printData").click(function() {
  var printToDiv = $("#printing");
  var newWin = window.open("", "print-window");
  newWin.document.open();
  newWin.document.write('<html><body onload="window.print()">' + printToDiv.innerHTML + '</body></html>');
  newWin.document.close();
  setTimeout(function() {
    newWin.close();
  }, 10);
})
</code>```

Printed content should be on one single page. Is there any option?

答:
JavaSript code has no control whatsoever over the printing process other than initiating it. From that point forward, it's browser-specific and out of the control of your code.

The only way of doing this that I can see is to ask the user what page size they're using and with what margins (since the browser won't tell you), and then ensure that your table, when rendered, fits within the area inside the margins (e.g., by reducing/enlarging font size and such). You can, after all, get the rendered size in pixels via jQuery's outerWidth and outerHeight functions, and in general you can assume 96dpi (so pixels / 96 = inches).

Body:
I have tried to print the table of data within one page. Which having 200 or 300 rows. It should be printed in in single page like Online MS Excel print option -> Fit Sheet on One Page. How can i achieve this it is possible?

I have tried the below code,

var tble = document.createElement("table");
tble.id = "tble";
document.body.appendChild(tble);
var trtd = "
123
"
for (var i = 0; i < 300; i++) {
  $("#tble").append(trtd);
}
var divs = "

";
$("#printing").append($("#tble"));

$("#printData").click(function() {
  var printToDiv = $("#printing");
  var newWin = window.open("", "print-window");
  newWin.document.open();
  newWin.document.write('' + printToDiv.innerHTML + '');
  newWin.document.close();
  setTimeout(function() {
    newWin.close();
  }, 10);
})

Printed content should be on one single page. Is there any option?


问:
how convert locations: [CLLocation] to Coordinate2D?
how cat get coordinate location of didUpdateLocation delegate ?

```<code>func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
</code>```

Please Help me.Thanks

答:
Another way:

let lastLocation = locations.flatMap({ $0.coordinate }).last

Body:
how cat get coordinate location of didUpdateLocation delegate ?

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

Please Help me.Thanks


问:
Could not take photo with front camera 2
I checkout Camera2Basic (google sample)

and I just changed this method in the class Camera2BasicFragment in order to take a photo with front camera :

```<code>  private void setUpCameraOutputs(int width, int height) {
        Activity activity = getActivity();
        CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
        try {
//            for (String cameraId : manager.getCameraIdList()) {

            mCameraId = "1";
                CameraCharacteristics characteristics
                        = manager.getCameraCharacteristics(mCameraId);

                // We don't use a front facing camera in this sample.
                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
//                if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
//                    continue;
//                }

                StreamConfigurationMap map = characteristics.get(
                        CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
//                if (map == null) {
//                    continue;
//                }

                // For still image captures, we use the largest available size.
                Size largest = Collections.max(
                        Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
                        new CompareSizesByArea());
                mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(),
                        ImageFormat.JPEG, /*maxImages*/2);
                mImageReader.setOnImageAvailableListener(
                        mOnImageAvailableListener, mBackgroundHandler);

                // Find out if we need to swap dimension to get the preview size relative to sensor
                // coordinate.
                int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
                //noinspection ConstantConditions
                mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
                boolean swappedDimensions = false;
                switch (displayRotation) {
                    case Surface.ROTATION_0:
                    case Surface.ROTATION_180:
                        if (mSensorOrientation == 90 || mSensorOrientation == 270) {
                            swappedDimensions = true;
                        }
                        break;
                    case Surface.ROTATION_90:
                    case Surface.ROTATION_270:
                        if (mSensorOrientation == 0 || mSensorOrientation == 180) {
                            swappedDimensions = true;
                        }
                        break;
                    default:
                        Log.e(TAG, "Display rotation is invalid: " + displayRotation);
                }

                Point displaySize = new Point();
                activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
                int rotatedPreviewWidth = width;
                int rotatedPreviewHeight = height;
                int maxPreviewWidth = displaySize.x;
                int maxPreviewHeight = displaySize.y;

                if (swappedDimensions) {
                    rotatedPreviewWidth = height;
                    rotatedPreviewHeight = width;
                    maxPreviewWidth = displaySize.y;
                    maxPreviewHeight = displaySize.x;
                }

                if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
                    maxPreviewWidth = MAX_PREVIEW_WIDTH;
                }

                if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
                    maxPreviewHeight = MAX_PREVIEW_HEIGHT;
                }

                // Danger, W.R.! Attempting to use too large a preview size could  exceed the camera
                // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
                // garbage capture data.
                mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
                        rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
                        maxPreviewHeight, largest);

                // We fit the aspect ratio of TextureView to the size of preview we picked.
                int orientation = getResources().getConfiguration().orientation;
                if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    mTextureView.setAspectRatio(
                            mPreviewSize.getWidth(), mPreviewSize.getHeight());
                } else {
                    mTextureView.setAspectRatio(
                            mPreviewSize.getHeight(), mPreviewSize.getWidth());
                }

                // Check if the flash is supported.
                Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
                mFlashSupported = available == null ? false : available;

//            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            // Currently an NPE is thrown when the Camera2API is used but not supported on the
            // device this code runs.
            ErrorDialog.newInstance(getString(R.string.camera_error))
                    .show(getChildFragmentManager(), FRAGMENT_DIALOG);
        }
    }
</code>```

The front preview is displayed but I could not take photo.

And each time I trigger the button Picture, this log is displayed :

11-23 10:08:44.774 15690-16475/com.example.android.camera2basic
  W/LegacyRequestMapper: convertRequestToMetadata - Ignoring
  android.lens.focusDistance false, only 0.0f is supported 11-23
  10:08:44.829 15690-16475/com.example.android.camera2basic
  W/LegacyRequestMapper: convertRequestMetadata - control.awbRegions
  setting is not supported, ignoring value 11-23 10:08:44.832
  15690-16475/com.example.android.camera2basic W/LegacyRequestMapper:
  Only received metering rectangles with weight 0. 11-23 10:08:44.833
  15690-16475/com.example.android.camera2basic W/LegacyMetadataMapper:
  convertAfModeToLegacy - ignoring unsupported mode 4, defaulting to
  fixed

Does anyone has an idea how to fix this problem ?

答:
To resolve this problem, I declared an attribute mAutoFocusSupported and I initialize in this method :

```<code>private void setUpCameraOutputs(int width, int height) {
       //...
 int[] afAvailableModes = characteristics.get(CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES);
            if (afAvailableModes.length == 0 || (afAvailableModes.length == 1
                    && afAvailableModes[0] == CameraMetadata.CONTROL_AF_MODE_OFF)) {
                mAutoFocusSupported = false;
            } else {
                mAutoFocusSupported = true;
            }

//...
}
</code>```

and I change the method takePicture like this  :

```<code>  public void takePicture() {
        if (mAutoFocusSupported) {
            lockFocus();
        } else {
            captureStillPicture();
        }
    }
</code>```

And I changed the callback mCaptureCallback like this :

```<code>   private CameraCaptureSession.CaptureCallback mCaptureCallback
            = new CameraCaptureSession.CaptureCallback() {

        private void process(CaptureResult result) {

            switch (mState) {

                case STATE_PREVIEW: {
                    // We have nothing to do when the camera preview is working normally.
                    break;
                }
                case STATE_WAITING_LOCK: {
                    Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
                    Log.i(TAG, "STATE_WAITING_LOCK " + mState + " " + afState);

                    if (afState == null) {
                        captureStillPicture();
                    } else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState ||
                            CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState ||
                            CaptureResult.CONTROL_AF_STATE_INACTIVE == afState) {
                        // CONTROL_AE_STATE can be null on some devices
                        Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                        if (aeState == null ||
                                aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
                            mState = STATE_PICTURE_TAKEN;
                            captureStillPicture();
                        } else {
                            runPreCaptureSequence();
                        }
                    }
                    break;
                }
                case STATE_WAITING_PRECAPTURE: {
                    // CONTROL_AE_STATE can be null on some devices
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null ||
                            aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE ||
                            aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
                        mState = STATE_WAITING_NON_PRECAPTURE;
                    }
                    break;
                }
                case STATE_WAITING_NON_PRECAPTURE: {
                    // CONTROL_AE_STATE can be null on some devices
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
                        mState = STATE_PICTURE_TAKEN;
                        captureStillPicture();
                    }
                    break;
                }
            }
        }

        @Override
        public void onCaptureProgressed(@NonNull CameraCaptureSession session,
                                        @NonNull CaptureRequest request,
                                        @NonNull CaptureResult partialResult) {
//            Log.i(TAG, "onCaptureProgressed " + mState + " "+partialResult);

            process(partialResult);
        }

        @Override
        public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                       @NonNull CaptureRequest request,
                                       @NonNull TotalCaptureResult result) {
            process(result);
        }

    };
</code>```

Body:
I checkout Camera2Basic (google sample)

and I just changed this method in the class Camera2BasicFragment in order to take a photo with front camera :

  private void setUpCameraOutputs(int width, int height) {
        Activity activity = getActivity();
        CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
        try {
//            for (String cameraId : manager.getCameraIdList()) {

            mCameraId = "1";
                CameraCharacteristics characteristics
                        = manager.getCameraCharacteristics(mCameraId);

                // We don't use a front facing camera in this sample.
                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
//                if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
//                    continue;
//                }

                StreamConfigurationMap map = characteristics.get(
                        CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
//                if (map == null) {
//                    continue;
//                }

                // For still image captures, we use the largest available size.
                Size largest = Collections.max(
                        Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
                        new CompareSizesByArea());
                mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(),
                        ImageFormat.JPEG, /*maxImages*/2);
                mImageReader.setOnImageAvailableListener(
                        mOnImageAvailableListener, mBackgroundHandler);

                // Find out if we need to swap dimension to get the preview size relative to sensor
                // coordinate.
                int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
                //noinspection ConstantConditions
                mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
                boolean swappedDimensions = false;
                switch (displayRotation) {
                    case Surface.ROTATION_0:
                    case Surface.ROTATION_180:
                        if (mSensorOrientation == 90 || mSensorOrientation == 270) {
                            swappedDimensions = true;
                        }
                        break;
                    case Surface.ROTATION_90:
                    case Surface.ROTATION_270:
                        if (mSensorOrientation == 0 || mSensorOrientation == 180) {
                            swappedDimensions = true;
                        }
                        break;
                    default:
                        Log.e(TAG, "Display rotation is invalid: " + displayRotation);
                }

                Point displaySize = new Point();
                activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
                int rotatedPreviewWidth = width;
                int rotatedPreviewHeight = height;
                int maxPreviewWidth = displaySize.x;
                int maxPreviewHeight = displaySize.y;

                if (swappedDimensions) {
                    rotatedPreviewWidth = height;
                    rotatedPreviewHeight = width;
                    maxPreviewWidth = displaySize.y;
                    maxPreviewHeight = displaySize.x;
                }

                if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
                    maxPreviewWidth = MAX_PREVIEW_WIDTH;
                }

                if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
                    maxPreviewHeight = MAX_PREVIEW_HEIGHT;
                }

                // Danger, W.R.! Attempting to use too large a preview size could  exceed the camera
                // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
                // garbage capture data.
                mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
                        rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
                        maxPreviewHeight, largest);

                // We fit the aspect ratio of TextureView to the size of preview we picked.
                int orientation = getResources().getConfiguration().orientation;
                if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    mTextureView.setAspectRatio(
                            mPreviewSize.getWidth(), mPreviewSize.getHeight());
                } else {
                    mTextureView.setAspectRatio(
                            mPreviewSize.getHeight(), mPreviewSize.getWidth());
                }

                // Check if the flash is supported.
                Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
                mFlashSupported = available == null ? false : available;

//            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            // Currently an NPE is thrown when the Camera2API is used but not supported on the
            // device this code runs.
            ErrorDialog.newInstance(getString(R.string.camera_error))
                    .show(getChildFragmentManager(), FRAGMENT_DIALOG);
        }
    }

The front preview is displayed but I could not take photo.

And each time I trigger the button Picture, this log is displayed :

11-23 10:08:44.774 15690-16475/com.example.android.camera2basic
  W/LegacyRequestMapper: convertRequestToMetadata - Ignoring
  android.lens.focusDistance false, only 0.0f is supported 11-23
  10:08:44.829 15690-16475/com.example.android.camera2basic
  W/LegacyRequestMapper: convertRequestMetadata - control.awbRegions
  setting is not supported, ignoring value 11-23 10:08:44.832
  15690-16475/com.example.android.camera2basic W/LegacyRequestMapper:
  Only received metering rectangles with weight 0. 11-23 10:08:44.833
  15690-16475/com.example.android.camera2basic W/LegacyMetadataMapper:
  convertAfModeToLegacy - ignoring unsupported mode 4, defaulting to
  fixed

Does anyone has an idea how to fix this problem ?

Body:
To resolve this problem, I declared an attribute mAutoFocusSupported and I initialize in this method :

private void setUpCameraOutputs(int width, int height) {
       //...
 int[] afAvailableModes = characteristics.get(CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES);
            if (afAvailableModes.length == 0 || (afAvailableModes.length == 1
                    && afAvailableModes[0] == CameraMetadata.CONTROL_AF_MODE_OFF)) {
                mAutoFocusSupported = false;
            } else {
                mAutoFocusSupported = true;
            }

//...
}

and I change the method takePicture like this  :

  public void takePicture() {
        if (mAutoFocusSupported) {
            lockFocus();
        } else {
            captureStillPicture();
        }
    }

And I changed the callback mCaptureCallback like this :

   private CameraCaptureSession.CaptureCallback mCaptureCallback
            = new CameraCaptureSession.CaptureCallback() {

        private void process(CaptureResult result) {

            switch (mState) {

                case STATE_PREVIEW: {
                    // We have nothing to do when the camera preview is working normally.
                    break;
                }
                case STATE_WAITING_LOCK: {
                    Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
                    Log.i(TAG, "STATE_WAITING_LOCK " + mState + " " + afState);

                    if (afState == null) {
                        captureStillPicture();
                    } else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState ||
                            CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState ||
                            CaptureResult.CONTROL_AF_STATE_INACTIVE == afState) {
                        // CONTROL_AE_STATE can be null on some devices
                        Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                        if (aeState == null ||
                                aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
                            mState = STATE_PICTURE_TAKEN;
                            captureStillPicture();
                        } else {
                            runPreCaptureSequence();
                        }
                    }
                    break;
                }
                case STATE_WAITING_PRECAPTURE: {
                    // CONTROL_AE_STATE can be null on some devices
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null ||
                            aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE ||
                            aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
                        mState = STATE_WAITING_NON_PRECAPTURE;
                    }
                    break;
                }
                case STATE_WAITING_NON_PRECAPTURE: {
                    // CONTROL_AE_STATE can be null on some devices
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
                        mState = STATE_PICTURE_TAKEN;
                        captureStillPicture();
                    }
                    break;
                }
            }
        }

        @Override
        public void onCaptureProgressed(@NonNull CameraCaptureSession session,
                                        @NonNull CaptureRequest request,
                                        @NonNull CaptureResult partialResult) {
//            Log.i(TAG, "onCaptureProgressed " + mState + " "+partialResult);

            process(partialResult);
        }

        @Override
        public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                       @NonNull CaptureRequest request,
                                       @NonNull TotalCaptureResult result) {
            process(result);
        }

    };


问:
Is it possible to use reduce in a callback function?
I have this simple component

```<code>let component = ReasonReact.statelessComponent("Input");

let make = (~name, ~onChange, ~value, _children) => {
    ...component,
    render: (_self) =>
        <input
            name=name
            onChange={(_) => {
              onChange(name, "change")
            }}
            value=value />
};
</code>```

and I'm trying to use it like this

```<code><Input
    name="
    placeholder="Your email"
    onChange={self.reduce((name, value) => Change(name, value))}
    label=""
    value={self.state.email} />
</code>```

But I get this error on the onChange line

```<code>This is:
    ReasonReact.Callback.t(string) (defined as (string) => unit)
  But somewhere wanted:
    (string, string) => unit

  The incompatible parts:
    unit
    vs
    (string) => unit
</code>```

I think I understand the error, but I have no idea to to fix it. I also to define onChange like this

```<code>onChange={(name, value) => self.reduce((_, _) => Change(name, value))}
</code>```

but this time I get

```<code>This is:
    ReasonReact.Callback.t('a) (defined as ('a) => unit)
  But somewhere wanted:
    unit
</code>```

Do you have an idea how to fix it ? Is it possible to call reduce inside another callback function ?

答:
reduce takes a 1-ary function and returns a 1-ary function, but your onChange is expected to be a 2-ary function. Since you seem to control both sides of this, the simplest fix is to just use a tuple:

Definition:

```<code>onChange={self.reduce(((name, value)) => Change(name, value))}
</code>```

Application:

```<code>onChange={(_) => {
  onChange((name, "change"))
}}
</code>```

Alternatively, if you don't control how the callback is used, you can wrap it in another function like you tried to, but since reduce returns a function you have to explicitly call it:

```<code>onChange={(name, value) => self.reduce(() => Change(name, value))()}
</code>```

Note: The argument you pass to the callback returned by reduce is the same argument that will be passed to the callback passed to reduce, in this case just (). But value => self.reduce(val => Action(val))(value) is therefore equivalent to just doing self.reduce(val => Action(val)).

Body:
I have this simple component

let component = ReasonReact.statelessComponent("Input");

let make = (~name, ~onChange, ~value, _children) => {
    ...component,
    render: (_self) =>
        <input
            name=name
            onChange={(_) => {
              onChange(name, "change")
            }}
            value=value />
};

and I'm trying to use it like this

<Input
    name="
    placeholder="Your email"
    onChange={self.reduce((name, value) => Change(name, value))}
    label=""
    value={self.state.email} />

But I get this error on the onChange line

This is:
    ReasonReact.Callback.t(string) (defined as (string) => unit)
  But somewhere wanted:
    (string, string) => unit

  The incompatible parts:
    unit
    vs
    (string) => unit

I think I understand the error, but I have no idea to to fix it. I also to define onChange like this

onChange={(name, value) => self.reduce((_, _) => Change(name, value))}

but this time I get

This is:
    ReasonReact.Callback.t('a) (defined as ('a) => unit)
  But somewhere wanted:
    unit

Do you have an idea how to fix it ? Is it possible to call reduce inside another callback function ?

Body:
reduce takes a 1-ary function and returns a 1-ary function, but your onChange is expected to be a 2-ary function. Since you seem to control both sides of this, the simplest fix is to just use a tuple:

Definition:

onChange={self.reduce(((name, value)) => Change(name, value))}

Application:

onChange={(_) => {
  onChange((name, "change"))
}}

Alternatively, if you don't control how the callback is used, you can wrap it in another function like you tried to, but since reduce returns a function you have to explicitly call it:

onChange={(name, value) => self.reduce(() => Change(name, value))()}

Note: The argument you pass to the callback returned by reduce is the same argument that will be passed to the callback passed to reduce, in this case just (). But value => self.reduce(val => Action(val))(value) is therefore equivalent to just doing self.reduce(val => Action(val)).


问:
CSS not working in stylesheet
I have a set of Styles that were first created inside the style attribute on a page.

I want to move it from being on the page itself into a stylesheet.

however, when I move it to a .css file, the page breaks, move the code back to the html doc and it works fine again.

This makes absolutely no sense, moving styles from a style to a css file shouldnt break the code should it?

Am I missing something? I am not changing any of the code, its simply a copy and paste.

答:
You should make sure the stylesheet is properly imported.
Sometimes the @import doesn't work well if not used accordingly, so always reference your stylesheet:

<link rel="stylesheet" type="text/css" href="name-of-stylesheet.css" />

Always remember to close the <link> tag as it's a self-close tag. I think @zzzzBov forgot to mention that.

Finally, if that doesn't work, try to override some of the styles by physically writing (above the  section) something like:

```<code><style type="text/css">
    body { background: blue; }
    * { color: red; }
</style>
</code>```

and see if that gives you a blue background and red colored text. It should. After that, try to implement the referencing method and make sure you reference the stylesheet file to the right directory.

Good luck!

Title: CSS not working in stylesheet

Body:
You should make sure the stylesheet is properly imported.
Sometimes the @import doesn't work well if not used accordingly, so always reference your stylesheet:

<link rel="stylesheet" type="text/css" href="name-of-stylesheet.css" />

Always remember to close the <link> tag as it's a self-close tag. I think @zzzzBov forgot to mention that.

Finally, if that doesn't work, try to override some of the styles by physically writing (above the </head> section) something like:

<style type="text/css">
    body { background: blue; }
    * { color: red; }
</style>

and see if that gives you a blue background and red colored text. It should. After that, try to implement the referencing method and make sure you reference the stylesheet file to the right directory.

Good luck!


问:
ng-change is not working properly with ng-if

1. java script which is called

```<code>this.changeRole=function(user){
    alert(user)
    if(user=='Admin' || user=='Subject Manager'){
     $scope.role=false;
    }
    else{
        $scope.role=true;
    }
  }
</code>```

2. html from that function is called

```<code> <div class="form-group">
    <label class="col-sm-2 control-label">Role
        <span class="text-danger">*</span>
    </label>
    <div class="col-sm-9">
        <select class="form-control" ng-model="uc.newuser.role"
                ng-change="uc.changeRole(uc.newuser.role)" required >
            <option  ng-repeat="role in uc.roles" ng-value="user.name" >
              {{role}}
            </option>
        </select>
    </div>
 </div>
</code>```

```<code><table class="table">
    <thead>
        <tr>
          <th>User Name</th>
          <th>E-mail ID</th>
          <th>Mobile</th>
          <th>User type</th>
          <th ng-if="role=='Admin'">Action</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="user in users">
          <td>{{user.name}}</td>
          <td>{{user.email}}</td>
          <td>{{user.phone}}</td>
          <td>{{user.role.toString()}}</td>
          <td ng-if="role=='Admin'">
            <button class="btn btn-circle btn-gout1"
                    ng-click="uc.editUser(user.id)"
                    data-toggle="modal"
                    data-target=".bs-register-modal-md">
              <i class="fa fa-pencil"></i>
            </button>
            <button class="btn btn-circle btn-gout"
                    ng-click="uc.deleteUser(user.id)">
              <i class="fa fa-trash"></i>
            </button>
          </td>
        </tr>

    </tbody>
</table>
</code>```

After ng-change the column with ng-if is hiding.

答:
ng-if should be checked like</p>

```<code><td ng-if="role">
</code>```

Body:
1. java script which is called

this.changeRole=function(user){
    alert(user)
    if(user=='Admin' || user=='Subject Manager'){
     $scope.role=false;
    }
    else{
        $scope.role=true;
    }
  }

2. html from that function is called

    Role
        *

        <select class="form-control" ng-model="uc.newuser.role"
                ng-change="uc.changeRole(uc.newuser.role)" required >
            <option  ng-repeat="role in uc.roles" ng-value="user.name" >
              {{role}}
            </option>
        </select>

          User Name
          E-mail ID
          Mobile
          User type
          Action

          {{user.name}}
          {{user.email}}
          {{user.phone}}
          {{user.role.toString()}}

            <button class="btn btn-circle btn-gout1"
                    ng-click="uc.editUser(user.id)"
                    data-toggle="modal"
                    data-target=".bs-register-modal-md">

            </button>
            <button class="btn btn-circle btn-gout"
                    ng-click="uc.deleteUser(user.id)">

            </button>

After ng-change the column with ng-if is hiding.

Body:
ng-if should be checked like

<td ng-if="role">