问:
Add new objects after using "new"
after I call new, how can I add more objects to the pointer? (I need it for a class)
this is what I mean:

```<code>int *a;
a = new int;
a = new int;
</code>```

Thank you very much!

答:
In C, you would use realloc. In C++, you would use STL's std::vector instead of a pointer. You could always do something ugly like:

```<code>int *a;
a = new int[1];
delete [] a;
a = new int[2];
</code>```

But you'd hit a performance drop.

Title: Add new objects after using "new"

Body:
after I call new, how can I add more objects to the pointer? (I need it for a class)
this is what I mean:

int *a;
a = new int;
a = new int;

Thank you very much!

Body:
In C, you would use realloc. In C++, you would use STL's std::vector instead of a pointer. You could always do something ugly like:

int *a;
a = new int[1];
delete [] a;
a = new int[2];

But you'd hit a performance drop.


来源: stackexchange

问:
AWS CloudWatch Logs are not Created
I am trying to use AWS Glue to run an ETL job that fetches data from Redshift to S3.

When I run a crawler it successfully connects to Redshift and fetches schema information. Relevant logs are created under a log group aws-glue/crawlers.

When I run the ETL job, it is supposed to create a log stream under log groups aws-glue/jobs/output and aws-glue/jobs/error, but it fails to create such log streams, and eventually the job too fails.

( I am using AWS managed AWSGlueServiceRole policy for Glue service)

Since it does not produce any logs, it is difficult to identify the reason for ETL job failure. I would appreciate it if you could help me resolve this issue.

答:
I would make sure that your Endpoint and VPC is set up correctly via these instructions:

http://docs.aws.amazon.com/glue/latest/dg/setup-vpc-for-glue-access.html

I had my inbound rules set up correctly but did not set up the outbound rules which is what I think the issue was.

ContentLicense: CC BY-SA 3.0

Title: AWS CloudWatch Logs are not Created


问:
How to remove diacritics from text?
I am making a swedish website, and swedish letters are å, ä, and ö.

I need to make a string entered by a user to become url-safe with PHP.

Basically, need to convert all characters to underscore, all EXCEPT these:

```<code> A-Z, a-z, 1-9
</code>```

and all swedish should be converted like this:

'å' to 'a' and 'ä' to 'a' and 'ö' to 'o' (just remove the dots above).

The rest should become underscores as I said.

Im not good at regular expressions so I would appreciate the help guys!

Thanks

NOTE: NOT URLENCODE...I need to store it in a database... etc etc, urlencode wont work for me.

答:
If intl php extension is enabled, you can use Transliterator like this :

```<code>protected function removeDiacritics($string)
{
    $transliterator = \Transliterator::create('NFD; [:Nonspacing Mark:] Remove; NFC;');
    return $transliterator->transliterate($string);
}
</code>```

To remove other special chars (not diacritics only like 'æ')

```<code>protected function removeDiacritics($string)
{
    $transliterator = \Transliterator::createFromRules(
        ':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;',
        \Transliterator::FORWARD
    );
    return $transliterator->transliterate($string);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to remove diacritics from text?

Body:
I am making a swedish website, and swedish letters are å, ä, and ö.

I need to make a string entered by a user to become url-safe with PHP.

Basically, need to convert all characters to underscore, all EXCEPT these:

 A-Z, a-z, 1-9

and all swedish should be converted like this:

'å' to 'a' and 'ä' to 'a' and 'ö' to 'o' (just remove the dots above).

The rest should become underscores as I said.

Im not good at regular expressions so I would appreciate the help guys!

Thanks

NOTE: NOT URLENCODE...I need to store it in a database... etc etc, urlencode wont work for me.

Body:
If intl php extension is enabled, you can use Transliterator like this :

protected function removeDiacritics($string)
{
    $transliterator = \Transliterator::create('NFD; [:Nonspacing Mark:] Remove; NFC;');
    return $transliterator->transliterate($string);
}

To remove other special chars (not diacritics only like 'æ')

protected function removeDiacritics($string)
{
    $transliterator = \Transliterator::createFromRules(
        ':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;',
        \Transliterator::FORWARD
    );
    return $transliterator->transliterate($string);
}


问:
super.super.func()? - Java polymorphism
Say that I in Java have 3 classes, wheres the super one has a function named func(), I now make a subclass which overrides this, and a subclass to my subclass, now working on my sub-sub-class how will I call the 'func()' of the sub class, and the superclass?

I tried casting the 'this' "pointer", but Java 'fixes' it at runtime and calls the subsub func().

Edit:
Thanks everyone; 'Skeen is back at the drawing board'.

答:
You can access the superclass methods from within the subclass itself, e.g.

```<code>class A {
   void foo() {...}
}

class B extends A {
   void foo() {...}
   void defaultFoo() { super.foo(); }
}
</code>```

However, you really shouldn't be exposing overridden methods this way, you should write B.foo() in such a way that works fine for A and B. This is where it is a good idea to use super.foo(); like this:

```<code> class B extends A {
    void foo() {
      super.foo(); //call superclass implementation first
      ... //do stuff specific to B
    }
 }
</code>```

Update: In response to your comment on trying to access the implementation 2 levels up, here's a way of doing it.

```<code>class A {
   void foo() {
     defaultFoo();
   }
   protected void defaultFoo() { ... }

}

class B extends A {
   void foo() {...}
}

class C extends B {
   void foo() {
     defaultFoo();
     ... //do other stuff
   }
}
</code>```

This is a healthier pattern of coding what you want to do.

Title: super.super.func()? - Java polymorphism

Body:
You can access the superclass methods from within the subclass itself, e.g.

class A {
   void foo() {...}
}

class B extends A {
   void foo() {...}
   void defaultFoo() { super.foo(); }
}

However, you really shouldn't be exposing overridden methods this way, you should write B.foo() in such a way that works fine for A and B. This is where it is a good idea to use super.foo(); like this:

 class B extends A {
    void foo() {
      super.foo(); //call superclass implementation first
      ... //do stuff specific to B
    }
 }

Update: In response to your comment on trying to access the implementation 2 levels up, here's a way of doing it.

class A {
   void foo() {
     defaultFoo();
   }
   protected void defaultFoo() { ... }

}

class B extends A {
   void foo() {...}
}

class C extends B {
   void foo() {
     defaultFoo();
     ... //do other stuff
   }
}

This is a healthier pattern of coding what you want to do.


问:
Why is setting onClickListener working once?
I want to migrate a very solid project structure that I use to Kotlin. I first tried the basics: Activities and Fragment transactions. It appears so easy and simple:

```<code>class MainActivity : AppCompatActivity(), SomeInterface {
     override fun onCreate(savedInstanceState: Bundle?) {
         setContentView(R.layout.activity_main)

         val mainFragment = supportFragmentManager.findFragmentById(R.id.fragment_main) as MainActionsFragment?
                    ?: MainActionsFragment.newInstance()
         supportFragmentManager.inTransaction {
              add(R.id.container_main, mainFragment)
         }
    }

    private val anotherFragment by lazy {
    supportFragmentManager.findFragmentById(R.id.another_fragment) as AnotherFragment?
            ?: AnotherFragment.newInstance()
    }

    override fun myInterfaceMethod() {
        replaceFragment(anotherFragment, R.id.container_main)
    }
}

class MainActionsFragment : Fragment() {
    val btnSale: Button by bindView(R.id.btn_sale)
    val btnVisit: Button by bindView(R.id.btn_visit)

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater!!.inflate(R.layout.fragment_main, container, false)
    }

    override fun onResume() {
        super.onResume()

        btnSale.setOnClickListener{ _ ->
            listener.requestAction(SaleType.SALE)
        }

        btnVisit.setOnClickListener{ _ ->
            listener.requestAction(SaleType.VISIT)
        }
    }
}
</code>```

Extensions.kt

```<code>fun AppCompatActivity.replaceFragment(fragment: Fragment, @IdRes frameId: Int) {
    supportFragmentManager.inTransaction {
        replace(frameId, fragment)
                .addToBackStack(fragment.tag)
    }
}

inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> FragmentTransaction) {
    beginTransaction()
            .func()
            .commit()
}
</code>```

Now, MainActionsFragment holds two buttons. Everything works as expected, the first click on either one takes me to the desired fragment. However, once I press the back button and I see my two buttons again, their click listener is gone. This is pretty much the standard way of doings things translated to Kotlin, nothing fancy besides its cool new features. I tried moving setting the onClickListeners to onCreateView() but it crashes:

Caused by: kotlin.KotlinNullPointerException
                                                                                at kotterknife.ButterKnifeKt$viewFinder$7.invoke(ButterKnife.kt:95)
                                                                                at kotterknife.ButterKnifeKt$viewFinder$7.invoke(ButterKnife.kt)
                                                                                at kotterknife.ButterKnifeKt$required$1.invoke(ButterKnife.kt:104)
                                                                                at kotterknife.ButterKnifeKt$required$1.invoke(ButterKnife.kt)
                                                                                at kotterknife.Lazy.getValue(ButterKnife.kt:125)

So, in spite of Kotlin being so cool, I'm having trouble doing the basics and I'm getting disheartened to migrate. Am I really doing things so wrong? Or how come setting a simple click listener is so frustrating?

Thank you.

答:
You have to set your variables that are bound by ButterKnife as lateinit var instead of val. Try

```<code>@BindView(R.id.btn_sale)
lateinit var title: Button

