问:
Android Kotlin error : "return type is 'unit' which is not a subtype of overridden"
I'm trying to pop out an alert box which asks the user if he wants to delete a value from an ArrayList which is displayed in a ListView whenever he attemps to make a long click on one of them

```<code>mainListView.setLongClickable(true)
mainListView.setOnItemLongClickListener(object: AdapterView.OnItemLongClickListener {
        override fun onItemLongClick(parent: AdapterView<*>, view: View, position:Int, id:Long) {
           val alertDialog = AlertDialog.Builder(this@listV)
           alertDialog.setTitle("Would you like to delete this ?")
           alertDialog.setPositiveButton("Yes") { dialog, whichButton -> mobileArray.removeAt(position);listAdapter.notifyDataSetChanged() }
           alertDialog.setNegativeButton("Cancel", { dialog, which ->  })
           alertDialog.create()
           alertDialog.show()}})
</code>```

but there's an error on the OnItemLongClick function which is

return type is 'unit' which is not a subtype of overridden

  public abstract fun onItemLongClick(...): Boolean defined in android.widget.adapterView.OnItemLongClickListener

I'm very confused since I used pretty much the same code for a simple "onItemClick" and it worked fine

答:
The signatures of onItemClick and onItemLongClick differ (which, granted, is an odd inconsistency in the API):

```<code>void onItemClick(AdapterView<?> parent, View view, int position, long id)

boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
</code>```

The latter returns a boolean value indicating whether the event has been consumed by the listener. If this is true, other listeners won't get called for this event.

So what you want to do is something like this:

```<code>override fun onItemLongClick(parent: AdapterView<*>, view: View, position: Int, id: Long): Boolean {
    // alert dialog code
    return true
}
</code>```

Body:
I'm trying to pop out an alert box which asks the user if he wants to delete a value from an ArrayList which is displayed in a ListView whenever he attemps to make a long click on one of them

mainListView.setLongClickable(true)
mainListView.setOnItemLongClickListener(object: AdapterView.OnItemLongClickListener {
        override fun onItemLongClick(parent: AdapterView<*>, view: View, position:Int, id:Long) {
           val alertDialog = AlertDialog.Builder(this@listV)
           alertDialog.setTitle("Would you like to delete this ?")
           alertDialog.setPositiveButton("Yes") { dialog, whichButton -> mobileArray.removeAt(position);listAdapter.notifyDataSetChanged() }
           alertDialog.setNegativeButton("Cancel", { dialog, which ->  })
           alertDialog.create()
           alertDialog.show()}})

but there's an error on the OnItemLongClick function which is

return type is 'unit' which is not a subtype of overridden

  public abstract fun onItemLongClick(...): Boolean defined in android.widget.adapterView.OnItemLongClickListener

I'm very confused since I used pretty much the same code for a simple "onItemClick" and it worked fine

Body:
The signatures of onItemClick and onItemLongClick differ (which, granted, is an odd inconsistency in the API):

void onItemClick(AdapterView<?> parent, View view, int position, long id)

boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)

The latter returns a boolean value indicating whether the event has been consumed by the listener. If this is true, other listeners won't get called for this event.

So what you want to do is something like this:

override fun onItemLongClick(parent: AdapterView<*>, view: View, position: Int, id: Long): Boolean {
    // alert dialog code
    return true
}


来源: stackexchange

问:
Python 2.7 RE Search by condition
When I am using re.search, I have some problem.

For example:

```<code>a = '<span class="chapternum">1 </span>abc，def.</span>'
</code>```

How can I search the number '1'?
Or how to search by matching digit start with ">" and end with writespace?

I tried:

```<code>test = re.search('(^>)(\d+)(\s$)', a)
print test
>> []
</code>```

It is fail to get the number "1"

答:
^ and $ indicate the beginning and the end of the string. If you get rid of them you have your answer:

```<code>>>> test = re.search('(>)(\d+)(\s)', a)
>>> test.groups()
('>', '1', ' ')
</code>```

Not sure that you need the first and last groups though (capturing with parenthesis):

```<code>>>> a = '<span class="chapternum">23 </span>abc，def.</span>'
>>> test = re.search('>(\d+)\s', a)
>>> test.group(1)
'23'
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python 2.7 RE Search by condition

Body:
When I am using re.search, I have some problem.

For example:

a = '1 abc，def.'

How can I search the number '1'?
Or how to search by matching digit start with ">" and end with writespace?

I tried:

test = re.search('(^>)(\d+)(\s$)', a)
print test
>> []

It is fail to get the number "1"

Body:
^ and $ indicate the beginning and the end of the string. If you get rid of them you have your answer:

>>> test = re.search('(>)(\d+)(\s)', a)
>>> test.groups()
('>', '1', ' ')

Not sure that you need the first and last groups though (capturing with parenthesis):

>>> a = '<span class="chapternum">23 </span>abc，def.</span>'
>>> test = re.search('>(\d+)\s', a)
>>> test.group(1)
'23'


问:
Convert base64string to downloadable file using javascript
I want to download the file while clicking on the link.

```<code><a href="javascript:download(375,untitled.png,image/x-png,*base64bytestring*)" >untitled.png</a>
</code>```

javascript code

```<code>function download(id,name,contenttype,filebyte)
{

}
</code>```

答:
I suggest you use download.js library. Include this library and Try below code with image mime type:

```<code><a href="javascript:download(atob('*base64bytestring*'), 'dlText.txt', 'text/plain');" >untitled.txt</a>
</code>```

Body:
I want to download the file while clicking on the link.

untitled.png

javascript code

function download(id,name,contenttype,filebyte)
{

}

Body:
I suggest you use download.js library. Include this library and Try below code with image mime type:

<a href="javascript:download(atob('*base64bytestring*'), 'dlText.txt', 'text/plain');" >untitled.txt</a>


问:
Custom alert dialog is shown different in older Api's
When I run my device on API 23
I get this alert dialog

But On API 23 I got this

I used this code

```<code>final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.alertaialog);

final TextView alertmessage = (TextView)dialog.findViewById(R.id.alertmessage);
final TextView alert = (TextView)dialog.findViewById(R.id.message);
final Button button = (Button) dialog.findViewById(R.id.alertbutton);
</code>```

What should I do?

答:
It may happens default themes behave different in different android Version, You should define themes also while creating Dialog class object like

final Dialog dialog = new Dialog(mContext, android.R.style.Theme_Translucent_NoTitleBar);

Hope it will help you.

Body:
When I run my device on API 23
I get this alert dialog

But On API 23 I got this

I used this code

final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.alertaialog);

final TextView alertmessage = (TextView)dialog.findViewById(R.id.alertmessage);
final TextView alert = (TextView)dialog.findViewById(R.id.message);
final Button button = (Button) dialog.findViewById(R.id.alertbutton);

What should I do?


问:
Explicitly fail a celery task
I want to explicitly fail a task if a condition won't meet. Example:

```<code>@app.task(bind=True, name="task.my_task", max_retries=2)
def my_task(self, filename):
    result = get_result(filename)
    if result is None:
        self.update_state(task_id=self.request.id, state=states.FAILURE, meta="result is None")
        raise Ignore()
    return result
</code>```

Logs say "Task task.my_task[855c1cbc-e894-409f-af29-d70a35d86e34] ignored"

However, this doesn't work. When I look at task.state, it's in PENDING status. flower says my_task state == STARTED (and it gets stuck there).

Am I missing something? How do I fail a celery task?

答:
To fail the task, just say let_it_fail

```<code>@app.task(bind=True, name="task.my_task", max_retries=2)
def my_task(self, filename):
    result = get_result(filename)
    if result is None:
        self.update_state(task_id=self.request.id, state=states.FAILURE, meta="result is None")
        raise let_it_fail
    return result
</code>```

Title: Explicitly fail a celery task

Body:
I want to explicitly fail a task if a condition won't meet. Example:

@app.task(bind=True, name="task.my_task", max_retries=2)
def my_task(self, filename):
    result = get_result(filename)
    if result is None:
        self.update_state(task_id=self.request.id, state=states.FAILURE, meta="result is None")
        raise Ignore()
    return result

Logs say "Task task.my_task[855c1cbc-e894-409f-af29-d70a35d86e34] ignored"

However, this doesn't work. When I look at task.state, it's in PENDING status. flower says my_task state == STARTED (and it gets stuck there).

Am I missing something? How do I fail a celery task?

Body:
To fail the task, just say let_it_fail

@app.task(bind=True, name="task.my_task", max_retries=2)
def my_task(self, filename):
    result = get_result(filename)
    if result is None:
        self.update_state(task_id=self.request.id, state=states.FAILURE, meta="result is None")
        raise let_it_fail
    return result


问:
Ruby on rails number_to_phone helper method
I have the following line in my application,

```<code><%= f.telephone_field number_to_phone(1235551234) , placeHolder: 'Telephone', :class => 'form-control' %>
</code>```

But when I browse the page, I'm consistently getting the following error.

```<code>NoMethodError - undefined method `123-555-1234' for #<User:0x007fcca00ef690>:
</code>```

I have tried that one but it didn't work either.

```<code><%= f.telephone_field ActionView::Helpers::NumberHelper.number_to_phone(1235551234) , placeHolder: 'Telephone', :class => 'form-control' %>
</code>```

I can't see what I'm missing ?

Any suggestions,

Thanks.