@BindView(R.id.btn_visit)
lateinit var title: Button
</code>```

Body:
I want to migrate a very solid project structure that I use to Kotlin. I first tried the basics: Activities and Fragment transactions. It appears so easy and simple:

class MainActivity : AppCompatActivity(), SomeInterface {
     override fun onCreate(savedInstanceState: Bundle?) {
         setContentView(R.layout.activity_main)

         val mainFragment = supportFragmentManager.findFragmentById(R.id.fragment_main) as MainActionsFragment?
                    ?: MainActionsFragment.newInstance()
         supportFragmentManager.inTransaction {
              add(R.id.container_main, mainFragment)
         }
    }

    private val anotherFragment by lazy {
    supportFragmentManager.findFragmentById(R.id.another_fragment) as AnotherFragment?
            ?: AnotherFragment.newInstance()
    }

    override fun myInterfaceMethod() {
        replaceFragment(anotherFragment, R.id.container_main)
    }
}

class MainActionsFragment : Fragment() {
    val btnSale: Button by bindView(R.id.btn_sale)
    val btnVisit: Button by bindView(R.id.btn_visit)

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater!!.inflate(R.layout.fragment_main, container, false)
    }

    override fun onResume() {
        super.onResume()

        btnSale.setOnClickListener{ _ ->
            listener.requestAction(SaleType.SALE)
        }

        btnVisit.setOnClickListener{ _ ->
            listener.requestAction(SaleType.VISIT)
        }
    }
}

Extensions.kt

fun AppCompatActivity.replaceFragment(fragment: Fragment, @IdRes frameId: Int) {
    supportFragmentManager.inTransaction {
        replace(frameId, fragment)
                .addToBackStack(fragment.tag)
    }
}

inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> FragmentTransaction) {
    beginTransaction()
            .func()
            .commit()
}

Now, MainActionsFragment holds two buttons. Everything works as expected, the first click on either one takes me to the desired fragment. However, once I press the back button and I see my two buttons again, their click listener is gone. This is pretty much the standard way of doings things translated to Kotlin, nothing fancy besides its cool new features. I tried moving setting the onClickListeners to onCreateView() but it crashes:

Caused by: kotlin.KotlinNullPointerException
                                                                                at kotterknife.ButterKnifeKt$viewFinder$7.invoke(ButterKnife.kt:95)
                                                                                at kotterknife.ButterKnifeKt$viewFinder$7.invoke(ButterKnife.kt)
                                                                                at kotterknife.ButterKnifeKt$required$1.invoke(ButterKnife.kt:104)
                                                                                at kotterknife.ButterKnifeKt$required$1.invoke(ButterKnife.kt)
                                                                                at kotterknife.Lazy.getValue(ButterKnife.kt:125)

So, in spite of Kotlin being so cool, I'm having trouble doing the basics and I'm getting disheartened to migrate. Am I really doing things so wrong? Or how come setting a simple click listener is so frustrating?

Thank you.

Body:
You have to set your variables that are bound by ButterKnife as lateinit var instead of val. Try

@BindView(R.id.btn_sale)
lateinit var title: Button

@BindView(R.id.btn_visit)
lateinit var title: Button


问:
In which version of JDK7, MergeSort was replaced with TimSort in Collections.sort method?
I searched and couldn't find in which version the TimSort actually replaced the MergeSort in collections.sort() method. If anyone can let me know the exact version for JDK7 it would be a great help.</p>

答:
TimSort has been used in Java 7 right from the release. To be more specific, it has been added in Java 7, beta 70.

It might be worth noting that this is still a modified merge sort, just having more modifications being more efficient than the modified merge sort that has been used in previous version.


问:
PHP SQL Output orderby change refreshes whole page
I have some PHP code that initially sends a query to order by name ascending. I have arrow glyphicons to select different values to sort by. The data is about meteorites, in the database there's columns for name, id, class, lat, lon,year, and mass. I have arrow buttons for the user to sort for name, mass, and year both ASC and DESC.

I have it so that when the user selects an arrow to sort by it loads the page with JQuery and in this example it's sort mass ascendingly. I have an array of valid inputs so there's no risk for SQL injection.

```<code>$("#massASC").click(function () {
     location.href = '?orderby=massASC';
});
</code>```

My problem is that I have a Google maps div that refreshes I'm loading a new page.

Is there a way that I can only refresh the table data and not load a new page?

答:
yes, You need use AJAX:

```<code><div id="data_sorted">
....
....
</div>

$("#massASC").click(function () {
     $.post('/getData.php', {orderBy: 'massASC'}, function(response) {
         $('#data_sorted').html(response.html);
     });
});
</code>```

getData.php:

```<code>$orderBy = $_POST['orderBy'];
$sql = 'SELECT * from {the_table} order by ' . $orderBy;
$data = // Fetch the data the way you want using $sql query
$html = '';
foreach ($data as $row) {
    $html .= 'SOME HTML for current row';
}

return json_encode(array('html' => $html));
</code>```

Body:
I have some PHP code that initially sends a query to order by name ascending. I have arrow glyphicons to select different values to sort by. The data is about meteorites, in the database there's columns for name, id, class, lat, lon,year, and mass. I have arrow buttons for the user to sort for name, mass, and year both ASC and DESC.

I have it so that when the user selects an arrow to sort by it loads the page with JQuery and in this example it's sort mass ascendingly. I have an array of valid inputs so there's no risk for SQL injection.

$("#massASC").click(function () {
     location.href = '?orderby=massASC';
});

My problem is that I have a Google maps div that refreshes I'm loading a new page.

Is there a way that I can only refresh the table data and not load a new page?

Body:
yes, You need use AJAX:

<div id="data_sorted">
....
....
</div>

$("#massASC").click(function () {
     $.post('/getData.php', {orderBy: 'massASC'}, function(response) {
         $('#data_sorted').html(response.html);
     });
});

getData.php:

$orderBy = $_POST['orderBy'];
$sql = 'SELECT * from {the_table} order by ' . $orderBy;
$data = // Fetch the data the way you want using $sql query
$html = '';
foreach ($data as $row) {
    $html .= 'SOME HTML for current row';
}

return json_encode(array('html' => $html));


问:
Calling a value from has_one association
I am trying to grab some info from a has_one association but I can't get the correct way to call it. I have 2 tables a students table which has_one emergency_contact. The emergency_contact table has a foreign key value student_id. I am trying to link_to the record that the foreign key is attached to in the emergency_contact table and I just can't seem to get it correct.

student.rb

```<code>class Student < ApplicationRecord
self.primary_key = :student_id
has_one :emergency_contact
</code>```

emergency_contact.rb

```<code>class EmergencyContact < ApplicationRecord
self.primary_key = :contact_id
belongs_to  :student, optional: true
</code>```

students/show.html.erb

```<code><%= emergency_contact_path(@student.student_id) %>
</code>```

Right now I am just getting directed to the value of student_id, which for example student_id = 5. When really the contact_id of the emergency_contact.contact_id = 1. How can I get that 1?

答:
Set foreign_key for has_one:

```<code>has_one :emergency_contact, foreign_key: 'contact_id'
</code>```

Link is:

```<code><%= emergency_contact_path(@student.emergency_contact.contact_id) %>
</code>```

Body:
I am trying to grab some info from a has_one association but I can't get the correct way to call it. I have 2 tables a students table which has_one emergency_contact. The emergency_contact table has a foreign key value student_id. I am trying to link_to the record that the foreign key is attached to in the emergency_contact table and I just can't seem to get it correct.

student.rb

class Student < ApplicationRecord
self.primary_key = :student_id
has_one :emergency_contact

emergency_contact.rb

class EmergencyContact < ApplicationRecord
self.primary_key = :contact_id
belongs_to  :student, optional: true

students/show.html.erb

<%= emergency_contact_path(@student.student_id) %>

Right now I am just getting directed to the value of student_id, which for example student_id = 5. When really the contact_id of the emergency_contact.contact_id = 1. How can I get that 1?

Body:
Set foreign_key for has_one:

has_one :emergency_contact, foreign_key: 'contact_id'

Link is:

<%= emergency_contact_path(@student.emergency_contact.contact_id) %>


问:
MySQL57 service on Local Computer started and then stopped
I'm having a problem with mySql. It is stopped and when I try to start it, I get the following: "MySQL57 service on Local Computer started and then stopped." as you can see in the following image:

My server log is the following:

2017-04-05T10:04:58.085384Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-04-05T10:04:58.085384Z 0 [Warning] 'NO_ZERO_DATE', 'NO_ZERO_IN_DATE' and 'ERROR_FOR_DIVISION_BY_ZERO' sql modes should be used with strict mode. They will be merged with strict mode in a future release.
2017-04-05T10:04:58.087363Z 0 [Note] C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe (mysqld 5.7.9-log) starting as process 7852 ...
2017-04-05T10:04:58.108397Z 0 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2017-04-05T10:04:58.109398Z 0 [Note] InnoDB: Uses event mutexes
2017-04-05T10:04:58.109398Z 0 [Note] InnoDB: _mm_lfence() and _mm_sfence() are used for memory barrier
2017-04-05T10:04:58.110399Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-04-05T10:04:58.110399Z 0 [Note] InnoDB: Adjusting innodb_buffer_pool_instances from 8 to 1 since innodb_buffer_pool_size is less than 1024 MiB
2017-04-05T10:04:58.116403Z 0 [Note] InnoDB: Number of pools: 1
2017-04-05T10:04:58.116403Z 0 [Note] InnoDB: Not using CPU crc32 instructions
2017-04-05T10:04:58.156434Z 0 [Note] InnoDB: Initializing buffer pool, total size = 8M, instances = 1, chunk size = 8M
2017-04-05T10:04:58.158435Z 0 [Note] InnoDB: Completed initialization of buffer pool
2017-04-05T10:04:58.200443Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2017-04-05T10:04:58.207479Z 0 [Note] InnoDB: Log scan progressed past the checkpoint lsn 43061044961
2017-04-05T10:04:58.208477Z 0 [Note] InnoDB: Doing recovery: scanned up to log sequence number 43061045173
2017-04-05T10:04:58.209476Z 0 [ERROR] InnoDB: Ignoring the redo log due to missing MLOG_CHECKPOINT between the checkpoint 43061044961 and the end 43061045173.
2017-04-05T10:04:58.210477Z 0 [ERROR] InnoDB: Plugin initialization aborted with error Generic error
2017-04-05T10:04:58.514809Z 0 [ERROR] Plugin 'InnoDB' init function returned error.
2017-04-05T10:04:58.515786Z 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2017-04-05T10:04:58.515786Z 0 [ERROR] Failed to initialize plugins.
2017-04-05T10:04:58.516785Z 0 [ERROR] Aborting

2017-04-05T10:04:58.517786Z 0 [Note] Binlog end
2017-04-05T10:04:58.517786Z 0 [Note] Shutting down plugin 'CSV'
2017-04-05T10:04:58.519788Z 0 [Note] C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe: Shutdown complete

I have tried, some options like turn off innodb_log_checksums via command line or set innodb_log_checksums = 0 in configure file. and then restart, or this one in stackoverflow but It is still stopped.
What can I do? Can some one help me?

Thank you

答:
Just had this problem, way i solved it was:

In the command prompt go to mysql location mysql\bin (use cd .. to go back one folder or cd name_of_folder to access it)

In this location, type mysqld --initialize


问:
jQuery Syntax Help
I'm looking for some help explaining exactly what this line of code does in jQuery;

```<code>myString += $(settings.mySelector,this).css('display') === 'none' ? 'closed' : 'not-closed';
</code>```

I'm unfamiliar with the syntax and some of the operators used.

答:
```<code>$(settings.mySelector,this).css('display')
</code>```

This selects an element that is a child of this and matches the given selector, then extracts the value of the CSS display property.

```<code>x === 'none' ? 'closed' : 'not-closed'
</code>```

This uses the conditional (?:) operator and evaluates to closed if x === 'none' or not-closed otherwise.

Finally, myString += y appends the value of y to myString.

Title: jQuery Syntax Help

Body:
I'm looking for some help explaining exactly what this line of code does in jQuery;

myString += $(settings.mySelector,this).css('display') === 'none' ? 'closed' : 'not-closed';

I'm unfamiliar with the syntax and some of the operators used.

Body:
$(settings.mySelector,this).css('display')

This selects an element that is a child of this and matches the given selector, then extracts the value of the CSS display property.

x === 'none' ? 'closed' : 'not-closed'

This uses the conditional (?:) operator and evaluates to closed if x === 'none' or not-closed otherwise.

Finally, myString += y appends the value of y to myString.


问:
API issue when editing order in opencart admin
Afternoon all,

I've got an issue when trying to change the status of an order (from pending to complete etc...) in the admin section.

A warning appears saying
Warning: You do not have permission to access the API!
if i have add my IP to the API IP address section it's working fine
the fields are all in red and the continue button doesn't work.

A similar thing happens if I view an order instead and try to add a new status to the order history.

I've seen this problem mentioned a few times in other posts but, afaik, without any satisfactory answer.

I'm using Opencart 2.0.3.1 and I'm logged in as an administrator and the administrator user group has all Access and Modify permissions enabled.

There is the default API user set up in System > Users > API and I also added (and then removed) another one but I was not sure what to do once I had created a new API user with a username and generated password.
There are no other problems on the site but, despite trying just about all the suggestions in the other forum posts, I can't edit the existing orders from the admin section.

答: I know it's late, but after trying everything and not getting it working, I deleted everything here /system/storage/cache. It solved the problem.


问:
Websockets and scalability
I am a beginner with websockets.
I have a need in my application where server needs to notify clients when something changes and am planning to use websockets.

Single server instance and  single client ==> How many websockets will be created and how many connections to websockets?

Single server instance and  10 clients ==> How many websockets will be created and how many connections to websockets?

Single server instance and  1000 clients ==>  How many websockets will be created and how many connections to websockets?

How do you scale with websockets when your application has a 1000’s of user base?

Thanks much for your feedback.

答:
1) Single server instance and single client ==> How many websockets will be created and how many connections to websockets?

If your client creates one webSocket connection, then that's what there will be one webSocket connection on the client and one on the server.  It's the client that creates webSocket connections to the server so it is the client that determines how many there will be.  If it creates 3, then there will be 3.  If it creates 1, then there will be 1.  Usually, the client would just create 1.

2) Single server instance and 10 clients ==> How many websockets will be created and how many connections to websockets?

As described above, it depends upon what the client does.  If each client creates 1 webSocket connection and there are 10 clients connected to the server, then the server will see a total of 10 webSocket connections.

3) Single server instance and 1000 clients ==> How many websockets will be created and how many connections to websockets?

Same as point #2.

How do you scale with webscokets when your application has a 1000’s of user base?

A single server, configured appropriately can handle hundreds of thousands of simultaneous webSocket connections that are mostly idle since an idle webSocket uses pretty much no server CPU.  For even larger scale deployments, one can cluster the server (run multiple server processes) and use sticky load balancing to spread the load.

There are many other articles like these on Google worth reading if you're pursuing large scale webSocket or socket.io deployments:

The Road to 2 Million Websocket Connections in Phoenix

600k concurrent websocket connections on AWS using Node.js

10 million concurrent webSockets

Ultimately, the achievable scale per a properly configured server will likely have more to do with how much activity there is per connection and how much computation is needed to deliver that.

ContentLicense: CC BY-SA 4.0

Title: Websockets and scalability


问:
Code push - Release update to multiple version
My app already on market with these versions. 1.0 ,1.1 ,1.2, 1.2.1 and 1.2.2.
 And now I need to release an update to version 1.0 , 1.1 , 1.2.

I have try with

```<code>code-push release-react myaap-Android Android --deploymentName Production --targetBinaryVersion=1.0-1.2
</code>```

But I got this error

```<code>[Error] Please use a semver-compliant target binary version range, for example "1.0.0", "*" or "^1.2.3"
</code>```

My first 3 version is not using semantic versioning, so how can I send update to them?
Thank you

答: you can always use the following range for that: >=1.0.0 <1.2.1</p>

Body:
My app already on market with these versions. 1.0 ,1.1 ,1.2, 1.2.1 and 1.2.2.
 And now I need to release an update to version 1.0 , 1.1 , 1.2.

I have try with

code-push release-react myaap-Android Android --deploymentName Production --targetBinaryVersion=1.0-1.2

But I got this error

[Error] Please use a semver-compliant target binary version range, for example "1.0.0", "*" or "^1.2.3"

My first 3 version is not using semantic versioning, so how can I send update to them?
Thank you


问:
Chrome Remote Developer tools not interpreting received data
I'm trying to create a Google Chrome DevTools Remote debugging session.

I have a remote debugging session, running on this URL:

```<code>chrome-devtools://devtools/remote/serve_rev/@8925c3c45f3923bc78ffc841842183cc592a0143/inspector.html?ws=localhost:8888/5f3be6ad-c4dd-4835-baf6-99779b6de1f6&remoteFrontend=true&dockSide=unlocked&experiments=true
</code>```

And I have a Node.js server, connected to remote DevTools via a Websocket connection.

I'm trying to send following message to the remote debugging session:

```<code>id: 1,
method: "Log.entryAdded",
params: {
   timestamp: (new Date).getTime(),
   text: "Forced reflow while executing JavaScript took 47ms",
   source: "violation",
   level: "verbose",
}
</code>```

The remote session clearly receives the message, judging from the Network log. (It's the last one)

But the dev tools don't seem to interpret the message correctly. As my Console is empty. But I'd expect a line, containing the a text message from above.

I'm stuck on this problem, as I don't know how to even debug this any further.

Help much aprreciated

答:
Managed to somewhat work this out.

I actually had to enable

```<code>{
   method: "Page.enable"
}
</code>```

and

```<code>{
   method: "Page.getResourceTree"
}
</code>```

in the debugger.

Now remote debugger correctly displays gathered console.log data. Therefore, enabling only

```<code>{
   method: "Log.enable"
}
</code>```

does not seem to be enough. Remote debugger needs more data than this, to interpret console.log data.

Body:
I'm trying to create a Google Chrome DevTools Remote debugging session.

I have a remote debugging session, running on this URL:

chrome-devtools://devtools/remote/serve_rev/@8925c3c45f3923bc78ffc841842183cc592a0143/inspector.html?ws=localhost:8888/5f3be6ad-c4dd-4835-baf6-99779b6de1f6&remoteFrontend=true&dockSide=unlocked&experiments=true

And I have a Node.js server, connected to remote DevTools via a Websocket connection.

I'm trying to send following message to the remote debugging session:

id: 1,
method: "Log.entryAdded",
params: {
   timestamp: (new Date).getTime(),
   text: "Forced reflow while executing JavaScript took 47ms",
   source: "violation",
   level: "verbose",
}

The remote session clearly receives the message, judging from the Network log. (It's the last one)

But the dev tools don't seem to interpret the message correctly. As my Console is empty. But I'd expect a line, containing the a text message from above.

I'm stuck on this problem, as I don't know how to even debug this any further.

Help much aprreciated

Body:
Managed to somewhat work this out.

I actually had to enable

{
   method: "Page.enable"
}

and

{
   method: "Page.getResourceTree"
}

in the debugger.

Now remote debugger correctly displays gathered console.log data. Therefore, enabling only

{
   method: "Log.enable"
}

does not seem to be enough. Remote debugger needs more data than this, to interpret console.log data.


问:
TypeError : list indices must be integers not str
I'd like to create an alarm whose metric (trigger) is ApproximateNumberOfMessagesVisible in a Queue 'myDownlinQueue', the alarm takes the action of autoscaling an AutoScalingGroup. However based on the code I am writing I get the error mentioned in the title. Maybe I am doing it wrong, but below is the code that causes this error.

```<code># ==== AutoSCaling config =======================
autoscaling_group = {
"name": "myAG", #descriptive name for your auto scaling group
"min_size": 0 , #Minimum number of instances that should be running at all times
"max_size": 0   #Maximum number of instances that should be running at all times
}

lc_name = 'myLG' #Descriptive name for your launch configuration

#=================AMI to launch======================================================
as_ami = {
"id": "ami-******c", #The AMI ID of the instance your Auto Scaling group will launch
"VpcId" : "vpc-0c805575",
"security_groups": "sg-xxxxxxxa", #The security group(s) your instances will belong to
"instance_type": "t2.micro", #The size of instance that will be launched
"instance_monitoring": True #Indicated whether the instances will be launched with detailed monitoring enabled. Needed to enable CloudWatch
}

conn_reg = boto.ec2.connect_to_region(region_name=awsRegion)
zones = conn_reg.get_all_zones()

zoneStrings = []
for zone in zones:
    zoneStrings.append(zone.name)
    print " Available zones : " + zone.name

conn_vpc = boto.connect_vpc()
subnetids = conn_vpc.get_all_subnets()

conn_as = AutoScaleConnection(AWS_ACCESS_KEY,AWS_SECRET_KEY)

lc = LaunchConfiguration(name = lc_name,
                         image_id = as_ami["id"],
                         instance_type = as_ami["instance_type"],
                         user_data = "user-data.bls",
                         associate_public_ip_address = True,
                         instance_monitoring=as_ami["instance_monitoring"])

conn_as.create_launch_configuration(lc)

ag = AutoScalingGroup(group_name = autoscaling_group["name"],
                      availability_zones= zoneStrings,
                      vpc_zone_identifier = subnetList,
                      launch_config=lc, min_size = autoscaling_group["min_size"],
                      max_size = autoscaling_group["max_size"])
conn_as.create_auto_scaling_group(ag)

#=================Create Scaling Policies===================================
# Policy for scaling the number of servers up and down

scalingUpPolicy = ScalingPolicy(name = "myScaleUpPolicy",
                                          adjustment_type ="ChangeInCapacity",
                                          as_name=ag.name,
                                          scaling_adjustment = numInstances ,
                                          cooldown=180)

scalingDownPolicy = ScalingPolicy(name = "myScaleDownPolicy",
                                           adjustment_type= "ExactCapacity",
                                           as_name=ag.name,
                                           scaling_adjustment= 0 ,
                                           cooldown=180)

conn_as.create_scaling_policy(scalingUpPolicy)
conn_as.create_scaling_policy(scalingDownPolicy)

scalingUpPolicy = conn_as.get_all_policies(as_group="myAG", policy_names=["myScaleUpPolicy"])[0]
scalingDownPolicy = conn_as.get_all_policies(as_group="myAG",policy_names=["myScaleDownPolicy"])[0]

# =========== CloudWatch Connection =============
cw = connect_to_region(awsRegion)

# ===========  SNS Connection ===================
sns = connect_to_region(awsRegion)

cw = CloudWatchConnection(AWS_ACCESS_KEY,AWS_SECRET_KEY)
sqs = SQSConnection(AWS_ACCESS_KEY,AWS_SECRET_KEY)

# ==== Alarm =================
numberOfMessages = 1
metric_object = cw.list_metrics(dimensions={"QueueName":"myDownlinkQueue"}, metric_name = "ApproximateNumberOfMessagesVisible",namespace = "AWS/SQS")

alarm_name = "myAlarm"

metric_object["ApproximateNumberOfMessagesVisible"].create_alarm(name =alarm_name,
                                             comparison=">=",
                                             threshold = numberOfMessages,
                                             period = 60,
                                             evaluation_periods = 1,
                                             statistic = "Average",
                                             alarm_actions=[scalingDownPolicy.policy_arn])