答:
NoMethodError - undefined method `123-555-1234' for
  User:0x007fcca00ef690

telephone_field(object_name, method, options = {}) public

Returns a text_field of type “tel”.

telephone_field("user", "phone")

#=><input id="user_phone" name="user[phone]" type="tel" />

The problem is not with number_to_phone helper. All form helpers expect method(attribute of a model)as a second argument. You should pass an attribute of your User model to which you want to save the input. For example lets say your attribute name is phone_number, then write it like below

```<code><%= f.telephone_field :phone_number , placeHolder: 'Telephone', :class => 'form-control' %>
</code>```

And in the view where you are displaying the phone_number, use number_to_phone helper

```<code><%= number_to_phone(@user.phone_number) %>
</code>```

Body:
I have the following line in my application,

<%= f.telephone_field number_to_phone(1235551234) , placeHolder: 'Telephone', :class => 'form-control' %>

But when I browse the page, I'm consistently getting the following error.

NoMethodError - undefined method `123-555-1234' for #<User:0x007fcca00ef690>:

I have tried that one but it didn't work either.

<%= f.telephone_field ActionView::Helpers::NumberHelper.number_to_phone(1235551234) , placeHolder: 'Telephone', :class => 'form-control' %>

I can't see what I'm missing ?

Any suggestions,

Thanks.

Body:
NoMethodError - undefined method `123-555-1234' for
  User:0x007fcca00ef690

telephone_field(object_name, method, options = {}) public

Returns a text_field of type “tel”.

telephone_field("user", "phone")

#=><input id="user_phone" name="user[phone]" type="tel" />

The problem is not with number_to_phone helper. All form helpers expect method(attribute of a model)as a second argument. You should pass an attribute of your User model to which you want to save the input. For example lets say your attribute name is phone_number, then write it like below

<%= f.telephone_field :phone_number , placeHolder: 'Telephone', :class => 'form-control' %>

And in the view where you are displaying the phone_number, use number_to_phone helper

<%= number_to_phone(@user.phone_number) %>


问:
Add reference to .dll asp.net
I have a simple question about adding references to a .NET project. I'm adding reCAPTCHA to a website and i have downloaded the dll.

After setting the reference to the dll i build and run the project and gets this error:

```<code>[ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.]
   System.Reflection.Module._GetTypesInternal(StackCrawlMark& stackMark) +0
   System.Reflection.Assembly.GetTypes() +96
   StarSuite.Core.Settings.GetSingletonInstancesOfBaseType(Type baseType, String staticMethodName, Type returnType) +149