</code>```

The error is in the last method - creating an alarm, precisely scalingDownPolicy.policy_arn

答:
Either OP misread the documentation or confuse.

According to boto2   cloudwatch.list_metric(), the item will return a list.

list_metrics(next_token=None, dimensions=None, metric_name=None,
  namespace=None)

Returns a list of the valid metrics for which there is recorded data
  available.

So metric_object["ApproximateNumberOfMessagesVisible"] will kick error TypeError : list indices must be integers not str

OTH, boto3 cloudwatch.list_object return a dict. And they are NOT compatible. However, none of the dictionary key having ApproximateNumberOfMessagesVisible.

```<code>{
    'Metrics': [
        {
            'Namespace': 'string',
            'MetricName': 'string',
            'Dimensions': [
                {
                    'Name': 'string',
                    'Value': 'string'
                },
            ]
        },
    ],
    'NextToken': 'string'
}
</code>```

Body:
I'd like to create an alarm whose metric (trigger) is ApproximateNumberOfMessagesVisible in a Queue 'myDownlinQueue', the alarm takes the action of autoscaling an AutoScalingGroup. However based on the code I am writing I get the error mentioned in the title. Maybe I am doing it wrong, but below is the code that causes this error.

# ==== AutoSCaling config =======================
autoscaling_group = {
"name": "myAG", #descriptive name for your auto scaling group
"min_size": 0 , #Minimum number of instances that should be running at all times
"max_size": 0   #Maximum number of instances that should be running at all times
}

lc_name = 'myLG' #Descriptive name for your launch configuration

#=================AMI to launch======================================================
as_ami = {
"id": "ami-******c", #The AMI ID of the instance your Auto Scaling group will launch
"VpcId" : "vpc-0c805575",
"security_groups": "sg-xxxxxxxa", #The security group(s) your instances will belong to
"instance_type": "t2.micro", #The size of instance that will be launched
"instance_monitoring": True #Indicated whether the instances will be launched with detailed monitoring enabled. Needed to enable CloudWatch
}

conn_reg = boto.ec2.connect_to_region(region_name=awsRegion)
zones = conn_reg.get_all_zones()

zoneStrings = []
for zone in zones:
    zoneStrings.append(zone.name)
    print " Available zones : " + zone.name

conn_vpc = boto.connect_vpc()
subnetids = conn_vpc.get_all_subnets()

conn_as = AutoScaleConnection(AWS_ACCESS_KEY,AWS_SECRET_KEY)

lc = LaunchConfiguration(name = lc_name,
                         image_id = as_ami["id"],
                         instance_type = as_ami["instance_type"],
                         user_data = "user-data.bls",
                         associate_public_ip_address = True,
                         instance_monitoring=as_ami["instance_monitoring"])

conn_as.create_launch_configuration(lc)

ag = AutoScalingGroup(group_name = autoscaling_group["name"],
                      availability_zones= zoneStrings,
                      vpc_zone_identifier = subnetList,
                      launch_config=lc, min_size = autoscaling_group["min_size"],
                      max_size = autoscaling_group["max_size"])
conn_as.create_auto_scaling_group(ag)

#=================Create Scaling Policies===================================
# Policy for scaling the number of servers up and down

scalingUpPolicy = ScalingPolicy(name = "myScaleUpPolicy",
                                          adjustment_type ="ChangeInCapacity",
                                          as_name=ag.name,
                                          scaling_adjustment = numInstances ,
                                          cooldown=180)

scalingDownPolicy = ScalingPolicy(name = "myScaleDownPolicy",
                                           adjustment_type= "ExactCapacity",
                                           as_name=ag.name,
                                           scaling_adjustment= 0 ,
                                           cooldown=180)

conn_as.create_scaling_policy(scalingUpPolicy)
conn_as.create_scaling_policy(scalingDownPolicy)

scalingUpPolicy = conn_as.get_all_policies(as_group="myAG", policy_names=["myScaleUpPolicy"])[0]
scalingDownPolicy = conn_as.get_all_policies(as_group="myAG",policy_names=["myScaleDownPolicy"])[0]

# =========== CloudWatch Connection =============
cw = connect_to_region(awsRegion)

# ===========  SNS Connection ===================
sns = connect_to_region(awsRegion)

cw = CloudWatchConnection(AWS_ACCESS_KEY,AWS_SECRET_KEY)
sqs = SQSConnection(AWS_ACCESS_KEY,AWS_SECRET_KEY)

# ==== Alarm =================
numberOfMessages = 1
metric_object = cw.list_metrics(dimensions={"QueueName":"myDownlinkQueue"}, metric_name = "ApproximateNumberOfMessagesVisible",namespace = "AWS/SQS")

alarm_name = "myAlarm"

metric_object["ApproximateNumberOfMessagesVisible"].create_alarm(name =alarm_name,
                                             comparison=">=",
                                             threshold = numberOfMessages,
                                             period = 60,
                                             evaluation_periods = 1,
                                             statistic = "Average",
                                             alarm_actions=[scalingDownPolicy.policy_arn])

The error is in the last method - creating an alarm, precisely scalingDownPolicy.policy_arn

Body:
Either OP misread the documentation or confuse.

According to boto2   cloudwatch.list_metric(), the item will return a list.

list_metrics(next_token=None, dimensions=None, metric_name=None,
  namespace=None)

Returns a list of the valid metrics for which there is recorded data
  available.

So metric_object["ApproximateNumberOfMessagesVisible"] will kick error TypeError : list indices must be integers not str

OTH, boto3 cloudwatch.list_object return a dict. And they are NOT compatible. However, none of the dictionary key having ApproximateNumberOfMessagesVisible.

{
    'Metrics': [
        {
            'Namespace': 'string',
            'MetricName': 'string',
            'Dimensions': [
                {
                    'Name': 'string',
                    'Value': 'string'
                },
            ]
        },
    ],
    'NextToken': 'string'
}


问:
Working with Spring FeignClient with fallback behavior
I got a problem to solve with Spring FeignClient.

I have two endpoints to send an SMS, both are the same behavior:

When I send a GET with all query parameters required, the service sends the SMS.

But I need to check if endpoint A is off – in which case I must send to endpoint B, both with the same request path and payload.

How can I solve this problem?

Today I have an interface with FeignClient annotation and just one URL.

I tried to make use a FeignBuilder to create the request in runtime and change the URL but without success.

How can I use Feign to control service fallback in client side, like:

```<code>@Value(${sms.urls})
List<String> endPoints;

for (endPoint : endPoints){
  if(endPoint.isUp())
  return makeRequest(endPoint).
}
</code>```

答:
With regards to using FeignBuilder, maybe you can find an answer to your problem here

If this doesn't work, I would suggest creating a wrapper class around the interface.

When I had to deal with such a problem in the past I simply created a class that uses the Feign client interface. Spring will handle the wiring for you based on the fact that you annotated your feign client with the @FeignClient annotation. This way you can modify the behavior from the wrapper class. You'd write your fallback logic in a method and call the feign client as needed.

Hope this helps

Body:
I got a problem to solve with Spring FeignClient.

I have two endpoints to send an SMS, both are the same behavior:

When I send a GET with all query parameters required, the service sends the SMS.

But I need to check if endpoint A is off – in which case I must send to endpoint B, both with the same request path and payload.

How can I solve this problem?

Today I have an interface with FeignClient annotation and just one URL.

I tried to make use a FeignBuilder to create the request in runtime and change the URL but without success.

How can I use Feign to control service fallback in client side, like:

@Value(${sms.urls})
List<String> endPoints;

for (endPoint : endPoints){
  if(endPoint.isUp())
  return makeRequest(endPoint).
}


问:
How to hide url shown at bottom of browser when hover on link?
I am using colorbox with iframe true option for links to open.

In fancybox, I used a code to hide url shown at bottom of browser when hovered on link button.

But I am stucked at how to do it for colorbox.

I want solution for this following code :

```<code><script>
$(document).ready(function(){
   $(".iframecolor").colorbox({
       iframe:true, width:"80%", height:"80%"
   });
});
</script>
</code>```

And  tag used is as follows :

```<code><a class="iframecolor btn btn-success" href="http://www.linkofwebsite.com">VIEW NOW</a>
</code>```

Here I want to hide showing http://www.linkofwebsite.com shown at bottom of browser when we hover on VIEW NOW button.

==========================================================

==========================================================

The working code for fancybox used earlier is as follows:

```<code><script type="text/javascript">
      $(document).ready(function() {
        $('.fancybox').fancybox();

        $("#fancybox-manual-b").click(function() {
            $.fancybox.open({
                href : 'test.html',
                type : 'iframe',
                padding : 5
            });
        });

        $(".fancy").fancybox(); // ***This worked for fancybox to hide url
    });
</script>
</code>```

AND in  tag, code used as follows :

```<code><a class="fancybox fancybox.iframe more_info_btn" data-fancybox-href="http://www.linkofwebsite.com">VIEW NOW</a>
</code>```

答:
According to the colorbox documentation it can accept a href parameter, like you did with fancybox

```<code><script>
    $(document).ready(function(){
    $(".iframecolor").colorbox({
        iframe:true,
        width:"80%",
        height:"80%",
        href:"http://linkofwebsite.com"
    });
 });
</script>
<a class="iframecolor btn btn-success" href="#">VIEW NOW</a>
</code>```

http://www.jacklmoore.com/colorbox/

Body:
I am using colorbox with iframe true option for links to open.

In fancybox, I used a code to hide url shown at bottom of browser when hovered on link button.

But I am stucked at how to do it for colorbox.

I want solution for this following code :

And  tag used is as follows :

VIEW NOW

Here I want to hide showing http://www.linkofwebsite.com shown at bottom of browser when we hover on VIEW NOW button.

==========================================================

==========================================================

The working code for fancybox used earlier is as follows:

AND in  tag, code used as follows :

VIEW NOW

Body:
According to the colorbox documentation it can accept a href parameter, like you did with fancybox

<script>
    $(document).ready(function(){
    $(".iframecolor").colorbox({
        iframe:true,
        width:"80%",
        height:"80%",
        href:"http://linkofwebsite.com"
    });
 });
</script>
<a class="iframecolor btn btn-success" href="#">VIEW NOW</a>

http://www.jacklmoore.com/colorbox/


问:
Linked Lists: Iterator vs List Iterator
I'm reviewing linked lists in Java, learned them in C, and I noticed that I can use an iterator class to go through the linked list. But what I found strange is that they used a ListIterator to iterate forwards on the list (it can also be used to iterate backwards depending on where the pointer is), and Iterator to iterate backwards on the list. My question is, why can't we just use Iterator to iterate both forwards and backwards? What is the difference between the two?</p>

答:
From the API:

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list.

Conversely, an Iterator can only iterate forwards.

Title: Linked Lists: Iterator vs List Iterator


问:
Best practices for top-level domains in directory structure
I am researching the process on how to setup multiple websites from the same VPS. I have noticed that in many cases I have seen online, the directory folders are named to include the top-level domain.

Say you are serving example.com out of /var/www/example.com/. What is the reasoning for including the TLD in the directory name?

Wouldn’t it make more sense to just name it as /var/www/example/? For instance, if they wanted to later change the domain to example.net, they wouldn’t need to update the directory name.

答:
I can't speak for others, but I do this myself, so I'll answer from my perspective. Having a full domain name is a good practice because

You (or some other admin) don't have to guess

There can never be any conflicts such as between example.com and example.net existing simultaneously

If you are automating things, scripts are simpler because you can avoid extra level of mapping. (similar to point 1, but for computers)


问:
Why can't I access array inside forEach() in javascript
I'm not sure why i can't access the allSubIABs array inside forEach.
I can access the string newCheckState fine.

```<code>const newIABs = { ...this.state.iabs }
let allSubIABs = []
let newCheckState = 'asdasdasd'

console.log(typeof allSubIABs, allSubIABs)
Object.keys(newIABs).forEach(firstLevelIABCode => {
  console.log(newCheckState)
  console.log(typeof allSubIABs, allSubIABs)
  let allSubIABs = allSubIABs.concat(newIABs[firstLevelIABCode].children)
})
</code>```

Output:

```<code>object []
asdasdasd
undefined undefined
Uncaught TypeError: Cannot read property 'concat' of undefined
</code>```

答: Your problem is that the let declaration in the callback hides the outer allSubIABs declaration. Just get rid of that let.

Body:
I'm not sure why i can't access the allSubIABs array inside forEach.
I can access the string newCheckState fine.

const newIABs = { ...this.state.iabs }
let allSubIABs = []
let newCheckState = 'asdasdasd'

console.log(typeof allSubIABs, allSubIABs)
Object.keys(newIABs).forEach(firstLevelIABCode => {
  console.log(newCheckState)
  console.log(typeof allSubIABs, allSubIABs)
  let allSubIABs = allSubIABs.concat(newIABs[firstLevelIABCode].children)
})

Output:

object []
asdasdasd
undefined undefined
Uncaught TypeError: Cannot read property 'concat' of undefined


问:
Programmatically add arguments to a Promise
I need to create a function that receives a Promise as a first parameter and an array of its parameters (if it has at least one) or null if none.

My function looks this way:

```<code>var executeMappingStep = (promiseStatus, myPromise, myPromiseParams) => {
    return new Promise((resolve, reject) => {
        //if the execution was success, there's no need to invoke myPromise again
        if(promiseStatus.success == true)
           return resolve(promiseStatus.previousResponseSaved);

        if (myPromiseParams!= null) {
            //how I resolve this logic is my doubt
            myPromise.addArrayOfParameters(myPromiseParams);
        }

        myPromise().then(result => resolve(result)).catch(err => reject(err));
    });
};
</code>```

I was reading about the .bind() function which works for functions but not for promises according to this question. I also saw something about the .apply() function, but this doesn't seems to be what I need.

Edit

My function is invoked like myFirstPromise when there aren't parameters, and like mySecondPromise when I have at least one:

```<code>var executePromises = (myFirstPromise, mySecondPromisePromise) => {
    return new Promise((resolve, reject) => {
        //retrieve an array of every promise status
        var promisesStatus = getPromisesStatus();

        executeMappingStep(promisesStatus[0], myFirstPromise, null).then(result => {
                return convertToXml(result);
        }).then(result => {

            var parameters = {
                value1 : result,
                value2: [1,2,3],
                value3: "some string",
                value4: 10
            };

            return executeMappingStep(promisesStatus[1], mySecondPromisePromise, parameters);
        }).then(result => resolve(result)).catch(err => reject(err));
    });
};

var myFirstPromise = function() {
    return new Promise(function (resolve, reject) {
        //some logic for first promise
    });
}

var mySecondPromise = function(firstParam, secondParam, thirdParam, fourthParam) {
    return new Promise(function (resolve, reject) {
        //some logic for second promise with its params
    });
}
</code>```

Probably, in the function addArrayOfParameters I need to loop into every property on the object (I realized that an array would not work), like this

Is there a way to programmatically add parameters from an array before its resolved?

Edit 2

The reason behind this logic is much complex, but this is pretty much what I need to solve. Basically, in my code, every promise can be executed with errors and there's a logic involved in the executePromises function which returns the status of every promise whether was successfully executed or not. This logic involves more than 10 promises chained, and if some of them fail e.g: promise number 5, then 6,7 etc, will have to be invoked again in some admin backend.

I don't what to replicate the logic for each promise, so that's why I wanted to create the executeMappingStep function to encapsulate that logic.
Probably is hard to explain, I tried to simplify the most as I could. I made a few more changes to explain what I just said.

答:
Probably, I have complicated things a lot here, but anyway, this is the solution that I wanted.
It's good to know that the .then function can invoked in other place and the promises can be created with the needed arguments and then sent as parameter.

With that said:

```<code>var executePromises = (myFirstPromise, mySecondPromisePromise) => {
    return new Promise((resolve, reject) => {
        //retrieve an array of every promise status
        var promisesStatus = getPromisesStatus();

        executeMappingStep(promisesStatus[0], myFirstPromise()).then(result => {
                return convertToXml(result);
        }).then(result => {

            var mySecondPromisePromiseParameter = mySecondPromise(result, [1,2,3], "some string", 10);

            return executeMappingStep(promisesStatus[1], mySecondPromisePromiseParameter);
        }).then(result => resolve(result)).catch(err => reject(err));
    });
};
</code>```

An then, the executeMappingStep just receives the promise and invokes the .then internally, this way:

```<code>var executeMappingStep = (promiseStatus, myPromise) => {
    return new Promise((resolve, reject) => {
        //if the execution was success, there's no need to invoke myPromise again
        if(promiseStatus.success == true)
           return resolve(promiseStatus.previousResponseSaved);

        myPromise.then(result => resolve(result)).catch(err => reject(err));
    });
};
</code>```

Body:
I need to create a function that receives a Promise as a first parameter and an array of its parameters (if it has at least one) or null if none.

My function looks this way:

var executeMappingStep = (promiseStatus, myPromise, myPromiseParams) => {
    return new Promise((resolve, reject) => {
        //if the execution was success, there's no need to invoke myPromise again
        if(promiseStatus.success == true)
           return resolve(promiseStatus.previousResponseSaved);

        if (myPromiseParams!= null) {
            //how I resolve this logic is my doubt
            myPromise.addArrayOfParameters(myPromiseParams);
        }

        myPromise().then(result => resolve(result)).catch(err => reject(err));
    });
};

I was reading about the .bind() function which works for functions but not for promises according to this question. I also saw something about the .apply() function, but this doesn't seems to be what I need.

Edit

My function is invoked like myFirstPromise when there aren't parameters, and like mySecondPromise when I have at least one:

var executePromises = (myFirstPromise, mySecondPromisePromise) => {
    return new Promise((resolve, reject) => {
        //retrieve an array of every promise status
        var promisesStatus = getPromisesStatus();

        executeMappingStep(promisesStatus[0], myFirstPromise, null).then(result => {
                return convertToXml(result);
        }).then(result => {

            var parameters = {
                value1 : result,
                value2: [1,2,3],
                value3: "some string",
                value4: 10
            };

            return executeMappingStep(promisesStatus[1], mySecondPromisePromise, parameters);
        }).then(result => resolve(result)).catch(err => reject(err));
    });
};

var myFirstPromise = function() {
    return new Promise(function (resolve, reject) {
        //some logic for first promise
    });
}

var mySecondPromise = function(firstParam, secondParam, thirdParam, fourthParam) {
    return new Promise(function (resolve, reject) {
        //some logic for second promise with its params
    });
}

Probably, in the function addArrayOfParameters I need to loop into every property on the object (I realized that an array would not work), like this

Is there a way to programmatically add parameters from an array before its resolved?

Edit 2

The reason behind this logic is much complex, but this is pretty much what I need to solve. Basically, in my code, every promise can be executed with errors and there's a logic involved in the executePromises function which returns the status of every promise whether was successfully executed or not. This logic involves more than 10 promises chained, and if some of them fail e.g: promise number 5, then 6,7 etc, will have to be invoked again in some admin backend.

I don't what to replicate the logic for each promise, so that's why I wanted to create the executeMappingStep function to encapsulate that logic.
Probably is hard to explain, I tried to simplify the most as I could. I made a few more changes to explain what I just said.

Body:
Probably, I have complicated things a lot here, but anyway, this is the solution that I wanted.
It's good to know that the .then function can invoked in other place and the promises can be created with the needed arguments and then sent as parameter.

With that said:

var executePromises = (myFirstPromise, mySecondPromisePromise) => {
    return new Promise((resolve, reject) => {
        //retrieve an array of every promise status
        var promisesStatus = getPromisesStatus();

        executeMappingStep(promisesStatus[0], myFirstPromise()).then(result => {
                return convertToXml(result);
        }).then(result => {

            var mySecondPromisePromiseParameter = mySecondPromise(result, [1,2,3], "some string", 10);

            return executeMappingStep(promisesStatus[1], mySecondPromisePromiseParameter);
        }).then(result => resolve(result)).catch(err => reject(err));
    });
};

An then, the executeMappingStep just receives the promise and invokes the .then internally, this way:

var executeMappingStep = (promiseStatus, myPromise) => {
    return new Promise((resolve, reject) => {
        //if the execution was success, there's no need to invoke myPromise again
        if(promiseStatus.success == true)
           return resolve(promiseStatus.previousResponseSaved);

        myPromise.then(result => resolve(result)).catch(err => reject(err));
    });
};


问:
PHP Error Array to string conversion
I have class Router which has array of routes property

```<code><?php
class Router
{
    private $routes = [];

    function setRoutes(array $routes)
    {
        $this->$routes = $routes;
    }
}
?>
</code>```

In other File routes.php :

```<code><?php
$routes = [
    'users' => 'users.php',
    'comments' => 'comments.php'
];
?>
</code>```

And I use it like :

```<code><?php
require __DIR__ .'/Data.php';
require __DIR__ .'/Router.php';
require __DIR__ .'/../routes.php';