[ApplicationException: Unable to load types from 'Recaptcha, Version=1.0.5.0, Culture=neutral, PublicKeyToken=9afc4d65b28c38c2'. LoaderExceptions: [FileNotFoundException: Could not load file or assembly 'System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.]
]
</code>```

What am i missing, why do i get this error?

答:
File Not Found:

This is you reason - its in the output:

```<code>FileNotFoundException
</code>```

Double check where your reference is pointing to

ContentLicense: CC BY-SA 2.5

Title: Add reference to .dll asp.net

Body:
I have a simple question about adding references to a .NET project. I'm adding reCAPTCHA to a website and i have downloaded the dll.

After setting the reference to the dll i build and run the project and gets this error:

[ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.]
   System.Reflection.Module._GetTypesInternal(StackCrawlMark& stackMark) +0
   System.Reflection.Assembly.GetTypes() +96
   StarSuite.Core.Settings.GetSingletonInstancesOfBaseType(Type baseType, String staticMethodName, Type returnType) +149

[ApplicationException: Unable to load types from 'Recaptcha, Version=1.0.5.0, Culture=neutral, PublicKeyToken=9afc4d65b28c38c2'. LoaderExceptions: [FileNotFoundException: Could not load file or assembly 'System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.]
]

What am i missing, why do i get this error?

Body:
File Not Found:

This is you reason - its in the output:

FileNotFoundException

Double check where your reference is pointing to


问:
How to compress multy files to one zip by logback?
Our project will produce about 100GB logs per day.So we try to use logback to compress these logs to save disk capacity.

But sadly, I can only find way to compress one file each time.

What I want is: hour1.log, hour2.log, hour3.log => zip up to
hour1-3.log.zip

But what I can get with logback is: hour1.log, hour2.log, hour3.log => hour1.log.zip, hour2.log.zip, hour3.log.zip.

The configuration I use is as follows:

```<code><rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
  <fileNamePattern>${catalina.home}/%i.log.gz</fileNamePattern>
  <minIndex>1</minIndex>
  <maxIndex>3</maxIndex>
</rollingPolicy>

<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
  <maxFileSize>10MB</maxFileSize>
</triggeringPolicy>
</code>```

If each log file is 50MB(if each file 1GB, it will hard to open and edit), it means I will have 2000 zip files(totally 100GB) under log path, that would be too many and ridiculous.

So please help me.Is there any tricks or tips, to achieve what I want. Cool as logback shouldn't be such less capibility.

答:
After checking logback's source code, I can tell that, it does not support compress multifiles.In other words, logback can achive "one" log file in two ways, rename this log or zip this single one log.And of cause do some rolling on proper time point.

In one word, logback(1.2.3) does not support compress multi files to one zip file.

Body:
Our project will produce about 100GB logs per day.So we try to use logback to compress these logs to save disk capacity.

But sadly, I can only find way to compress one file each time.

What I want is: hour1.log, hour2.log, hour3.log => zip up to
hour1-3.log.zip

But what I can get with logback is: hour1.log, hour2.log, hour3.log => hour1.log.zip, hour2.log.zip, hour3.log.zip.

The configuration I use is as follows:

<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
  <fileNamePattern>${catalina.home}/%i.log.gz</fileNamePattern>
  <minIndex>1</minIndex>
  <maxIndex>3</maxIndex>
</rollingPolicy>

<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
  <maxFileSize>10MB</maxFileSize>
</triggeringPolicy>

If each log file is 50MB(if each file 1GB, it will hard to open and edit), it means I will have 2000 zip files(totally 100GB) under log path, that would be too many and ridiculous.

So please help me.Is there any tricks or tips, to achieve what I want. Cool as logback shouldn't be such less capibility.


问:
Send email with a template using php
How can I send an email using php then add a template design in the email? I'm using this:

```<code>$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
</code>```

And it works fine! The problem is just how to add a template.

答:
My simple example

template.php

```<code><?php
class Template
{
  function get_contents($templateName, $variables) {
    $template = file_get_contents($templateName);

    foreach($variables as $key => $value)
    {
        $template = str_replace('{{ '.$key.' }}', $value, $template);
    }
    return $template;
  }
}
?>
</code>```

contact-us.tpl

```<code>Name: {{ name }}
Email:  {{ email }}
subject:  {{ subject }}
------messages------
{{ messages }}
---------------------
</code>```

main.php

```<code><?php
include_once 'template.php';

$name = "Your name";
$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From: $from";

$text = Template::get_contents("contact-us.tpl", array('name' => $name, 'email' => $from, 'subject' => $subject, 'messages' => $message));
echo '```';
echo $text;
echo '```';

$mail = @mail($to, $subject, $text, $headers);
if($mail) {
  echo "<p>Mail Sent.</p>";
}
else {
  echo "<p>Mail Fault.</p>";
}
?>
</code>```

Title: Send email with a template using php

Body:
How can I send an email using php then add a template design in the email? I'm using this:

$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";

And it works fine! The problem is just how to add a template.

Body:
My simple example

template.php

<?php
class Template
{
  function get_contents($templateName, $variables) {
    $template = file_get_contents($templateName);

    foreach($variables as $key => $value)
    {
        $template = str_replace('{{ '.$key.' }}', $value, $template);
    }
    return $template;
  }
}
?>

contact-us.tpl

Name: {{ name }}
Email:  {{ email }}
subject:  {{ subject }}
------messages------
{{ messages }}
---------------------

main.php

<?php
include_once 'template.php';

$name = "Your name";
$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From: $from";

$text = Template::get_contents("contact-us.tpl", array('name' => $name, 'email' => $from, 'subject' => $subject, 'messages' => $message));
echo '<pre>';
echo $text;
echo '<pre>';

$mail = @mail($to, $subject, $text, $headers);
if($mail) {
  echo "<p>Mail Sent.</p>";
}
else {
  echo "<p>Mail Fault.</p>";
}
?>


问:
PHP File send mail every time when opened explicitly
I have a contact page which made with the help of PHPMailer. The minimal code is as follows

```<code><form class="form-horizontal" method="POST" action="Mail.php" name="contactForm">
...
</form>
</code>```

This works perfectly fine, but whenever I try to open Mail.php explicitly on the webserver, the webserver sends blank email every time. Here's a screenshot of email whenever I access Mail.php

Below is the minimal code from PHPMailer's Mail.php

```<code>$mail->Subject = $subject;
    $mail->Body    = "<b>From: </b>". $sender. "<br>" ." <b>Name: </b>". $yourName. "<br>". "<b> Message Body </b>" .$message;
    $mail->AltBody = "<b>From: </b>". $sender. "<br>" ." <b>Name: </b>". $yourName. "<br>". "<b> Message Body </b>" .$message;

        if(!$mail->send()) {
            echo 'Message could not be sent.';
            echo 'Mailer Error: ' . $mail->ErrorInfo;
        }
        else {
            echo "Message has been sent....You're being redirected.....";
            }
</code>```

How can I restrict the user to explicitly access Mail.php?

答:
You could add a condition to check, whether the values from the form are filled:</p>

```<code>if (isset($_POST['sender'])) {
    // send mail
}
</code>```

Body:
I have a contact page which made with the help of PHPMailer. The minimal code is as follows

<form class="form-horizontal" method="POST" action="Mail.php" name="contactForm">
...
</form>

This works perfectly fine, but whenever I try to open Mail.php explicitly on the webserver, the webserver sends blank email every time. Here's a screenshot of email whenever I access Mail.php

Below is the minimal code from PHPMailer's Mail.php

$mail->Subject = $subject;
    $mail->Body    = "From: ". $sender. "
" ." Name: ". $yourName. "
". " Message Body " .$message;
    $mail->AltBody = "From: ". $sender. "
" ." Name: ". $yourName. "
". " Message Body " .$message;

        if(!$mail->send()) {
            echo 'Message could not be sent.';
            echo 'Mailer Error: ' . $mail->ErrorInfo;
        }
        else {
            echo "Message has been sent....You're being redirected.....";
            }

How can I restrict the user to explicitly access Mail.php?

Body:
You could add a condition to check, whether the values from the form are filled:

if (isset($_POST['sender'])) {
    // send mail
}


答:
you should check if the request is POST in your php file  for example:

```<code>if(isset($_POST['from'])){
   // send email
}
</code>```

when you try to open Mailer.php explicitly, your request is  GET.

UPDATE:

from is not form!  it is one of your form inputs!  : <input name="from"  type="text"> , you can use another field, like : name or message,  when you try to open Mailer.php  explicitly , none of from or to or name or subject or .... are filled with $_POST so there is no need to check all of them!

it is just enough to check for example to or from :

```<code>if(isset($_POST['to'])){
   // send email
} else {
    die("forbidden! you can not open this file explicitly!")
}
</code>```

Title: PHP File send mail every time when opened explicitly

Body:
you should check if the request is POST in your php file  for example:

if(isset($_POST['from'])){
   // send email
}

when you try to open Mailer.php explicitly, your request is  GET.

UPDATE:

from is not form!  it is one of your form inputs!  : <input name="from"  type="text"> , you can use another field, like : name or message,  when you try to open Mailer.php  explicitly , none of from or to or name or subject or .... are filled with $_POST so there is no need to check all of them!

it is just enough to check for example to or from :

if(isset($_POST['to'])){
   // send email
} else {
    die("forbidden! you can not open this file explicitly!")
}


问:
How to dynamically create and destroy datepicker in materializecss
I want to initialize and destroy datepicker in materializecss. I know how to initialize but unable to find it how to destroy.

I have one textbox and one dropdown.based on dropdown, the textbox type is changed. so when user select dob, I initialized textbox with materializecss datepicker but after that I am not able to change textbox back to its normal mode, I mean where user can insert text or number.

I am using below code to initialize -

```<code>$('#txtDatePicker').pickadate({
                selectMonths: true, // Creates a dropdown to control month
                selectYears: 100 // Creates a dropdown of 15 years to control year
   });
</code>```

答:
A datepicker usually has 3 buttons, however if these buttons are initialized without values ie. today: "" they will not be shown.

```<code>$('.datepicker').pickadate({
   today: '',
   clear: 'Clear selection',
   close: 'Cancel'
});
</code>```

For more information see: http://amsul.ca/pickadate.js/date/#buttons

Body:
I want to initialize and destroy datepicker in materializecss. I know how to initialize but unable to find it how to destroy.

I have one textbox and one dropdown.based on dropdown, the textbox type is changed. so when user select dob, I initialized textbox with materializecss datepicker but after that I am not able to change textbox back to its normal mode, I mean where user can insert text or number.

I am using below code to initialize -

$('#txtDatePicker').pickadate({
                selectMonths: true, // Creates a dropdown to control month
                selectYears: 100 // Creates a dropdown of 15 years to control year
   });

Body:
A datepicker usually has 3 buttons, however if these buttons are initialized without values ie. today: "" they will not be shown.

$('.datepicker').pickadate({
   today: '',
   clear: 'Clear selection',
   close: 'Cancel'
});

For more information see: http://amsul.ca/pickadate.js/date/#buttons


问:
int objective not iterable error
I'm a new one in coding with python, but I had to finish one project work for my school related to Crude Oil scheduling problem.  When I run the code I got an error message

int objective not iterable error.

My code:

```<code>enter code here
#Here my code:
#indeces:
T = [1,2,3,4,5,6]
M = [1,2,3,4]
#Continuous Variables:
for m in M:
    for c in C:
        for t in T:
            VCT[m,c,t] = model.addVar(obj = 0.0, vtype = 'C', name = 'VCT[%s,%s,%s]'%(m,c,t))
for m in M:
    for t in T:
        V[m,t] = model.addVar(obj = 0.0, vtype = 'C' , name = 'V[%s,%s]'%(m,t))
#Constraints:
for m in M:
    for t in T:
        model.addConstr(V[m,t], '=', quicksum(VCT[m,c,t] for c in C)) #28
        model.addConstr(V[m,t], '<=',V_U[m]) #29
        model.addConstr(V[m,t], '>=',V_L[m]) #30
</code>```

答:
Ofcourse, that error makes sense....

There is no "C" array
for c in C: How will this work... ? I dunno what "C" means!!

 So create a array named "C" or remove that if you dont need that.... A elaboration of your code will help..

Title: int objective not iterable error

Body:
I'm a new one in coding with python, but I had to finish one project work for my school related to Crude Oil scheduling problem.  When I run the code I got an error message

int objective not iterable error.

My code:

enter code here
#Here my code:
#indeces:
T = [1,2,3,4,5,6]
M = [1,2,3,4]
#Continuous Variables:
for m in M:
    for c in C:
        for t in T:
            VCT[m,c,t] = model.addVar(obj = 0.0, vtype = 'C', name = 'VCT[%s,%s,%s]'%(m,c,t))
for m in M:
    for t in T:
        V[m,t] = model.addVar(obj = 0.0, vtype = 'C' , name = 'V[%s,%s]'%(m,t))
#Constraints:
for m in M:
    for t in T:
        model.addConstr(V[m,t], '=', quicksum(VCT[m,c,t] for c in C)) #28
        model.addConstr(V[m,t], '<=',V_U[m]) #29
        model.addConstr(V[m,t], '>=',V_L[m]) #30


问:
Binding Combobox SelectedItem by a field's value
Combobox bind to a set of Provinces, Village object has ProvinceID field and i want to bind SelectedItem of Combobox to a Province with Village's ProvinceID.

My code is:

```<code><ComboBox ItemsSource="{Binding ProvincesList}"
          DisplayMemberPath="ProvinceName"
          SelectedValuePath="ProvinceID"
          SelectedValue="{Binding Village.ProvinceID}" />
</code>```

But SelectedItem is anything.

答: Your binding direction is OneWay and BindingEngine of SL can't propagate UI changes to your object's property, hence you must add Mode=TwoWay at end of binding expression.

Body:
Combobox bind to a set of Provinces, Village object has ProvinceID field and i want to bind SelectedItem of Combobox to a Province with Village's ProvinceID.

My code is:

<ComboBox ItemsSource="{Binding ProvincesList}"
          DisplayMemberPath="ProvinceName"
          SelectedValuePath="ProvinceID"
          SelectedValue="{Binding Village.ProvinceID}" />

But SelectedItem is anything.


问:
jhipster 4: How to Update to Own Needs
After generating a new jhipster project with Angular 2+ and creating an entity:

I want to disable that the user can create an instance of my entity. Therefore as a first start I deleted in the file
src/main/webapp/app/entities/book/book.component.html the following html code:

```<code><button class="btn btn-primary float-right create-book" [routerLink]="['/', { outlets: { popup: ['book-new'] } }]">
 <span class="fa fa-plus"></span>
 <span  jhiTranslate="jhipsterApp.book.home.createLabel">Create new Book</span>
</button>
</code>```

But still the button is displayed in the system - probably as it is still visible in target/www/app/main.bundle.js.

What are the proper steps to update the Angular 2+ frontend? Do I miss another generator step?

答:
Doing angular changes have to be done by executing

```<code>npm start
</code>```

This ensures that webpack updates the referring target files.

My error was to start the project just with

```<code>./mvnw
</code>```

Title: jhipster 4: How to Update to Own Needs

Body:
After generating a new jhipster project with Angular 2+ and creating an entity:

I want to disable that the user can create an instance of my entity. Therefore as a first start I deleted in the file
src/main/webapp/app/entities/book/book.component.html the following html code:

<button class="btn btn-primary float-right create-book" [routerLink]="['/', { outlets: { popup: ['book-new'] } }]">

 Create new Book
</button>

But still the button is displayed in the system - probably as it is still visible in target/www/app/main.bundle.js.

What are the proper steps to update the Angular 2+ frontend? Do I miss another generator step?

Body:
Doing angular changes have to be done by executing

npm start

This ensures that webpack updates the referring target files.

My error was to start the project just with

./mvnw


问:
call on function returns undefined on first call
In my controller i am calling this function in my service. idservice.getid()
I am testing it by printing it to console using console.log(idservice.getid())

and it returns undefined the first time, but after that if i call it again it returns the value.

I understand this is a async issue but im not sure how to make this work.

my service is below:

```<code>function idservice (userauth) {

 var id;

  this.getid = function() {
    userauth.currentUser().then(function(user) {
      id = user.id;
    });

    return id
  }
}
</code>```

How can i make it so that on the first call it doesnt return undefined? Is this a async issue?

答:
This's happening because inside userauth currentUser() method you're making http call and response ('user.id') is yet not available. You can return the userauth.currentUser() call inside getid() method & also return id inside its success callback then. So your service method should look like

```<code>function idservice (userauth) {

 var id;

  this.getid = function() {
    return userauth.currentUser().then(function(user) {
              id = user.id;
              return id;
            });

  }
}
</code>```

And inside controller you should handle it like

```<code>idservice.getid().then(function(response){
  $scope.id  = response;
});
</code>```

Here's small example of your requirement: https://plnkr.co/edit/bEjR9e179aRPfJiaQpei?p=preview

Body:
In my controller i am calling this function in my service. idservice.getid()
I am testing it by printing it to console using console.log(idservice.getid())

and it returns undefined the first time, but after that if i call it again it returns the value.

I understand this is a async issue but im not sure how to make this work.

my service is below:

function idservice (userauth) {

 var id;

  this.getid = function() {
    userauth.currentUser().then(function(user) {
      id = user.id;
    });

    return id
  }
}

How can i make it so that on the first call it doesnt return undefined? Is this a async issue?

Body:
This's happening because inside userauth currentUser() method you're making http call and response ('user.id') is yet not available. You can return the userauth.currentUser() call inside getid() method & also return id inside its success callback then. So your service method should look like

function idservice (userauth) {

 var id;

  this.getid = function() {
    return userauth.currentUser().then(function(user) {
              id = user.id;
              return id;
            });

  }
}

And inside controller you should handle it like

idservice.getid().then(function(response){
  $scope.id  = response;
});

Here's small example of your requirement: https://plnkr.co/edit/bEjR9e179aRPfJiaQpei?p=preview


问:
gradle does not work correctly
I was working with Android Studio and i decided to add recyclerView to build.gradle. but after added it and syncing gradle i got this error:

```<code>    Executing tasks: [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies]
</code>```

even i do Rebuild project but in this task also i got same error. for other way i did invalidate caches/Restart but it did not work an still my problem exist.
I turn off instant run but i got same error.
I deleted .gradle folder in my user and still i got this error!!!
how can i pass this problem?

my build.gradle:

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 26
buildToolsVersion "26.0.0"
defaultConfig {
    applicationId "com.example.sayres.mychat"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner  "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),  'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-  core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile('org.eclipse.paho:org.eclipse.paho.android.service:1.0.2') {
    exclude module: 'support-v4'
}
compile('org.eclipse.paho:org.eclipse.paho.android.service:1.0.3-SNAPSHOT') {
    exclude module: 'support-v4'
}
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}
</code>```

Edit:

in the gradle console apeare these lines:

```<code>Error: Some file crunching failed, see logs for details
</code>```

:app:mergeDebugResources FAILED

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:mergeDebugResources'.

Error: Some file crunching failed, see logs for details

Try:
Run with --stacktrace option to get the stack trace. Run with --info or     --debug option to get more log output.

BUILD FAILED

Total time: 3.358 secs

and this is my log: enter link description here

I delete build folder but i got same error. in these folders there is no PNG images.

答:
Try this in gradle, Make sure you clean your project:

```<code> android {
 aaptOptions {
            cruncherEnabled = false
        }
 }
</code>```

Hope this helps.

Title: gradle does not work correctly

Body:
I was working with Android Studio and i decided to add recyclerView to build.gradle. but after added it and syncing gradle i got this error:

    Executing tasks: [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies]

even i do Rebuild project but in this task also i got same error. for other way i did invalidate caches/Restart but it did not work an still my problem exist.
I turn off instant run but i got same error.
I deleted .gradle folder in my user and still i got this error!!!
how can i pass this problem?

my build.gradle:

apply plugin: 'com.android.application'

android {
compileSdkVersion 26
buildToolsVersion "26.0.0"
defaultConfig {
    applicationId "com.example.sayres.mychat"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner  "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),  'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-  core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile('org.eclipse.paho:org.eclipse.paho.android.service:1.0.2') {
    exclude module: 'support-v4'
}
compile('org.eclipse.paho:org.eclipse.paho.android.service:1.0.3-SNAPSHOT') {
    exclude module: 'support-v4'
}
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}

Edit:

in the gradle console apeare these lines:

Error: Some file crunching failed, see logs for details

:app:mergeDebugResources FAILED

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:mergeDebugResources'.

Error: Some file crunching failed, see logs for details

Try:
Run with --stacktrace option to get the stack trace. Run with --info or     --debug option to get more log output.

BUILD FAILED

Total time: 3.358 secs

and this is my log: enter link description here

I delete build folder but i got same error. in these folders there is no PNG images.

Body:
Try this in gradle, Make sure you clean your project:

 android {
 aaptOptions {
            cruncherEnabled = false
        }
 }

Hope this helps.


问:
Swift - Increase speed of a moving Node using SpriteKit
I am working on a game similar to pong, while starting the game I apply impulse to the ball in random direction, which is at the centre of the screen e.g.

```<code>func impulse(){
    let randomNum:UInt32 = arc4random_uniform(200)
    let someInt:Int = Int(randomNum)

    //Ball Impulse
    if someInt<49{
    ball.physicsBody?.applyImpulse(CGVector(dx: ballSpeed+3, dy: ballSpeed-5))
    }else if someInt<99{
        ball.physicsBody?.applyImpulse(CGVector(dx: ballSpeed+5, dy: -ballSpeed+5))
    }else if someInt<149{
        ball.physicsBody?.applyImpulse(CGVector(dx: -ballSpeed-5, dy: -ballSpeed+5))
    }else if someInt<200{
        ball.physicsBody?.applyImpulse(CGVector(dx: -ballSpeed-3, dy: ballSpeed-5))
    }

}
</code>```

Where ballSpeed is the preset speed of ball.
So is there any way I can gradually increase the velocity of ball with duration while it is in motion? As ball will keep on bouncing around the screen so it is difficult to apply force to it using dx and dy.

EDIT -

I am using above method just to assign a random quadrant/direction to ball at start of the game.

Start, when impulse method is implemented e.g.
Game start image

And I want to increase speed of the ball by a predefined unit over time during gameplay e.g.
Gameplay

答:
Ok, here you go! The ball CONSTANTLY gets faster, no matter what!!! Adjust amount to determine how much the ball gains speed each frame.

```<code>class GameScene: SKScene, SKPhysicsContactDelegate {

  let ball = SKShapeNode(circleOfRadius: 20)
  var initialDY = CGFloat(0)
  var initialDX = CGFloat(0)

  override func didMove(to view: SKView) {
    self.physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
    self.physicsWorld.gravity = CGVector.zero

    // Configure ball pb:
    let pb = SKPhysicsBody(circleOfRadius: 20)
    ball.physicsBody = pb
    addChild(ball)

    pb.applyImpulse(CGVector(dx: 10, dy: 10))
  }

  override func update(_ currentTime: TimeInterval) {
    initialDX = abs(ball.physicsBody!.velocity.dx)
    initialDY = abs(ball.physicsBody!.velocity.dy)
  }

  override func didSimulatePhysics() {
    guard let pb = ball.physicsBody else { fatalError() }

    // decrease this to adjust the amount of speed gained each frame :)
    let amount = CGFloat(5)

    // When bouncing off a wall, speed decreases... this corrects that to _increase speed_ off bounces.
    if abs(pb.velocity.dx) < abs(initialDX) {
      if      pb.velocity.dx < 0 { pb.velocity.dx = -initialDX - amount }
      else if pb.velocity.dx > 0 { pb.velocity.dx =  initialDX + amount }
    }

    if abs(pb.velocity.dy) < abs(initialDY) {
      if      pb.velocity.dy < 0 { pb.velocity.dy = -initialDY - amount }
      else if pb.velocity.dy > 0 { pb.velocity.dy =  initialDY + amount }
    }
  }
}
</code>```

you can modify this to only increase speed every 5 seconds with an SKAction.repeatForever(.sequence([.wait(forDuration: TimeInterval, .run( { code } ))) but IMO having it constantly gain speed is a bit more awesome and easier to implement.

Body:
I am working on a game similar to pong, while starting the game I apply impulse to the ball in random direction, which is at the centre of the screen e.g.

func impulse(){
    let randomNum:UInt32 = arc4random_uniform(200)
    let someInt:Int = Int(randomNum)

    //Ball Impulse
    if someInt<49{
    ball.physicsBody?.applyImpulse(CGVector(dx: ballSpeed+3, dy: ballSpeed-5))
    }else if someInt<99{
        ball.physicsBody?.applyImpulse(CGVector(dx: ballSpeed+5, dy: -ballSpeed+5))
    }else if someInt<149{
        ball.physicsBody?.applyImpulse(CGVector(dx: -ballSpeed-5, dy: -ballSpeed+5))
    }else if someInt<200{
        ball.physicsBody?.applyImpulse(CGVector(dx: -ballSpeed-3, dy: ballSpeed-5))
    }

}

Where ballSpeed is the preset speed of ball.
So is there any way I can gradually increase the velocity of ball with duration while it is in motion? As ball will keep on bouncing around the screen so it is difficult to apply force to it using dx and dy.

EDIT -

I am using above method just to assign a random quadrant/direction to ball at start of the game.

Start, when impulse method is implemented e.g.
Game start image

And I want to increase speed of the ball by a predefined unit over time during gameplay e.g.
Gameplay

Body:
Ok, here you go! The ball CONSTANTLY gets faster, no matter what!!! Adjust amount to determine how much the ball gains speed each frame.

class GameScene: SKScene, SKPhysicsContactDelegate {

  let ball = SKShapeNode(circleOfRadius: 20)
  var initialDY = CGFloat(0)
  var initialDX = CGFloat(0)

  override func didMove(to view: SKView) {
    self.physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
    self.physicsWorld.gravity = CGVector.zero

    // Configure ball pb:
    let pb = SKPhysicsBody(circleOfRadius: 20)
    ball.physicsBody = pb
    addChild(ball)

    pb.applyImpulse(CGVector(dx: 10, dy: 10))
  }

  override func update(_ currentTime: TimeInterval) {
    initialDX = abs(ball.physicsBody!.velocity.dx)
    initialDY = abs(ball.physicsBody!.velocity.dy)
  }

  override func didSimulatePhysics() {
    guard let pb = ball.physicsBody else { fatalError() }

    // decrease this to adjust the amount of speed gained each frame :)
    let amount = CGFloat(5)

    // When bouncing off a wall, speed decreases... this corrects that to _increase speed_ off bounces.
    if abs(pb.velocity.dx) < abs(initialDX) {
      if      pb.velocity.dx < 0 { pb.velocity.dx = -initialDX - amount }
      else if pb.velocity.dx > 0 { pb.velocity.dx =  initialDX + amount }
    }

    if abs(pb.velocity.dy) < abs(initialDY) {
      if      pb.velocity.dy < 0 { pb.velocity.dy = -initialDY - amount }
      else if pb.velocity.dy > 0 { pb.velocity.dy =  initialDY + amount }
    }
  }
}

you can modify this to only increase speed every 5 seconds with an SKAction.repeatForever(.sequence([.wait(forDuration: TimeInterval, .run( { code } ))) but IMO having it constantly gain speed is a bit more awesome and easier to implement.


问:
how to change the yapsy plugin default file format?
I want to change the default file format extension of the yapsy plugin that looks like name.yapsy-plugin to simply name.info

I have even found the documentation here http://yapsy.sourceforge.net/PluginFileLocator.html But I am confused how to really implement it.

For now I am just working with the default file format and working well. I just want to make a change in extension. Can anyone make me understand the documentation and thus in the future I can tackle such problems.

```<code>try:
        simplePluginManager = PluginManager()
        simplePluginManager.setPluginPlaces(["plugins/"])
        simplePluginManager.collectPlugins()
        pluginlist = {}

        for plugininfo in simplePluginManager.getAllPlugins():
            print "Running the plugin--", plugininfo.name
            # running the plugins
            pluginlist[plugininfo.name] = plugininfo.plugin_object.run(
                cons.PLUGIN_CONFIG_PATH, outputpath, finallogs, plugininfo.name)
    except Exception as error:
        print "Plugin Configuration Error", error
        traceback.print_exc(error)
</code>```

答:
you need to change

```<code>simplePluginManager = PluginManager()
</code>```

to

```<code>simplePluginManager = PluginManager(plugin_info_ext="info")
</code>```

Body:
I want to change the default file format extension of the yapsy plugin that looks like name.yapsy-plugin to simply name.info

I have even found the documentation here http://yapsy.sourceforge.net/PluginFileLocator.html But I am confused how to really implement it.

For now I am just working with the default file format and working well. I just want to make a change in extension. Can anyone make me understand the documentation and thus in the future I can tackle such problems.

try:
        simplePluginManager = PluginManager()
        simplePluginManager.setPluginPlaces(["plugins/"])
        simplePluginManager.collectPlugins()
        pluginlist = {}

        for plugininfo in simplePluginManager.getAllPlugins():
            print "Running the plugin--", plugininfo.name
            # running the plugins
            pluginlist[plugininfo.name] = plugininfo.plugin_object.run(
                cons.PLUGIN_CONFIG_PATH, outputpath, finallogs, plugininfo.name)
    except Exception as error:
        print "Plugin Configuration Error", error
        traceback.print_exc(error)

Body:
you need to change

simplePluginManager = PluginManager()

to

simplePluginManager = PluginManager(plugin_info_ext="info")


问:
fortran split data in many files and do some processing
I want to split my text file and save it in many files and perform some calculation for every file and get results.
I wrote this code but it does code just in one file.
I glad somebody help me.</p>

```<code>rogram split
  implicit none
  integer:: n1,i,k,j
  parameter (n1=52017)
  real*8::bjd1,bjd(n1),phase(n1),flux(n1),errflux(n1),bjd2,sumation,ave
  open (1,file="myfile.txt")
  do i=1,n1
            read(1,*)  bjd(i),phase(i),flux(i),errflux(i)
            enddo
    close(1)
 bjd1=(bjd(1)+4)
 bjd2=bjd(1)
 j=0

 do k=1,n1
    if (bjd(k).le.bjd1) then
        write(2,*) bjd(k),phase(k),flux(k),errflux(k)
        j=j+1
        else
             write(2,*)'solution'
             bjd1=bjd(k)+4
             sumation=bjd2+bjd(k-1)
             ave=sumation/2
             bjd2=bjd(j)
             write(3,*)j,ave
     end if
 end do
end program
</code>```

答:
I want to strongly discourage you from using unit numbers less than 10. Depending on your compiler and system, some of these numbers are used for stdin, stdout, and errout.

What I'd do is to declare an integer variable, for example out_unit, and then use that in this way:

```<code>integer :: out_unit
...
open(newunit=out_unit, file=...)
...
write(out_unit, *) vars
...
close(out_unit)
</code>```

If you want to cycle between output files, why not use something like this:

```<code>integer :: out_unit
...
open(newunit=out_unit, file=<first file>, ...)
do ...
    ...
    write(out_unit, ...) ...
    if (<cycle trigger>) then
        close(out_unit)
        open(newunit=out_unit, file=...)
    end if
    ...
end do
...
close(out_unit)
</code>```

Edited to add

As @s8129 pointed out, the newunit parameter is fairly recent, and while most Fortran compilers now understand it, not all do. If yours doesn't, you can do it the 'old-fashioned way':

```<code>integer, parameter :: out_unit = 101   ! Some unique number >10
</code>```

And then replace every newunit=out_unit in the open statements with unit=out_unit

Body:
I want to split my text file and save it in many files and perform some calculation for every file and get results.
I wrote this code but it does code just in one file.
I glad somebody help me.

rogram split
  implicit none
  integer:: n1,i,k,j
  parameter (n1=52017)
  real*8::bjd1,bjd(n1),phase(n1),flux(n1),errflux(n1),bjd2,sumation,ave
  open (1,file="myfile.txt")
  do i=1,n1
            read(1,*)  bjd(i),phase(i),flux(i),errflux(i)
            enddo
    close(1)
 bjd1=(bjd(1)+4)
 bjd2=bjd(1)
 j=0

 do k=1,n1
    if (bjd(k).le.bjd1) then
        write(2,*) bjd(k),phase(k),flux(k),errflux(k)
        j=j+1
        else
             write(2,*)'solution'
             bjd1=bjd(k)+4
             sumation=bjd2+bjd(k-1)
             ave=sumation/2
             bjd2=bjd(j)
             write(3,*)j,ave
     end if
 end do
end program

Body:
I want to strongly discourage you from using unit numbers less than 10. Depending on your compiler and system, some of these numbers are used for stdin, stdout, and errout.

What I'd do is to declare an integer variable, for example out_unit, and then use that in this way:

integer :: out_unit
...
open(newunit=out_unit, file=...)
...
write(out_unit, *) vars
...
close(out_unit)

If you want to cycle between output files, why not use something like this:

integer :: out_unit
...
open(newunit=out_unit, file=<first file>, ...)
do ...
    ...
    write(out_unit, ...) ...
    if (<cycle trigger>) then
        close(out_unit)
        open(newunit=out_unit, file=...)
    end if
    ...
end do
...
close(out_unit)

Edited to add

As @s8129 pointed out, the newunit parameter is fairly recent, and while most Fortran compilers now understand it, not all do. If yours doesn't, you can do it the 'old-fashioned way':

integer, parameter :: out_unit = 101   ! Some unique number >10

And then replace every newunit=out_unit in the open statements with unit=out_unit


问:
I'm confused, what's the easiest way to install Ruby 1.9.2 on OS X?
My current version is ruby 1.8.7 (2010-08-16 patchlevel 302) [i686-darwin10]</p>

答:
if you will get error

undefined method `path' for Gem:Module (NoMethodError)

during command

```<code>~/rubygems-1.3.7 $ ruby setup.rb
</code>```

remove ruby and rubygems with command

```<code>sudo autoremove ruby
sudo autoremove rubygem
</code>```

ant try to install all again

Body:
if you will get error

undefined method `path' for Gem:Module (NoMethodError)

during command

~/rubygems-1.3.7 $ ruby setup.rb

remove ruby and rubygems with command

sudo autoremove ruby
sudo autoremove rubygem

ant try to install all again


问:
VisualStudio 2017 Community won't start
IDE crashes on startup, at the splash screen. I have looked into logs and found a bunch of errors:

```<code>    <entry>
    <record>14</record>
    <time>2017/07/09 07:28:50.672</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Could not find ConfigurationChanged timestamp.</description>
    <hr>80070002</hr>
  </entry>
  <entry>
    <record>15</record>
    <time>2017/07/09 07:28:50.672</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Could not find ConfigurationChanged timestamp.</description>
    <hr>80070002</hr>
  </entry>
  <entry>
    <record>16</record>
    <time>2017/07/09 07:28:50.672</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>PkgDefCache flags</description>
    <hr>00003801</hr>
  </entry>
  <entry>
    <record>17</record>
    <time>2017/07/09 07:28:50.672</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Could not find ConfigurationChanged timestamp.</description>
    <hr>80070002</hr>
  </entry>
  <entry>
    <record>18</record>
    <time>2017/07/09 07:28:50.672</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Could not find ConfigurationChanged timestamp.</description>
    <hr>80070002</hr>
  </entry>
</code>```

I tried to reinstall VS, remove all extensions etc but nothing helped me

UPD: it doesn't work with /setup

答:
Check this link. Maybe it will help. I know it's for Visual Studio 2012 but might apply here as well

https://social.msdn.microsoft.com/Forums/en-US/450f2b30-e902-4dad-870a-457b331f932f/could-not-find-configurationchanged-timestamp-error-message-appears-in-activitylogxml-while?forum=vsx

Title: VisualStudio 2017 Community won't start

Body:
IDE crashes on startup, at the splash screen. I have looked into logs and found a bunch of errors:

    <entry>
    <record>14</record>
    <time>2017/07/09 07:28:50.672</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Could not find ConfigurationChanged timestamp.</description>

80070002

  </entry>
  <entry>
    <record>15</record>
    <time>2017/07/09 07:28:50.672</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Could not find ConfigurationChanged timestamp.</description>

80070002

  </entry>
  <entry>
    <record>16</record>
    <time>2017/07/09 07:28:50.672</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>PkgDefCache flags</description>

00003801

  </entry>
  <entry>
    <record>17</record>
    <time>2017/07/09 07:28:50.672</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Could not find ConfigurationChanged timestamp.</description>

80070002

  </entry>
  <entry>
    <record>18</record>
    <time>2017/07/09 07:28:50.672</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Could not find ConfigurationChanged timestamp.</description>

80070002

  </entry>

I tried to reinstall VS, remove all extensions etc but nothing helped me

UPD: it doesn't work with /setup


问:
How Do I check In which place our localStrorage data stored in our system?
I have implemented the login functionality in which i have to set the uname and password into the localStorage API.I want to know which place our data will be stored?

```<code>localStorage.setItem('userName', JSON.stringify(data.uname));
localStorage.getItem('userName');
</code>```

答:
In Chrome, just go to the developer tools by pressing F12, then go to the Application tab and then go to the Local Storage option. After that, you'll see all your local storage of browser there.

Source : StackOverflow

Body:
I have implemented the login functionality in which i have to set the uname and password into the localStorage API.I want to know which place our data will be stored?

localStorage.setItem('userName', JSON.stringify(data.uname));
localStorage.getItem('userName');


问:
Pandas DataFrame mutability
I am pretty new to Panda's Dataframe and it would be highly appreciated if someone can briefly discuss about the mutability of DataFrame to me with the following example:

```<code>d1=pd.date_range('1/1/2016',periods=10,freq='w')
col1=['open','high','low','close']
list1=np.random.rand(10,4)
df1=pd.DataFrame(list1,d1,col1)
</code>```

To my understanding, currently df1 is a reference to a df object.

If I pass df1 or slicing of df1 (e.g. df1.iloc[2:3,1:2]) as an input to a new df, (e.g. df2=pd.DataFrame(df1)), does df2 return a new instance of dataframe or it is still referring to df1 that makes df1 exposed to df2?

Also any other point that I should pay attention to regarding mutability of DataFrame will be very much appreciated.

答:
It will probably share the data, but this style is pretty unclear if you intend to modify df, so I suggest not writing such code. Instead, if you want no copy, just say this:

```<code>df2 = df1.iloc[2:3,1:2]
</code>```

In summary: if you want a reference to existing data, do not call > pd.DataFrame() or any other method at all. If you want an independent copy, call .copy()

I do not agree. Doing the above would still return a reference to the sliced section of the original DataFrame. So, if you make any changes to df2, it will reflect in df1.

Rather the .copy() should be used,

```<code>df2 = df1.iloc[2:3,1:2].copy()
</code>```

Title: Pandas DataFrame mutability

Body:
I am pretty new to Panda's Dataframe and it would be highly appreciated if someone can briefly discuss about the mutability of DataFrame to me with the following example:

d1=pd.date_range('1/1/2016',periods=10,freq='w')
col1=['open','high','low','close']
list1=np.random.rand(10,4)
df1=pd.DataFrame(list1,d1,col1)

To my understanding, currently df1 is a reference to a df object.

If I pass df1 or slicing of df1 (e.g. df1.iloc[2:3,1:2]) as an input to a new df, (e.g. df2=pd.DataFrame(df1)), does df2 return a new instance of dataframe or it is still referring to df1 that makes df1 exposed to df2?

Also any other point that I should pay attention to regarding mutability of DataFrame will be very much appreciated.

Body:
It will probably share the data, but this style is pretty unclear if you intend to modify df, so I suggest not writing such code. Instead, if you want no copy, just say this:

df2 = df1.iloc[2:3,1:2]

In summary: if you want a reference to existing data, do not call > pd.DataFrame() or any other method at all. If you want an independent copy, call .copy()

I do not agree. Doing the above would still return a reference to the sliced section of the original DataFrame. So, if you make any changes to df2, it will reflect in df1.

Rather the .copy() should be used,

df2 = df1.iloc[2:3,1:2].copy()


问:
Applying neural network algorithms on Encrypted data
I have encrypted text dataset and i want to classify it using neural network algorithm. I know that there is a pattern in the encrypted data.
example of my input data :

diss%^ghghE(t dffd$#KL*vb xod@#:n>did ....

My questions is should i treat encrypted data as if its normal text and create vocabulary and transform my data into sequence of indices ?
should i clean my data first from all the special characters ?

What i tried is i cleaned all data from special characters, then created a vocabulary and transform my data into sequences however i am getting a very low accuracy. but my model works well when my data is in natural language.

Any help is appreciated.

答:
By definition, a good encryption algorithm will not allow you to learn anything[*] from the encrypted data.

So, unless you suspect that the encryption algorithm is weak, I suggest you abandon this idea.

[*] apart from the approximate size of the original text


问:
No module named _sysconfigdata_nd
This issue came up for me when I installed Gundo Vim plugin.

I found many posts about No module named _sysconfigdata_nd, but all of them (like this one) refer to a bug in the Ubuntu package, and suggest making a symbolic link like this:

```<code>sudo ln -s /usr/lib/python2.7/plat-*/_sysconfigdata_nd.py /usr/lib/python2.7/
</code>```

This, however, is not applicable for me, as I'm using Python that I compiled myself.

Per suggestion here, I did

```<code>sudo pip install --upgrade virtualenv
</code>```

which created this directory

```<code>.../lib/python2.7/plat-linux2/
</code>```

but there is no _sysconfigdata_nd.py in it.

In my .../lib/python2.7/ I have _sysconfigdata.py but no _sysconfigdata_nd.py.

I've not been able to find any further leads.

答: I was going through the same problem. I installed anaconda python and by mistake removed stock python. Then No module named _sysconfigdata_nd error started coming even though I explicitly pointed /usr/bin/python to anaconda python. I also tried all the methods that you have done but failed. So I downloaded stock python from official source and installed it. Even after installing python and pointing /usr/bin/python to /usr/bin/python2.7 using update-alternatives it started giving me the same error but when I invoke /usr/bin/python it works fine so i created an alias for python like this alias python=/usr/bin/python and added it to my .bashrc file and now it is working fine. I recommend you to try the same. If you want to export the alias python globally. You can add it in /eyc/bin/bash.bashrc which will be applied to all users by default.

Title: No module named _sysconfigdata_nd

Body:
This issue came up for me when I installed Gundo Vim plugin.

I found many posts about No module named _sysconfigdata_nd, but all of them (like this one) refer to a bug in the Ubuntu package, and suggest making a symbolic link like this:

sudo ln -s /usr/lib/python2.7/plat-*/_sysconfigdata_nd.py /usr/lib/python2.7/

This, however, is not applicable for me, as I'm using Python that I compiled myself.

Per suggestion here, I did

sudo pip install --upgrade virtualenv

which created this directory

.../lib/python2.7/plat-linux2/

but there is no _sysconfigdata_nd.py in it.

In my .../lib/python2.7/ I have _sysconfigdata.py but no _sysconfigdata_nd.py.

I've not been able to find any further leads.


问:
Only one match is returned after using (.|\s)*
String:

```<code>Person1(has(1, 1) has(2, 2)
    has(3, 3)
    had(4, 4) had(5, 5))
Person2(has(6, 6) had(7, 7))
</code>```

I'd like to select all contents in has() for Person1, i.e ['1, 1', '2, 2', '3, 3'].

I tried: has\((\d, \d)\)(.|\s)*Person2 with Global pattern flags, but only 1, 1 was returned.

答:
The solution using re.findall() function:

```<code>import re

s = '''
Person1(has(1, 1) has(2, 2)
    has(3, 3)
    had(4, 4) had(5, 5))
Person2(has(6, 6) had(7, 7))'''

has_items = re.findall(r'(?<!Person2\()has\(([^()]+)\)', s)
print(has_items)
</code>```

The output:

```<code>['1, 1', '2, 2', '3, 3']
</code>```

(?<!Person2\() - lookbehind negative assertion, ensures that crucial has substring is not preceded with Person2(

([^()]+) - the 1st captured group containing has items

To grep has items for a certain Person use the following unified approach with extended example:

```<code>def grepPersonItems(s, person):
    person_items = []
    person_group = re.search(r'(' + person + '\(.*?\)\))', s, re.DOTALL)

    if person_group:
        person_items = re.findall(r'has\(([^()]+)\)', person_group.group())
    return person_items

s = '''
Person1(has(1, 1) has(2, 2)
    has(3, 3)
    had(4, 4) had(5, 5))
Person2(has(6, 6) had(7, 7), has(8,8)) Person3(has(2, 6) had(7, 7), has(9, 9))'''

print('Person1: ', person1_items)
print('Person2: ', person2_items)
print('Person3: ', person3_items)

print(person1_items)
print(person2_items)
print(person3_items)
</code>```

The output:

```<code>Person1:  ['1, 1', '2, 2', '3, 3']
Person2:  ['6, 6', '8, 8']
Person3:  ['2, 6', '9, 9']
</code>```

Body:
String:

Person1(has(1, 1) has(2, 2)
    has(3, 3)
    had(4, 4) had(5, 5))
Person2(has(6, 6) had(7, 7))

I'd like to select all contents in has() for Person1, i.e ['1, 1', '2, 2', '3, 3'].

I tried: has\((\d, \d)\)(.|\s)*Person2 with Global pattern flags, but only 1, 1 was returned.

Body:
The solution using re.findall() function:

import re

s = '''
Person1(has(1, 1) has(2, 2)
    has(3, 3)
    had(4, 4) had(5, 5))
Person2(has(6, 6) had(7, 7))'''

has_items = re.findall(r'(?<!Person2\()has\(([^()]+)\)', s)
print(has_items)

The output:

['1, 1', '2, 2', '3, 3']

(?<!Person2\() - lookbehind negative assertion, ensures that crucial has substring is not preceded with Person2(

([^()]+) - the 1st captured group containing has items

To grep has items for a certain Person use the following unified approach with extended example:

def grepPersonItems(s, person):
    person_items = []
    person_group = re.search(r'(' + person + '\(.*?\)\))', s, re.DOTALL)

    if person_group:
        person_items = re.findall(r'has\(([^()]+)\)', person_group.group())
    return person_items

s = '''
Person1(has(1, 1) has(2, 2)
    has(3, 3)
    had(4, 4) had(5, 5))
Person2(has(6, 6) had(7, 7), has(8,8)) Person3(has(2, 6) had(7, 7), has(9, 9))'''

print('Person1: ', person1_items)
print('Person2: ', person2_items)
print('Person3: ', person3_items)

print(person1_items)
print(person2_items)
print(person3_items)

The output:

Person1:  ['1, 1', '2, 2', '3, 3']
Person2:  ['6, 6', '8, 8']
Person3:  ['2, 6', '9, 9']


问:
visual studio 2017 no asp.net templates
I just installed Visual Studio 2017 Community edition.
When I want to make a new project, there is no option to create an ASP.NET application.

What's up with that?

答: Go to Visual Studio Installer , select Community Version Update in the appeared menu select Asp.Net and Install it.

Title: visual studio 2017 no asp.net templates


问:
Setting Shape of View Controllers In Swift UIscrollview
I am trying to create a menu that uses scrollviews to swipe between 5 view controllers that are shaped like a T, my problem is that currently my viewcontrollers are shaped like a + sign. I was wondering  based on the code below how I could set the left and right view controllers to be aligned to form a T shape instead of a + shape. Just to clarify, the code works as such: The snapcontainerviewcontroller sets up a vertical scrollvew view with three view controllers, top bottom and middle, and then this scrollview view is sandwiched in a horizontal scroll view that contains a left and a right viewcontroller.

AppDelegate:

```<code> func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let left = storyboard.instantiateViewController(withIdentifier: "left")
    let middle = storyboard.instantiateViewController(withIdentifier: "middle")
    let right = storyboard.instantiateViewController(withIdentifier: "right")
    let top = storyboard.instantiateViewController(withIdentifier: "top")
    let bottom = storyboard.instantiateViewController(withIdentifier: "bottom")

    let snapContainer = SnapContainerViewController.containerViewWith(left,
                                                                      middleVC: middle,
                                                                      rightVC: right,
                                                                      topVC: top,
                                                                        bottomVC: bottom)

    self.window?.rootViewController = snapContainer
    self.window?.makeKeyAndVisible()
    return true
}`
</code>```

SnapContainerViewController:

```<code>class SnapContainerViewController: UIViewController, UIScrollViewDelegate,UIGestureRecognizerDelegate {

var topVc: UIViewController?
var leftVc: UIViewController!
var middleVc: UIViewController!
var rightVc: UIViewController!
var bottomVc: UIViewController?

var directionLockDisabled: Bool!

var horizontalViews = [UIViewController]()
var veritcalViews = [UIViewController]()

var initialContentOffset = CGPoint() // scrollView initial offset
var middleVertScrollVc: VerticalScrollViewController!
var scrollView: UIScrollView!
var delegate: SnapContainerViewControllerDelegate?

let player = MPMusicPlayerController.applicationMusicPlayer()

class func containerViewWith(_ leftVC: UIViewController,
                             middleVC: UIViewController,
                             rightVC: UIViewController,
                             topVC: UIViewController?=nil,
                             bottomVC: UIViewController?=nil,
                             directionLockDisabled: Bool?=false) -> SnapContainerViewController {
    let container = SnapContainerViewController()

    container.directionLockDisabled = directionLockDisabled

    container.topVc = topVC
    container.leftVc = leftVC
    container.middleVc = middleVC
    container.rightVc = rightVC
    container.bottomVc = bottomVC
    return container
}

override func viewDidLoad() {
    super.viewDidLoad()
    setupVerticalScrollView()
    setupHorizontalScrollView()
    scrollView.delaysContentTouches = false
    scrollView.bounces = false
    //scrollView.canCancelContentTouches = false
    scrollView.isPagingEnabled = true

}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

func setupVerticalScrollView() {
    middleVertScrollVc = VerticalScrollViewController.verticalScrollVcWith(topVc: topVc,
                                                                           middleVc: middleVc,
                                                                           bottomVc: bottomVc)
    delegate = middleVertScrollVc
}

func setupHorizontalScrollView() {
    scrollView = UIScrollView()
    scrollView.isPagingEnabled = true
    scrollView.showsHorizontalScrollIndicator = false
    scrollView.bounces = false

    //self.view.bounds.origin.x
    let view = (
        x: CGFloat(0) ,
        y: CGFloat(0),
        width: self.view.bounds.width,
        height: self.view.bounds.height
    )

    scrollView.frame = CGRect(x: view.x,
                              y: view.y,
                              width: view.width,
                              height: view.height
    )

    self.view.addSubview(scrollView)

    let scrollWidth  = 3 * view.width
    let scrollHeight  = view.height
    scrollView.contentSize = CGSize(width: scrollWidth, height: scrollHeight)

    leftVc.view.frame = CGRect(x: 0,
                               y: 0,
                               width: view.width,
                               height: view.height
    )

    middleVertScrollVc.view.frame = CGRect(x: view.width,
                                           y: 0,
                                           width: view.width,
                                           height: view.height
    )

    rightVc.view.frame = CGRect(x: 2 * view.width,
                                y: 0,
                                width: view.width,
                                height: view.height
    )

    addChildViewController(leftVc)
    addChildViewController(middleVertScrollVc)
    addChildViewController(rightVc)

    scrollView.addSubview(leftVc.view)
    scrollView.addSubview(middleVertScrollVc.view)
    scrollView.addSubview(rightVc.view)

    leftVc.didMove(toParentViewController: self)
    middleVertScrollVc.didMove(toParentViewController: self)
    rightVc.didMove(toParentViewController: self)

    scrollView.contentOffset.x = middleVertScrollVc.view.frame.origin.x
    //scrollView.contentOffset.y = (topVc?.view.frame.origin.y)!
    scrollView.delegate = self
}

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    self.initialContentOffset = scrollView.contentOffset

}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if delegate != nil && !delegate!.outerScrollViewShouldScroll() && !directionLockDisabled {
        let newOffset = CGPoint(x: self.initialContentOffset.x, y: self.initialContentOffset.y)

        // Setting the new offset to the scrollView makes it behave like a proper
        // directional lock, that allows you to scroll in only one direction at any given time
        self.scrollView!.setContentOffset(newOffset, animated:  false)
    }
}

}
</code>```

VerticalScrollViewController:

```<code>class VerticalScrollViewController: UIViewController, SnapContainerViewControllerDelegate {
var topVc: UIViewController!
var middleVc: UIViewController!
var bottomVc: UIViewController!
var scrollView: UIScrollView!

class func verticalScrollVcWith(topVc: UIViewController?=nil, middleVc: UIViewController,bottomVc: UIViewController?=nil) -> VerticalScrollViewController {
    let middleScrollVc = VerticalScrollViewController()

    middleScrollVc.topVc = topVc
    middleScrollVc.middleVc = middleVc
    middleScrollVc.bottomVc = bottomVc

    return middleScrollVc
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view:
    setupScrollView()
    scrollView.isPagingEnabled = true
}

func setupScrollView() {
    scrollView = UIScrollView()
    scrollView.isPagingEnabled = true
    scrollView.showsVerticalScrollIndicator = false
    scrollView.bounces = false
    //scrollView.isScrollEnabled = false

    let view = (
        x: CGFloat(0),
        y: CGFloat(0),
        width: self.view.bounds.width,
        height: self.view.bounds.height
    )

    scrollView.frame = CGRect(x: view.x, y: view.y, width: view.width, height: view.height)
    self.view.addSubview(scrollView)

    let scrollWidth: CGFloat  = view.width
    var scrollHeight: CGFloat

        scrollHeight  = 3 * view.height

        topVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
        middleVc.view.frame = CGRect(x: 0, y: view.height, width: view.width, height: view.height)
        bottomVc.view.frame = CGRect(x: 0, y: 2 * view.height, width: view.width, height: view.height)

        addChildViewController(topVc)
        addChildViewController(middleVc)
        addChildViewController(bottomVc)

        scrollView.addSubview(topVc.view)
        scrollView.addSubview(middleVc.view)
        scrollView.addSubview(bottomVc.view)

        topVc.didMove(toParentViewController: self)
        middleVc.didMove(toParentViewController: self)
        bottomVc.didMove(toParentViewController: self)
        print("1st case!")

        //scrollView.contentOffset.y = middleVc.view.frame.origin.y
        scrollView.contentOffset.y = topVc.view.frame.origin.y

    scrollView.contentSize = CGSize(width: scrollWidth, height: scrollHeight)
    scrollView.delaysContentTouches = false
    //scrollView.canCancelContentTouches = false
}

// MARK: - SnapContainerViewControllerDelegate Methods
/**

 */
func outerScrollViewShouldScroll() -> Bool {

    if scrollView.contentOffset.y < middleVc.view.frame.origin.y || scrollView.contentOffset.y > middleVc.view.frame.origin.y {
        return false
    } else {
        return true
    }

}

}
</code>```

答:
You're outerScrollViewShouldScroll method is not correct. You're only letting it scroll when the contentOffset is equal to the middleVc. You should change to allow scrolling only when contentOffset.y is equal to topVc's origin.y

Replace

```<code>if scrollView.contentOffset.y < middleVc.view.frame.origin.y || scrollView.contentOffset.y > middleVc.view.frame.origin.y {
    return false
} else {
    return true
}
</code>```

With this:

```<code>return scrollView.contentOffset.y == topVc.view.frame.origin.y
</code>```

Body:
I am trying to create a menu that uses scrollviews to swipe between 5 view controllers that are shaped like a T, my problem is that currently my viewcontrollers are shaped like a + sign. I was wondering  based on the code below how I could set the left and right view controllers to be aligned to form a T shape instead of a + shape. Just to clarify, the code works as such: The snapcontainerviewcontroller sets up a vertical scrollvew view with three view controllers, top bottom and middle, and then this scrollview view is sandwiched in a horizontal scroll view that contains a left and a right viewcontroller.

AppDelegate:

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let left = storyboard.instantiateViewController(withIdentifier: "left")
    let middle = storyboard.instantiateViewController(withIdentifier: "middle")
    let right = storyboard.instantiateViewController(withIdentifier: "right")
    let top = storyboard.instantiateViewController(withIdentifier: "top")
    let bottom = storyboard.instantiateViewController(withIdentifier: "bottom")

    let snapContainer = SnapContainerViewController.containerViewWith(left,
                                                                      middleVC: middle,
                                                                      rightVC: right,
                                                                      topVC: top,
                                                                        bottomVC: bottom)

    self.window?.rootViewController = snapContainer
    self.window?.makeKeyAndVisible()
    return true
}`

SnapContainerViewController:

class SnapContainerViewController: UIViewController, UIScrollViewDelegate,UIGestureRecognizerDelegate {

var topVc: UIViewController?
var leftVc: UIViewController!
var middleVc: UIViewController!
var rightVc: UIViewController!
var bottomVc: UIViewController?

var directionLockDisabled: Bool!

var horizontalViews = [UIViewController]()
var veritcalViews = [UIViewController]()

var initialContentOffset = CGPoint() // scrollView initial offset
var middleVertScrollVc: VerticalScrollViewController!
var scrollView: UIScrollView!
var delegate: SnapContainerViewControllerDelegate?

let player = MPMusicPlayerController.applicationMusicPlayer()

class func containerViewWith(_ leftVC: UIViewController,
                             middleVC: UIViewController,
                             rightVC: UIViewController,
                             topVC: UIViewController?=nil,
                             bottomVC: UIViewController?=nil,
                             directionLockDisabled: Bool?=false) -> SnapContainerViewController {
    let container = SnapContainerViewController()

    container.directionLockDisabled = directionLockDisabled

    container.topVc = topVC
    container.leftVc = leftVC
    container.middleVc = middleVC
    container.rightVc = rightVC
    container.bottomVc = bottomVC
    return container
}

override func viewDidLoad() {
    super.viewDidLoad()
    setupVerticalScrollView()
    setupHorizontalScrollView()
    scrollView.delaysContentTouches = false
    scrollView.bounces = false
    //scrollView.canCancelContentTouches = false
    scrollView.isPagingEnabled = true

}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

func setupVerticalScrollView() {
    middleVertScrollVc = VerticalScrollViewController.verticalScrollVcWith(topVc: topVc,
                                                                           middleVc: middleVc,
                                                                           bottomVc: bottomVc)
    delegate = middleVertScrollVc
}

func setupHorizontalScrollView() {
    scrollView = UIScrollView()
    scrollView.isPagingEnabled = true
    scrollView.showsHorizontalScrollIndicator = false
    scrollView.bounces = false

    //self.view.bounds.origin.x
    let view = (
        x: CGFloat(0) ,
        y: CGFloat(0),
        width: self.view.bounds.width,
        height: self.view.bounds.height
    )

    scrollView.frame = CGRect(x: view.x,
                              y: view.y,
                              width: view.width,
                              height: view.height
    )

    self.view.addSubview(scrollView)

    let scrollWidth  = 3 * view.width
    let scrollHeight  = view.height
    scrollView.contentSize = CGSize(width: scrollWidth, height: scrollHeight)

    leftVc.view.frame = CGRect(x: 0,
                               y: 0,
                               width: view.width,
                               height: view.height
    )

    middleVertScrollVc.view.frame = CGRect(x: view.width,
                                           y: 0,
                                           width: view.width,
                                           height: view.height
    )

    rightVc.view.frame = CGRect(x: 2 * view.width,
                                y: 0,
                                width: view.width,
                                height: view.height
    )

    addChildViewController(leftVc)
    addChildViewController(middleVertScrollVc)
    addChildViewController(rightVc)

    scrollView.addSubview(leftVc.view)
    scrollView.addSubview(middleVertScrollVc.view)
    scrollView.addSubview(rightVc.view)

    leftVc.didMove(toParentViewController: self)
    middleVertScrollVc.didMove(toParentViewController: self)
    rightVc.didMove(toParentViewController: self)

    scrollView.contentOffset.x = middleVertScrollVc.view.frame.origin.x
    //scrollView.contentOffset.y = (topVc?.view.frame.origin.y)!
    scrollView.delegate = self
}

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    self.initialContentOffset = scrollView.contentOffset

}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if delegate != nil && !delegate!.outerScrollViewShouldScroll() && !directionLockDisabled {
        let newOffset = CGPoint(x: self.initialContentOffset.x, y: self.initialContentOffset.y)

        // Setting the new offset to the scrollView makes it behave like a proper
        // directional lock, that allows you to scroll in only one direction at any given time
        self.scrollView!.setContentOffset(newOffset, animated:  false)
    }
}

}

VerticalScrollViewController:

class VerticalScrollViewController: UIViewController, SnapContainerViewControllerDelegate {
var topVc: UIViewController!
var middleVc: UIViewController!
var bottomVc: UIViewController!
var scrollView: UIScrollView!

class func verticalScrollVcWith(topVc: UIViewController?=nil, middleVc: UIViewController,bottomVc: UIViewController?=nil) -> VerticalScrollViewController {
    let middleScrollVc = VerticalScrollViewController()

    middleScrollVc.topVc = topVc
    middleScrollVc.middleVc = middleVc
    middleScrollVc.bottomVc = bottomVc

    return middleScrollVc
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view:
    setupScrollView()
    scrollView.isPagingEnabled = true
}

func setupScrollView() {
    scrollView = UIScrollView()
    scrollView.isPagingEnabled = true
    scrollView.showsVerticalScrollIndicator = false
    scrollView.bounces = false
    //scrollView.isScrollEnabled = false

    let view = (
        x: CGFloat(0),
        y: CGFloat(0),
        width: self.view.bounds.width,
        height: self.view.bounds.height
    )

    scrollView.frame = CGRect(x: view.x, y: view.y, width: view.width, height: view.height)
    self.view.addSubview(scrollView)

    let scrollWidth: CGFloat  = view.width
    var scrollHeight: CGFloat

        scrollHeight  = 3 * view.height

        topVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
        middleVc.view.frame = CGRect(x: 0, y: view.height, width: view.width, height: view.height)
        bottomVc.view.frame = CGRect(x: 0, y: 2 * view.height, width: view.width, height: view.height)

        addChildViewController(topVc)
        addChildViewController(middleVc)
        addChildViewController(bottomVc)

        scrollView.addSubview(topVc.view)
        scrollView.addSubview(middleVc.view)
        scrollView.addSubview(bottomVc.view)

        topVc.didMove(toParentViewController: self)
        middleVc.didMove(toParentViewController: self)
        bottomVc.didMove(toParentViewController: self)
        print("1st case!")

        //scrollView.contentOffset.y = middleVc.view.frame.origin.y
        scrollView.contentOffset.y = topVc.view.frame.origin.y

    scrollView.contentSize = CGSize(width: scrollWidth, height: scrollHeight)
    scrollView.delaysContentTouches = false
    //scrollView.canCancelContentTouches = false
}

// MARK: - SnapContainerViewControllerDelegate Methods
/**

 */
func outerScrollViewShouldScroll() -> Bool {

    if scrollView.contentOffset.y < middleVc.view.frame.origin.y || scrollView.contentOffset.y > middleVc.view.frame.origin.y {
        return false
    } else {
        return true
    }

}

}

Body:
You're outerScrollViewShouldScroll method is not correct. You're only letting it scroll when the contentOffset is equal to the middleVc. You should change to allow scrolling only when contentOffset.y is equal to topVc's origin.y

Replace

if scrollView.contentOffset.y < middleVc.view.frame.origin.y || scrollView.contentOffset.y > middleVc.view.frame.origin.y {
    return false
} else {
    return true
}

With this:

return scrollView.contentOffset.y == topVc.view.frame.origin.y