$router = new Router;
$router->setRoutes($routes);
$url = $_SERVER['REQUEST_URI'];
?>
</code>```

But I'm getting

Notice: Array to string conversion in /../XAMPP/xamppfiles/htdocs/TestPro/core/Router.php

Why this error is occurring ?

答:
YOu should replace this line:

```<code>$this->$routes = $routes;
</code>```

By:

```<code>$this->routes = $routes;
</code>```

Attributes should be called without $

Title: PHP Error Array to string conversion

Body:
I have class Router which has array of routes property

<?php
class Router
{
    private $routes = [];

    function setRoutes(array $routes)
    {
        $this->$routes = $routes;
    }
}
?>

In other File routes.php :

<?php
$routes = [
    'users' => 'users.php',
    'comments' => 'comments.php'
];
?>

And I use it like :

<?php
require __DIR__ .'/Data.php';
require __DIR__ .'/Router.php';
require __DIR__ .'/../routes.php';

$router = new Router;
$router->setRoutes($routes);
$url = $_SERVER['REQUEST_URI'];
?>

But I'm getting

Notice: Array to string conversion in /../XAMPP/xamppfiles/htdocs/TestPro/core/Router.php

Why this error is occurring ?

Body:
YOu should replace this line:

$this->$routes = $routes;

By:

$this->routes = $routes;

Attributes should be called without $


问:
How to send push notification from user to user?
Trying to send push notification from user-to-user, UserA is bidding on the value for an item. Scenario, UserA updates a value in the app and clicks send, and at the same time UserB gets a notification of the updated value.

```<code>       If UserB approves of the message(value) {
           UserA gets gets the notification of approval and proceeds to
      final step of buying the item.
 }  else {
sends no and UserA is updated of the denial and he sends a new value for approval
}
</code>```

A guide to accomplish the task would be greatly appreciated.

P.S using firebase as backend

答:
Sending Push Notifications is done with Apple Push Notification Service. Apple provides a documentation on how to use APNs.

The basic principal is illustrated in this picture.

Sending Messages from one device directly to another is not the way it works. You have to send a notification to the APNs in order to push them to another devices.

Since you are using Firebase I would recommend using Firebase Cloud Messaging to send Push Notifications.

If you just need real time updates in the app Firebase event listeners should work just fine.

Body:
Trying to send push notification from user-to-user, UserA is bidding on the value for an item. Scenario, UserA updates a value in the app and clicks send, and at the same time UserB gets a notification of the updated value.

       If UserB approves of the message(value) {
           UserA gets gets the notification of approval and proceeds to
      final step of buying the item.
 }  else {
sends no and UserA is updated of the denial and he sends a new value for approval
}

A guide to accomplish the task would be greatly appreciated.

P.S using firebase as backend


问:
WCF Client SocketException
We are getting an error on our production environment:

System.ServiceModel.CommunicationException:
  The socket connection was aborted.
  This could be caused by an error
  processing your message or a receive
  timeout being exceeded by the remote
  host, or an underlying network
  resource issue. Local socket timeout
  was '00:10:00'. --->
  System.Net.Sockets.SocketException: An
  existing connection was forcibly
  closed by the remote host

This happens on the first request after the WCF service has been idle for a time. Subsequent requests work correctly.

This error does not occur on our staging environment with the same configuration and data.

How do I go about diagnosing this? Tracing does not give any useful information.

Thanks,
Jon

答:
The first place to look is this: http://msdn.microsoft.com/en-us/library/bb332338.aspx

The issue you are describing sounds like IdleTimeout or ShutdownTimeout settings and having the domain recycle. Most likely, you have a long spin up time for the code to rejit when it spins down. Just a guess, but it would cover the symptoms.

One way to dupe this in another environment is setting up an instance and hitting it and then letting it sit idle for quite some time. If that yields nothing, get a delta between the environments. If you are doing more on the production environment that could be an issue when spin up happens.

Title: WCF Client SocketException


问:
Karma config - including other config files
I haven't seen anything on this, but I was wondering if it was possible to include multiple karma-conf.js files in a single Karma run? Basically, I'm thinking of having a configuration with coverage and tslint for CI as well as a configuration with just tests for local development.</p>

答:
As far as I know Karma only accepts a single configuration file as input, that can be specified as command line argument or as part of the constructor options of the karma server.

Maybe gulp offers an alternative approach for you. I use a gulp file with several tasks. Each task is able to override the default configuration that is given in karma-conf.js, e.g.

```<code>console.log('Importing gulp dependencies ...');

var gulp = require('gulp');
var karma = require('karma');
var KarmaServerConstructor = karma.Server;
var karmaStopper = karma.stopper;
var watch = require('gulp-watch');
var commandLineArguments = require('yargs').argv;
var svn = require('gulp-svn');
var exec = require('child_process').exec;
var fs = require('fs');
var os = require('os');
var open = require('gulp-open');
var collect = require('gulp-collect');

console.log('Imports finished.');

gulp.task('watch', function() {

  return gulp //
    .watch('MyTestProject/App/**/*.spec.js', handleFileChanged)
    .on('error', handleGulpError);

  function handleFileChanged(vinyl) {

    var pathForChangedFile = './' + vinyl.replace(/\\/g, '/');

    var karmaOptions = {
      configFile: __dirname + '/karma.conf.js',
      action: 'start',
      browsers: ['PhantomJS'],
      singleRun: true,
      files: firstKarmaFiles //
        .concat([
          {
            pattern: pathForChangedFile,
            included: false
          }
        ]) //
        .concat(lastKarmaFiles)
    };

    var karmaServer = new KarmaServerConstructor(karmaOptions);
    karmaServer.start();
    }
});
</code>```

Body:
As far as I know Karma only accepts a single configuration file as input, that can be specified as command line argument or as part of the constructor options of the karma server.

Maybe gulp offers an alternative approach for you. I use a gulp file with several tasks. Each task is able to override the default configuration that is given in karma-conf.js, e.g.

console.log('Importing gulp dependencies ...');

var gulp = require('gulp');
var karma = require('karma');
var KarmaServerConstructor = karma.Server;
var karmaStopper = karma.stopper;
var watch = require('gulp-watch');
var commandLineArguments = require('yargs').argv;
var svn = require('gulp-svn');
var exec = require('child_process').exec;
var fs = require('fs');
var os = require('os');
var open = require('gulp-open');
var collect = require('gulp-collect');

console.log('Imports finished.');

gulp.task('watch', function() {

  return gulp //
    .watch('MyTestProject/App/**/*.spec.js', handleFileChanged)
    .on('error', handleGulpError);

  function handleFileChanged(vinyl) {

    var pathForChangedFile = './' + vinyl.replace(/\\/g, '/');

    var karmaOptions = {
      configFile: __dirname + '/karma.conf.js',
      action: 'start',
      browsers: ['PhantomJS'],
      singleRun: true,
      files: firstKarmaFiles //
        .concat([
          {
            pattern: pathForChangedFile,
            included: false
          }
        ]) //
        .concat(lastKarmaFiles)
    };

    var karmaServer = new KarmaServerConstructor(karmaOptions);
    karmaServer.start();
    }
});


问:
jss how to change opacity for a color
Currently I am using the following code to add a color to an element using jss.

const styleSheet = theme => ({
  root: {
     backgroundColor: theme.colors.red,
  },
})```

I would like to know if exist a function to add opacity based on colortheme.colors.red.

example smt like:
backgroundColor: color(theme.colors.red, .05),

答:
I found a solution using</p>

```<code> backgroundColor: theme.utils.rgba(theme.axColor.black, 0.7),
</code>```

Title: jss how to change opacity for a color

Body:
Currently I am using the following code to add a color to an element using jss.

const styleSheet = theme => ({
  root: {
     backgroundColor: theme.colors.red,
  },
})

I would like to know if exist a function to add opacity based on colortheme.colors.red.

example smt like:
backgroundColor: color(theme.colors.red, .05),

Body:
I found a solution using

 backgroundColor: theme.utils.rgba(theme.axColor.black, 0.7),


问:
What's the equivalent SQL code for this hashing code in Java (Scala)
I have the following Scala code that is hashing user password:

```<code>val digest = MessageDigest.getInstance("SHA-256")
val hash = new String(digest.digest (password.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8).getBytes
</code>```

I want to do the same in my PostgresSQL server using SQL.

I have tried

```<code>digest(password, 'sha256')
</code>```

didn't work, I am guessing it is because of the getBytes call in java, we are digesting the bytes of the strings and not the string itself (if it even make any sense!)

what is the equivalent of getBytes for Postgress SQL ? if it exists ?

Thank you.

CONTEXT
I am just trying to make a query that will insert a user manually for ease of testing, it is inserting but I can't log in. the digest generated by my query and by the scala code is not the same.

答:
```<code>val hash = new String(digest.digest (password.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8).getBytes
</code>```

That's wrong. You're hashing the password properly, then for some reason you turn the bytes into a String...only to turn it back to bytes again. That's unnecessary, stupid, and will most likely corrupt things.

```<code>val hash = digest.digest (password.getBytes(StandardCharsets.UTF_8))
</code>```

There's your hash in bytes.

To mimic your broken code try convert_from(digest(password, 'sha256'), 'UTF8')::bytea and see if you get the same results.

Body:
I have the following Scala code that is hashing user password:

val digest = MessageDigest.getInstance("SHA-256")
val hash = new String(digest.digest (password.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8).getBytes

I want to do the same in my PostgresSQL server using SQL.

I have tried

digest(password, 'sha256')

didn't work, I am guessing it is because of the getBytes call in java, we are digesting the bytes of the strings and not the string itself (if it even make any sense!)

what is the equivalent of getBytes for Postgress SQL ? if it exists ?

Thank you.

CONTEXT
I am just trying to make a query that will insert a user manually for ease of testing, it is inserting but I can't log in. the digest generated by my query and by the scala code is not the same.

Body:
val hash = new String(digest.digest (password.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8).getBytes

That's wrong. You're hashing the password properly, then for some reason you turn the bytes into a String...only to turn it back to bytes again. That's unnecessary, stupid, and will most likely corrupt things.

val hash = digest.digest (password.getBytes(StandardCharsets.UTF_8))

There's your hash in bytes.

To mimic your broken code try convert_from(digest(password, 'sha256'), 'UTF8')::bytea and see if you get the same results.


问:
Remove diacritics from a string
Is it possible? This is my input string:

```<code>ľ š č ť ž ý á í é Č Á Ž Ý
</code>```

This is the output I want:

```<code>l s c t z y a i e C A Z Y
</code>```

答:
If intl php extension is enabled, you can use Transliterator like this :

```<code>protected function removeDiacritics($string)
{
    $transliterator = \Transliterator::create('NFD; [:Nonspacing Mark:] Remove; NFC;');
    return $transliterator->transliterate($string);
}
</code>```

To remove other special chars (not diacritics only like 'æ')

```<code>protected function removeDiacritics($string)
{
    $transliterator = \Transliterator::createFromRules(
        ':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;',
        \Transliterator::FORWARD
    );
    return $transliterator->transliterate($string);
}
</code>```

Title: Remove diacritics from a string

Body:
Is it possible? This is my input string:

ľ š č ť ž ý á í é Č Á Ž Ý

This is the output I want:

l s c t z y a i e C A Z Y

Body:
If intl php extension is enabled, you can use Transliterator like this :

protected function removeDiacritics($string)
{
    $transliterator = \Transliterator::create('NFD; [:Nonspacing Mark:] Remove; NFC;');
    return $transliterator->transliterate($string);
}

To remove other special chars (not diacritics only like 'æ')

protected function removeDiacritics($string)
{
    $transliterator = \Transliterator::createFromRules(
        ':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;',
        \Transliterator::FORWARD
    );
    return $transliterator->transliterate($string);
}


问:
How to write a code that distinguishes if there is '0' in existing file, or new generated file
I've been working on code that:

1. checks if "sample.txt" exist, if not ,generate a new file,

2. if file already exist, check if first line has single '0'. if not, truncate and write '0'

Below is what i've written so far. however the iszeroOrnewfile always turns into 0 so don't go into different case. Am i approaching this correctly?

```<code>   #include <fcntl.h>
   #include <unistd.h>
   #include <string.h>
   #define buf 128
   int main (int argc, char** argv)
   {
       int fd;
      char buff[buf]={0} ;
      int iszeroOrnewfile=1;
      int iszero=0;
      if(!(argv[0]>0))
          printf("insert positive integer");
      fd = open("./sample.txt",O_RDWR|O_CREAT);
      pread ( fd,buff,buf,0);
      for (int i=0;i<buf;i++)
      {
          if((0 != buff[i]) || ('0' != buff[i]) )
              {   iszeroOrnewfile = 0;}
          if('0' == buff [i]);
              { iszero = 1;}

      }
      if (iszeroOrnewfile == 1 )
      {
          if (iszero !=1)
          write(fd, "0",strlen("0"));
      }
      else if(iszeroOrnewfile ==0)
      {
          truncate ("./sample.txt" , 0);
          write(fd, "0",strlen("0"));
      }

  }
</code>```

答:
Following code may be useful:</p>

```<code>#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#define buf 128

int main (int argc, char** argv)
{
    int fd;
    char buff[buf]={0} ;
    int iszeroOrnewfile=1;
    int iszero=0;
    int isFileCreated = 0;
    int len = 0;
    int i;
    if(!(argv[0]>0))
        printf("insert positive integer");
    fd = open("./sample.txt",O_RDWR);
    if(fd==-1 && errno==ENOENT)
    {
        //File dosen't exists
        isFileCreated = 1;
        fd = open("./sample.txt",O_RDWR|O_CREAT);
        write(fd, "0",strlen("0"));
    }
    else
    {
        len = pread ( fd,buff,buf,0);
        for (i=0;i<len;i++)
        {
            if((0 == buff[i]) || ('0' == buff[i]) )
            {
                iszero = 1;
                break;
            }
        }
        if(len==-1 || iszero)
        {
            truncate ("./sample.txt" , 0);
            write(fd, "0",strlen("0"));
        }
    }
    return 0;
}
</code>```

Body:
I've been working on code that:

1. checks if "sample.txt" exist, if not ,generate a new file,

2. if file already exist, check if first line has single '0'. if not, truncate and write '0'

Below is what i've written so far. however the iszeroOrnewfile always turns into 0 so don't go into different case. Am i approaching this correctly?

   #include <fcntl.h>
   #include <unistd.h>
   #include <string.h>
   #define buf 128
   int main (int argc, char** argv)
   {
       int fd;
      char buff[buf]={0} ;
      int iszeroOrnewfile=1;
      int iszero=0;
      if(!(argv[0]>0))
          printf("insert positive integer");
      fd = open("./sample.txt",O_RDWR|O_CREAT);
      pread ( fd,buff,buf,0);
      for (int i=0;i<buf;i++)
      {
          if((0 != buff[i]) || ('0' != buff[i]) )
              {   iszeroOrnewfile = 0;}
          if('0' == buff [i]);
              { iszero = 1;}

      }
      if (iszeroOrnewfile == 1 )
      {
          if (iszero !=1)
          write(fd, "0",strlen("0"));
      }
      else if(iszeroOrnewfile ==0)
      {
          truncate ("./sample.txt" , 0);
          write(fd, "0",strlen("0"));
      }

  }

Body:
Following code may be useful:

#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#define buf 128

int main (int argc, char** argv)
{
    int fd;
    char buff[buf]={0} ;
    int iszeroOrnewfile=1;
    int iszero=0;
    int isFileCreated = 0;
    int len = 0;
    int i;
    if(!(argv[0]>0))
        printf("insert positive integer");
    fd = open("./sample.txt",O_RDWR);
    if(fd==-1 && errno==ENOENT)
    {
        //File dosen't exists
        isFileCreated = 1;
        fd = open("./sample.txt",O_RDWR|O_CREAT);
        write(fd, "0",strlen("0"));
    }
    else
    {
        len = pread ( fd,buff,buf,0);
        for (i=0;i<len;i++)
        {
            if((0 == buff[i]) || ('0' == buff[i]) )
            {
                iszero = 1;
                break;
            }
        }
        if(len==-1 || iszero)
        {
            truncate ("./sample.txt" , 0);
            write(fd, "0",strlen("0"));
        }
    }
    return 0;
}


问:
2 and 3 node Cassandra cluster setup
I have 2 issues.

1- I need 2 node cluster. I must write & read if 1 node is gone.

I think I need= Replication Factor:2 Consistency:1

But it certainly should not be the loss of any data.

2- I need 3 node cluster and nodes may increase over time. I should be able to add more nodes with this setup.

I think I need= Replication Factor:3 Consistency:2

The question is: Am i right on this configurations?

Thank you for answers.

答:
tldr; Use 3 node cluster for both, write/read quorum.

Keep in mind: Write Consistency + Read Consistency > Replication factor to ensure that your data is consistent.

You may as well go with a 3 node cluster for both.  Alternatively in your first setup (2 nodes) is the same as a 1 node 'cluster'.  Because you're either writing to ALL, or your reads won't be consistent.

Setup 1:

For Setup 1 in a RF 2 you would need to:

Write(2) + Read(1) If a node goes down, you can no longer write to the cluster.

Read(2) + write(1) If a node goes down you can no longer read from the cluster AND you've lost data.

Write(2) + Read(2)  Same effort as 3 node cluster.  Why do 2?

Neither of these is ideal and the only advantage the 2 node cluster has over a 1 node 'cluster' is that if you're writing to all at least you don't lose data when a node dies.

Setup 2:

Ideally here you go with quorum, otherwise you're more likely to suffer outages.

Write(2) + Read(2) > RF Quorum (option 1) enables 1 node to die and your cluster to function as normal.

Write(3) + Read(1) > RF Write 3 allows you to only read from 1 node, speeding up reads at the cost of failing writes if a node becomes disconnected.

Write(1) + Read(3) > RF Read 3 Speeds up writes at the cost of losing data if a node goes down.

Title: 2 and 3 node Cassandra cluster setup


问:
Symfony2 - Adding a new field to an existing entity
First off, I am completely new to Symfony2.

I created an entity -> created a table based on that entity -> created a form using the entity.

I have now realised I need to add a field to the form. So I did the following:

Added the new property -> Added the ORM annotations -> Generated the setters and getters -> ran "php app/console doctrine:schema:update"

This resulted in the following exception: "The table with name 'XXX' already exists"

So nothing was updated. Any idea what I did wrong? Below is the property I added to the entity:

```<code>/**
 * @var text
 *
 * @ORM\Column(name="description", type="text")
 *
 * @Assert\NotBlank(message="Please insert a description")
 * @Assert\Length(max=100)
 *
 */
private $description;
</code>```

答:
I know this is an old question. But I write because it can be usefull for others.

Probably you are not using annotations in your project. Probably your project is confiured for use xml or yml.

you must to check your configuation at $proyect_home/app/config/config.yml and write in the orm zone:

```<code>orm:
  ....
  mappings:
    AppBundle:
      type: annotation
</code>```

Body:
First off, I am completely new to Symfony2.

I created an entity -> created a table based on that entity -> created a form using the entity.

I have now realised I need to add a field to the form. So I did the following:

Added the new property -> Added the ORM annotations -> Generated the setters and getters -> ran "php app/console doctrine:schema:update"

This resulted in the following exception: "The table with name 'XXX' already exists"

So nothing was updated. Any idea what I did wrong? Below is the property I added to the entity:

/**
 * @var text
 *
 * @ORM\Column(name="description", type="text")
 *
 * @Assert\NotBlank(message="Please insert a description")
 * @Assert\Length(max=100)
 *
 */
private $description;

Body:
I know this is an old question. But I write because it can be usefull for others.

Probably you are not using annotations in your project. Probably your project is confiured for use xml or yml.

you must to check your configuation at $proyect_home/app/config/config.yml and write in the orm zone:

orm:
  ....
  mappings:
    AppBundle:
      type: annotation


Title: Create 6 bar subplots based on columns in dataframe

Body:
I have a bar plot that looks sort of like this:

I am hoping to make six different bar plots (one per "season", e.g. MAM 16) based on the columns of my dataframe dat.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

labels = {'pod','MAM-16',  'MAM-17',  'JJAS-16', 'JJAS-17', 'OND-15','OND-16'}
rf = [('22','343.7','467.4', '157', '251', '100','142.5'),
('72',  '82',  '184.4',   '143.3',  '12.7',  '120',  '152.4'),
('79',  '76.5',    '167.4',   '118.1',   '185.4',  '190', '145'),
('86',  '993.4',   '66.5',    '198.9',   '14', '78', '84.8'),
('87',  '206.2',   '178.1',   '121.4',   '285.2',  '89' ,'65'),
('88',  '209.3',   '280.4',  '138.4',   '279.9', '84',  '141'),
('90' , '134.9',   '137.9',   '92.7',    '224', '111', '133.1'),
('93',  '180.8',   '113.8',   '179.6',   '108.2', '184',  '211.8'),
('95',  '329.7',   '176.5',   '168.9',   '64', '75','103.6'),
('96', '270.5',   '158.5',   '196.6',   '363', '128','152.4'),
('97',  '167.9',   '103.1',   '184.4',   '117.1',  '132', '104.1'),
dat = pd.DataFrame.from_records(rf, columns=labels); dat

The first column in dat refers to a different ID which are the colored bars in the figure above and is not numeric. The rest of the values are numeric.

I know I can plot all the values together using something like this:

ax = dat.plot(kind='bar',rot=0,lw=2,colormap='jet',figsize=(10,4),
             title='Sample title')
x1 = [0,1,2,3,4,5]
labels = ['MAM 16', 'MAM 17', 'JJAS 16','JJAS 17', 'OND 15','OND 16']
ax1.set_xticks(x1)
ax1.set_xticklabels(labels, minor=False, rotation=45)
ax.set_xticklabels(labels)
plt.show()

To get subplots I imagine I could use a for-loop:

for col in dat:
    fig = plt.figure(figsize=(5.0, 6.0))

    axes1 = fig.add_subplot(3, 2, 1)
    axes2 = fig.add_subplot(3, 2, 2)
    axes3 = fig.add_subplot(3, 2, 3)

    axes1.set_ylabel('rainfall / mm')
    axes1.plot(???)

    axes2.set_ylabel('total rainfall / mm')
    axes2.plot(???)

    axes3.set_ylabel('total rainfall / mm')
    axes3.plot(???)

    fig.tight_layout()
    plt.show()

The result should be a 2x3 matrix of subplots where each group of bar plots from the image (fig1) above is its own plot.

Body:
You want to use the subplots=True and layout argument of the plotting function. This allows to obtain a subplot grid of the plots.

The following is a runnable example (where I replaced the strings "mean" and "var" by something useful).

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

labels = {'pod','MAM-16',  'MAM-17',  'JJAS-16', 'JJAS-17', 'OND-15','OND-16'}
rf = [('22','343.7','467.4', '157', '251', '100','142.5'),
('72',  '82',  '184.4',   '143.3',  '12.7',  '120',  '152.4'),
('79',  '76.5',    '167.4',   '118.1',   '185.4',  '190', '145'),
('86',  '993.4',   '66.5',    '198.9',   '14', '78', '84.8'),
('87',  '206.2',   '178.1',   '121.4',   '285.2',  '89' ,'65'),
('88',  '209.3',   '280.4',  '138.4',   '279.9', '84',  '141'),
('90' , '134.9',   '137.9',   '92.7',    '224', '111', '133.1'),
('93',  '180.8',   '113.8',   '179.6',   '108.2', '184',  '211.8'),
('95',  '329.7',   '176.5',   '168.9',   '64', '75','103.6'),
('96', '270.5',   '158.5',   '196.6',   '363', '128','152.4'),
('97',  '167.9',   '103.1',   '184.4',   '117.1',  '132', '104.1'),
('98', '394', '204.6',   '53.6',    '332.5', '85',  '103.4'),
('99', '243', '103.6',   '33.2',    '112.5', '25',  '37.9')]
dat = pd.DataFrame.from_records(rf, columns=labels).astype(float)

labels = ['MAM 16', 'MAM 17', 'JJAS 16','JJAS 17', 'OND 15','OND 16']
dat = dat[['MAM-16',  'MAM-17',  'JJAS-16', 'JJAS-17', 'OND-15','OND-16']]
axes = dat.plot(kind='bar',rot=0,lw=2,colormap='jet',figsize=(10,4),
             title='Sample title', subplots=True, layout=(3,2))

plt.show()

To set the colors of the bars differently, you need to manually set them.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

labels = {'pod','MAM-16',  'MAM-17',  'JJAS-16', 'JJAS-17', 'OND-15','OND-16'}
rf = [('22','343.7','467.4', '157', '251', '100','142.5'),
('72',  '82',  '184.4',   '143.3',  '12.7',  '120',  '152.4'),
('79',  '76.5',    '167.4',   '118.1',   '185.4',  '190', '145'),
('86',  '993.4',   '66.5',    '198.9',   '14', '78', '84.8'),
('87',  '206.2',   '178.1',   '121.4',   '285.2',  '89' ,'65'),
('88',  '209.3',   '280.4',  '138.4',   '279.9', '84',  '141'),
('90' , '134.9',   '137.9',   '92.7',    '224', '111', '133.1'),
('93',  '180.8',   '113.8',   '179.6',   '108.2', '184',  '211.8'),
('95',  '329.7',   '176.5',   '168.9',   '64', '75','103.6'),
('96', '270.5',   '158.5',   '196.6',   '363', '128','152.4'),
('97',  '167.9',   '103.1',   '184.4',   '117.1',  '132', '104.1'),
('98', '394', '204.6',   '53.6',    '332.5', '85',  '103.4'),
('99', '243', '103.6',   '33.2',    '112.5', '25',  '37.9')]
dat = pd.DataFrame.from_records(rf, columns=labels).astype(float)

labels = ['MAM 16', 'MAM 17', 'JJAS 16','JJAS 17', 'OND 15','OND 16']
dat = dat[['MAM-16',  'MAM-17',  'JJAS-16', 'JJAS-17', 'OND-15','OND-16']]

axes = dat.plot(kind='bar',rot=0,lw=2, figsize=(10,4), legend=False,
             title='Sample title', subplots=True, layout=(3,2))
colors = plt.cm.jet(np.linspace(0,1,len(dat)))
for ax in axes.flat:
    for i,bar in enumerate(ax.patches):
        bar.set_color(colors[i])
plt.show()


问:
Sequelize: Use query results as table for selectQuery
Is it possible to use the results of a query as a table for another select in sequelize's query generator? Here's the SQL I'm trying to get generated:

```<code>UPDATE target
SET fk1_id = '1'
WHERE id NOT IN
    (SELECT id
    FROM (
        SELECT id
        FROM target
        WHERE fk1_id = 1 AND fk2_id = 2
         ) AS inner_target )
    AND fk1_id IS NULL AND fk2_id = '2' LIMIT 1
</code>```

and I'm trying to accomplish this with:

```<code>const innerSelect =
sequelize.dialect.QueryGenerator.selectQuery('target', {
            attributes: ['fk1_id'],
            where: {
                fk1_id: fk1_id,
                fk2_id: fk2_id,
            },
        }).slice(0, -1);

const selectAs = sequelize.dialect.QueryGenerator.selectQuery(
    sequelize.literal(`${innerSelect}`), {
            attributes: ['id'],
        }).slice(0, -1);
</code>```

however, I get an error saying:

```<code>"message": "Table 'db.undefined' doesn't exist"
"name": "SequelizeDatabaseError"
"code": "ER_NO_SUCH_TABLE"
</code>```

and the inner select is trying to select from undefined

any suggestions would be greatly appreciated!

答: According to that error, you have not created the table you are querying.</p>

Body:
Is it possible to use the results of a query as a table for another select in sequelize's query generator? Here's the SQL I'm trying to get generated:

UPDATE target
SET fk1_id = '1'
WHERE id NOT IN
    (SELECT id
    FROM (
        SELECT id
        FROM target
        WHERE fk1_id = 1 AND fk2_id = 2
         ) AS inner_target )
    AND fk1_id IS NULL AND fk2_id = '2' LIMIT 1

and I'm trying to accomplish this with:

const innerSelect =
sequelize.dialect.QueryGenerator.selectQuery('target', {
            attributes: ['fk1_id'],
            where: {
                fk1_id: fk1_id,
                fk2_id: fk2_id,
            },
        }).slice(0, -1);

const selectAs = sequelize.dialect.QueryGenerator.selectQuery(
    sequelize.literal(`${innerSelect}`), {
            attributes: ['id'],
        }).slice(0, -1);

however, I get an error saying:

"message": "Table 'db.undefined' doesn't exist"
"name": "SequelizeDatabaseError"
"code": "ER_NO_SUCH_TABLE"

and the inner select is trying to select from undefined

any suggestions would be greatly appreciated!


问:
Getting Python variable name or value from memory location?
I have looked around the forums and I can't seem to find an answer (and there might not be one actually) as to whether or not you can get the name of a variable or the value by using its memory location in Python.  In other words, when I declare a = 10 and assign the value 10 to the variable 'a', and then I use the id() function on 'a' I get the location in memory where the value for 'a' is stored.  Is there a way to, say, print the variable name ('a') or the value ('10') by referencing the value that id() returns (either the decimal value or converting the decimal value to hex with the hex() function)?  I tried a few things like print(id(variable-name)) and just print(decimal-value-from-id) and no luck. Any help would be greatly appreciated and thank you in advance!

Cheers!

答:
This is possible with ctypes:

```<code>import ctypes
a = 10
ctypes.cast(id(a), ctypes.py_object).value
#10
</code>```

This will, of course, work if the object is still there.

Body:
This is possible with ctypes:

import ctypes
a = 10
ctypes.cast(id(a), ctypes.py_object).value
#10

This will, of course, work if the object is still there.


问:
Modifying how TTS speaks a string of capital letters
In certain (quantifiable by my program) circumstances I want the tts engine to speak a string of letters as their own names rather than what they spell.

For example, in the square with corners named A, B, C, & D, I want it to speak the name of the line AB as "ay bee". At the moment it says "ab".

Can I do this? And, obviously, if so, how?

答:
As suggested You can add spaces between alphabets and feed the it to TTS.

```<code>String a_z="A B C ...";
</code>```

or if it is coming from some input source then do

```<code>input = "ABCDE".replaceAll("([A-Z])"," $1").trim()
</code>```

where ([A-Z]) mean capture any capital alphabet which is represented by $1

and you can use setSpeechRate to stretch the speed to make it sounds as required.

Body:
As suggested You can add spaces between alphabets and feed the it to TTS.

String a_z="A B C ...";

or if it is coming from some input source then do

input = "ABCDE".replaceAll("([A-Z])"," $1").trim()

where ([A-Z]) mean capture any capital alphabet which is represented by $1

and you can use setSpeechRate to stretch the speed to make it sounds as required.


问:
Large title crash application when view controller is opened for 2nd time in tab bar
I have a table bar root view controller set to navigation view controller with view controller that has only a table view in it.

When I set navigation bar large titles to always or automatic it will crash the app when I open tab 2nd time.

Error message is shown below:

```<code>Assertion failure in -[UITableView _addScrollViewScrollObserver:]*
 Terminating app due to uncaught exception 'NSInternalInconsistencyException',
 reason: 'ERROR: UIScrollView does not support multiple observers implementing _scrollViewWillEndDraggingWithVelocity:targetContentOffset:'
</code>```

I don't have idea how to fix it. Thank you in advance.

sotryboard screenshot

答:
Found it!
Seems to be a bug with more than 1 Navigation controller in the stack.

So when my structure was (From top to bottom):

```<code>UINavigationController
UITabBarController
UINavigationControllers (Different tab items)
</code>```

If I removed to main NavigationController (Top), the exception is gone!
Hope they will fix it soon.

Body:
I have a table bar root view controller set to navigation view controller with view controller that has only a table view in it.

When I set navigation bar large titles to always or automatic it will crash the app when I open tab 2nd time.

Error message is shown below:

Assertion failure in -[UITableView _addScrollViewScrollObserver:]*
 Terminating app due to uncaught exception 'NSInternalInconsistencyException',
 reason: 'ERROR: UIScrollView does not support multiple observers implementing _scrollViewWillEndDraggingWithVelocity:targetContentOffset:'

I don't have idea how to fix it. Thank you in advance.

sotryboard screenshot

Body:
Found it!
Seems to be a bug with more than 1 Navigation controller in the stack.

So when my structure was (From top to bottom):

UINavigationController
UITabBarController
UINavigationControllers (Different tab items)

If I removed to main NavigationController (Top), the exception is gone!
Hope they will fix it soon.


问:
Existing app crashes on startup on iPhone X Simulator
I have an existing app, that crashes on launch, when running on iPhone X Simulator. (Breakpoint stops on the main.m files).
The app runs fine on iPhone 8 simulator, so it has something to with iPhone X.
Also, it has something to do with the status bar, since the stack shows something with [UIStatusbar _prepareForVisualProviderIfNeeded] before the crash.

Do I need to do something with status bar to run this app on iPhone X Simulator?

答:
Found the answer here: All exception break point is stopping for no reason on simulator

TL;DR: Make sure that all fonts that you specify in your Info.plist under Fonts provided by this application are actually in your application bundle.