问:
Mac OS X El Capitan - Scrapy/Python ImportError: cannot import name xmlrpc_client
I am trying to use Scrapy on Mac OS X El Capitan. I have zsh installed and I have tried everything that I could find online to fix this issue. I have also looked at Scrapy throws ImportError: cannot import name xmlrpc_client and could not resolve my problem!

Python installed via brew and added "pip install scrapy":

```<code>➜  DriverEBV  which python
/usr/local/bin/python
</code>```

My .zshrc has the following line:

```<code>export PATH=/usr/local/bin:$PATH
export PYTHONPATH="/Library/Python/2.7/site-packages"
</code>```

This is the error I get:

```<code>➜  DriverEBV  scrapy runspider DriverEBV.py
Traceback (most recent call last):
  File "/usr/local/bin/scrapy", line 7, in <module>
    from scrapy.cmdline import execute
  File "/Library/Python/2.7/site-packages/scrapy/__init__.py", line 48, in <module>
    from scrapy.spiders import Spider
  File "/Library/Python/2.7/site-packages/scrapy/spiders/__init__.py", line 10, in <module>
    from scrapy.http import Request
  File "/Library/Python/2.7/site-packages/scrapy/http/__init__.py", line 12, in <module>
    from scrapy.http.request.rpc import XmlRpcRequest
  File "/Library/Python/2.7/site-packages/scrapy/http/request/rpc.py", line 7, in <module>
    from six.moves import xmlrpc_client as xmlrpclib
ImportError: cannot import name xmlrpc_client
</code>```

When I run "pip install scrapy" now this is what I see:

```<code>➜  DriverEBV  pip install scrapy
Requirement already satisfied (use --upgrade to upgrade): scrapy in /Library/Python/2.7/site-packages
Requirement already satisfied (use --upgrade to upgrade): cssselect>=0.9 in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): queuelib in /usr/local/lib/python2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /usr/local/lib/python2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): w3lib>=1.8.0 in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): lxml in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): Twisted>=10.0.0 in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): six>=1.5.2 in /usr/local/lib/python2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): service-identity in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): cryptography>=0.7 in /usr/local/lib/python2.7/site-packages (from pyOpenSSL->scrapy)
Requirement already satisfied (use --upgrade to upgrade): zope.interface>=3.6.0 in /usr/local/lib/python2.7/site-packages (from Twisted>=10.0.0->scrapy)
Requirement already satisfied (use --upgrade to upgrade): characteristic>=14.0.0 in /Library/Python/2.7/site-packages (from service-identity->scrapy)
Requirement already satisfied (use --upgrade to upgrade): pyasn1-modules in /Library/Python/2.7/site-packages (from service-identity->scrapy)
Requirement already satisfied (use --upgrade to upgrade): pyasn1 in /Library/Python/2.7/site-packages (from service-identity->scrapy)
Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/local/lib/python2.7/site-packages (from cryptography>=0.7->pyOpenSSL->scrapy)
Requirement already satisfied (use --upgrade to upgrade): enum34 in /usr/local/lib/python2.7/site-packages (from cryptography>=0.7->pyOpenSSL->scrapy)
Requirement already satisfied (use --upgrade to upgrade): ipaddress in /usr/local/lib/python2.7/site-packages (from cryptography>=0.7->pyOpenSSL->scrapy)
Requirement already satisfied (use --upgrade to upgrade): idna>=2.0 in /usr/local/lib/python2.7/site-packages (from cryptography>=0.7->pyOpenSSL->scrapy)
Requirement already satisfied (use --upgrade to upgrade): cffi>=1.1.0 in /usr/local/lib/python2.7/site-packages (from cryptography>=0.7->pyOpenSSL->scrapy)
Requirement already satisfied (use --upgrade to upgrade): pycparser in /usr/local/lib/python2.7/site-packages (from cffi>=1.1.0->cryptography>=0.7->pyOpenSSL->scrape)
</code>```

Anybody able to help me?

答: Try uninstalling via pip and then reinstall using easy_install command. I had the same trouble with another python module and doing it this way fixed the issue for me on Mac OS X El Capitan.</p>

Body:
I am trying to use Scrapy on Mac OS X El Capitan. I have zsh installed and I have tried everything that I could find online to fix this issue. I have also looked at Scrapy throws ImportError: cannot import name xmlrpc_client and could not resolve my problem!

Python installed via brew and added "pip install scrapy":

➜  DriverEBV  which python
/usr/local/bin/python

My .zshrc has the following line:

export PATH=/usr/local/bin:$PATH
export PYTHONPATH="/Library/Python/2.7/site-packages"

This is the error I get:

➜  DriverEBV  scrapy runspider DriverEBV.py
Traceback (most recent call last):
  File "/usr/local/bin/scrapy", line 7, in <module>
    from scrapy.cmdline import execute
  File "/Library/Python/2.7/site-packages/scrapy/__init__.py", line 48, in <module>
    from scrapy.spiders import Spider
  File "/Library/Python/2.7/site-packages/scrapy/spiders/__init__.py", line 10, in <module>
    from scrapy.http import Request
  File "/Library/Python/2.7/site-packages/scrapy/http/__init__.py", line 12, in <module>
    from scrapy.http.request.rpc import XmlRpcRequest
  File "/Library/Python/2.7/site-packages/scrapy/http/request/rpc.py", line 7, in <module>
    from six.moves import xmlrpc_client as xmlrpclib
ImportError: cannot import name xmlrpc_client

When I run "pip install scrapy" now this is what I see:

➜  DriverEBV  pip install scrapy
Requirement already satisfied (use --upgrade to upgrade): scrapy in /Library/Python/2.7/site-packages
Requirement already satisfied (use --upgrade to upgrade): cssselect>=0.9 in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): queuelib in /usr/local/lib/python2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /usr/local/lib/python2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): w3lib>=1.8.0 in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): lxml in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): Twisted>=10.0.0 in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): six>=1.5.2 in /usr/local/lib/python2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): service-identity in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): cryptography>=0.7 in /usr/local/lib/python2.7/site-packages (from pyOpenSSL->scrapy)
Requirement already satisfied (use --upgrade to upgrade): zope.interface>=3.6.0 in /usr/local/lib/python2.7/site-packages (from Twisted>=10.0.0->scrapy)
Requirement already satisfied (use --upgrade to upgrade): characteristic>=14.0.0 in /Library/Python/2.7/site-packages (from service-identity->scrapy)
Requirement already satisfied (use --upgrade to upgrade): pyasn1-modules in /Library/Python/2.7/site-packages (from service-identity->scrapy)
Requirement already satisfied (use --upgrade to upgrade): pyasn1 in /Library/Python/2.7/site-packages (from service-identity->scrapy)
Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/local/lib/python2.7/site-packages (from cryptography>=0.7->pyOpenSSL->scrapy)
Requirement already satisfied (use --upgrade to upgrade): enum34 in /usr/local/lib/python2.7/site-packages (from cryptography>=0.7->pyOpenSSL->scrapy)
Requirement already satisfied (use --upgrade to upgrade): ipaddress in /usr/local/lib/python2.7/site-packages (from cryptography>=0.7->pyOpenSSL->scrapy)
Requirement already satisfied (use --upgrade to upgrade): idna>=2.0 in /usr/local/lib/python2.7/site-packages (from cryptography>=0.7->pyOpenSSL->scrapy)
Requirement already satisfied (use --upgrade to upgrade): cffi>=1.1.0 in /usr/local/lib/python2.7/site-packages (from cryptography>=0.7->pyOpenSSL->scrapy)
Requirement already satisfied (use --upgrade to upgrade): pycparser in /usr/local/lib/python2.7/site-packages (from cffi>=1.1.0->cryptography>=0.7->pyOpenSSL->scrape)

Anybody able to help me?


来源: stackexchange

问:
How to create a text with a bounding box of a background color using Constrained layout?
What I want to achieve is following result using a constraint layout inside a parent window:

I had seen in a udacity android tutorial that this can be achieved by using an ImageView and TextView with constraints specified for TextView wrt to ImageView.But this was achieved without hard-coding the dimensions of the box (i.e width and height of ImageView was set to 0dp each and ImageView expanded just using constraints.)

I tried following and it is not giving proper results:

```<code>   <ImageView
    android:id="@+id/imageViewTable"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="@color/colorPrimary"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="parent"
    android:layout_marginTop="10dp"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp"/>

<TextView
    android:id="@+id/textViewTest"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView"
    android:textAppearance="@style/TextAppearance.AppCompat.Display1"
    app:layout_constraintLeft_toLeftOf="@id/imageViewTable"
    app:layout_constraintRight_toRightOf="@id/imageViewTable"
    app:layout_constraintTop_toTopOf="@id/imageViewTable"
    app:layout_constraintBottom_toBottomOf="@id/imageViewTable"
    />
</code>```

I know there is a simple way to do it using padding , but I want to know how it can be done like this way (using 0dp imageview)

答:
Extending Tiago's answer, all you need is to remove imageViewTable and change textViewTest in the following way:

```<code><TextView
    android:id="@+id/textViewTest"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView"
    android:textAppearance="@style/TextAppearance.AppCompat.Display1"
    android:padding="16dp"
    android:background="@color/colorPrimary"
    />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What I want to achieve is following result using a constraint layout inside a parent window:

I had seen in a udacity android tutorial that this can be achieved by using an ImageView and TextView with constraints specified for TextView wrt to ImageView.But this was achieved without hard-coding the dimensions of the box (i.e width and height of ImageView was set to 0dp each and ImageView expanded just using constraints.)

I tried following and it is not giving proper results:

   <ImageView
    android:id="@+id/imageViewTable"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="@color/colorPrimary"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="parent"
    android:layout_marginTop="10dp"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp"/>

<TextView
    android:id="@+id/textViewTest"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView"
    android:textAppearance="@style/TextAppearance.AppCompat.Display1"
    app:layout_constraintLeft_toLeftOf="@id/imageViewTable"
    app:layout_constraintRight_toRightOf="@id/imageViewTable"
    app:layout_constraintTop_toTopOf="@id/imageViewTable"
    app:layout_constraintBottom_toBottomOf="@id/imageViewTable"
    />

I know there is a simple way to do it using padding , but I want to know how it can be done like this way (using 0dp imageview)

Body:
Extending Tiago's answer, all you need is to remove imageViewTable and change textViewTest in the following way:

<TextView
    android:id="@+id/textViewTest"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView"
    android:textAppearance="@style/TextAppearance.AppCompat.Display1"
    android:padding="16dp"
    android:background="@color/colorPrimary"
    />


问:
How to make automatic grader with Python3
I'm a beginner for coding.
I'm struggling to make student grader which each student names would be corresponded to each grade averages and show total average score among students.
This is my code :

```<code>Ken = [5,8,9]
Hiro = [10,11,20]
Nick = [20,20,20]

list1 = [Ken,Hiro,Nick]

total_average = 0
for j in list1:
   x = 0
   count = 0
   for i in j:
       x += i
       count += 1

   average = x / count
   print (round(average,2))
   total_average += average

final_average = total_average / len(list1)
print (round(final_average,2))
</code>```

and result is :

```<code>7.33
13.67
20.0
13.67
</code>```

However, I actually want to make code which returns like :

```<code>13.67, {'Ken': 13.67, 'Hiro': 20.0, 'Nick': 13.67}
</code>```

How could I express like this ?

It would be greatly appreciated if you could explain the details !!

答:
I would suggest another approach altogether. First, you store your names and grades in a dictionary:

```<code>grades = {'Ken': [5,8,9], 'Hiro': [10,11,20], 'Nick': [20,20,20]}
</code>```

Then, you loop over the dictionary and compute the average for each student and prepare to compute the global average:

```<code>averages = {}
sum_of_grades, number_of_grades = 0, 0
for name, marks in grades.items():
    averages[name] = sum(marks) / len(marks) # simple arithmetic average
    sum_of_grades += sum(marks)
    number_of_grades += len(marks)
</code>```

Finally, you compute the global average:

```<code>final_average = sum_of_grades / number_of_grades
</code>```

Here is the complete code, where the computations are encapsulated in a function:

```<code>grades = {'Ken': [5,8,9], 'Hiro': [10,11,20], 'Nick': [20,20,20]}

def compute_averages(grades):
    averages = {}
    sum_of_grades, number_of_grades = 0, 0
    for name, marks in grades.items():
        averages[name] = sum(marks) / len(marks)
        sum_of_grades += sum(marks)
        number_of_grades += len(marks)
    final_average = sum_of_grades / number_of_grades

    return averages, final_average

averages, final_average = compute_averages(grades)
for name, avg in averages.items():
    print(name, round(avg, 2))
print('Final average', round(final_average, 2))
</code>```

Body:
I'm a beginner for coding.
I'm struggling to make student grader which each student names would be corresponded to each grade averages and show total average score among students.
This is my code :

Ken = [5,8,9]
Hiro = [10,11,20]
Nick = [20,20,20]

list1 = [Ken,Hiro,Nick]

total_average = 0
for j in list1:
   x = 0
   count = 0
   for i in j:
       x += i
       count += 1

   average = x / count
   print (round(average,2))
   total_average += average

final_average = total_average / len(list1)
print (round(final_average,2))

and result is :

7.33
13.67
20.0
13.67

However, I actually want to make code which returns like :

13.67, {'Ken': 13.67, 'Hiro': 20.0, 'Nick': 13.67}

How could I express like this ?

It would be greatly appreciated if you could explain the details !!

Body:
I would suggest another approach altogether. First, you store your names and grades in a dictionary:

grades = {'Ken': [5,8,9], 'Hiro': [10,11,20], 'Nick': [20,20,20]}

Then, you loop over the dictionary and compute the average for each student and prepare to compute the global average:

averages = {}
sum_of_grades, number_of_grades = 0, 0
for name, marks in grades.items():
    averages[name] = sum(marks) / len(marks) # simple arithmetic average
    sum_of_grades += sum(marks)
    number_of_grades += len(marks)

Finally, you compute the global average:

final_average = sum_of_grades / number_of_grades

Here is the complete code, where the computations are encapsulated in a function:

grades = {'Ken': [5,8,9], 'Hiro': [10,11,20], 'Nick': [20,20,20]}

def compute_averages(grades):
    averages = {}
    sum_of_grades, number_of_grades = 0, 0
    for name, marks in grades.items():
        averages[name] = sum(marks) / len(marks)
        sum_of_grades += sum(marks)
        number_of_grades += len(marks)
    final_average = sum_of_grades / number_of_grades

    return averages, final_average

averages, final_average = compute_averages(grades)
for name, avg in averages.items():
    print(name, round(avg, 2))
print('Final average', round(final_average, 2))


问:
.py files opens up in a text editor when run from cmd
Whenever I try to run a .py file from cmd it opens up in a text editor(np++). I'm trying to run the following:

```<code>django-admin.py startproject testprj
</code>```

Even if I run 'setup.py install'

答:
You need to change the file association so that .py files open with Python executable, typically located in C:\Python<version>\ and not Notepad++

Changing this should be easy, but here is how to do it.

Also, read here on to set the environment path so that the Python executable is found without you having to navigate to C:\Python2.6.

ContentLicense: CC BY-SA 2.5

Body:
Whenever I try to run a .py file from cmd it opens up in a text editor(np++). I'm trying to run the following:

django-admin.py startproject testprj

Even if I run 'setup.py install'

ContentLicense: CC BY-SA 4.0


问:
Android studio if statement condition met but program won't enter it
So I'm trying to implement a simple class in android studio that takes user input in the form of a spinner and changes the colour of the text accordingly. However, even though the condition has been met, as can be seen by the debugging line, the program will not execute the contents of the if statement.
debugging line</p>

```<code>'import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Colour extends AppCompatActivity {

TextView tv;
Spinner mySpinner;
ArrayAdapter<CharSequence> adapter;
public static final String EXTRA_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_colour);
    Intent intent = getIntent();
    String messageText = intent.getStringExtra(EXTRA_MESSAGE);
    tv = (TextView)findViewById(R.id.message);
    tv.setText(messageText);
    mySpinner = (Spinner) findViewById(R.id.spinner);
    adapter = ArrayAdapter.createFromResource(this,R.array.colours,android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mySpinner.setAdapter(adapter);
    mySpinner.setOnItemSelectedListener(new     AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getBaseContext(), parent.getItemIdAtPosition(position)+ " selected",Toast.LENGTH_LONG).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

}

public void change(View v){

    String text = mySpinner.getSelectedItem().toString();

    if(text == "Red"){
        tv.setTextColor(Color.RED);
    }
    if(text == "Blue"){
        tv.setTextColor(Color.BLUE);
    }
    if(text == "Green"){
        tv.setTextColor(Color.GREEN);
    }
}'

 '<TextView
    android:textColor="#000000"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/message" />

<Spinner
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/colours"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="16dp"
    android:id="@+id/spinner" />

<Button
    android:text="HOME"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:onClick="home"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="52dp" />

<Button
    android:text="changeColour"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button4"
    android:layout_above="@+id/button"
    android:layout_alignStart="@+id/button"
    android:layout_marginBottom="101dp"
    android:onClick="change" />'
</code>```

答:
answer would be

if(text.equals("Red")) etc

because a text is an object of type String it is not a primitive type

primitive type can be compared using == but not a reference type

Body:
So I'm trying to implement a simple class in android studio that takes user input in the form of a spinner and changes the colour of the text accordingly. However, even though the condition has been met, as can be seen by the debugging line, the program will not execute the contents of the if statement.
debugging line

'import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Colour extends AppCompatActivity {

TextView tv;
Spinner mySpinner;
ArrayAdapter<CharSequence> adapter;
public static final String EXTRA_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_colour);
    Intent intent = getIntent();
    String messageText = intent.getStringExtra(EXTRA_MESSAGE);
    tv = (TextView)findViewById(R.id.message);
    tv.setText(messageText);
    mySpinner = (Spinner) findViewById(R.id.spinner);
    adapter = ArrayAdapter.createFromResource(this,R.array.colours,android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mySpinner.setAdapter(adapter);
    mySpinner.setOnItemSelectedListener(new     AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getBaseContext(), parent.getItemIdAtPosition(position)+ " selected",Toast.LENGTH_LONG).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

}

public void change(View v){

    String text = mySpinner.getSelectedItem().toString();

    if(text == "Red"){
        tv.setTextColor(Color.RED);
    }
    if(text == "Blue"){
        tv.setTextColor(Color.BLUE);
    }
    if(text == "Green"){
        tv.setTextColor(Color.GREEN);
    }
}'

 '<TextView
    android:textColor="#000000"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/message" />

<Spinner
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/colours"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="16dp"
    android:id="@+id/spinner" />

<Button
    android:text="HOME"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:onClick="home"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="52dp" />

<Button
    android:text="changeColour"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button4"
    android:layout_above="@+id/button"
    android:layout_alignStart="@+id/button"
    android:layout_marginBottom="101dp"
    android:onClick="change" />'


问:
Codeigniter file upload code not working
Controller Code:

```<code>if(isset($_FILES['imageupload']) && $_FILES['imageupload']['size'] > 0){
    echo 'inside if';
    if ( ! $this->upload->do_upload('imageupload'))
    {
    echo 'inside if';
    $error = array('error' => $this->upload->display_errors());
    }
    else
    {
    echo 'inside else';
    $upload_data = $this->upload->data();
    $file_name[] = $upload_data['file_name'];
    }
}
</code>```

View Code:

```<code><input type="file" class="default" id="imageupload" name="imageupload">
</code>```

ERROR: Call to a member function do_upload() on a non-object

Hoow can I resolve this error please help me.

答:
The error indicates that the upload library is not loaded. You need to load the upload library somewhere and in the constructor of the controller is one possible choice. Add the following to the controller code.

```<code>function __construct()
{
  parent::__construct();
  $this->load->library('upload');
}
</code>```

The other place to load this library is in application/config/autoload.php using the $autoload['libraries'] item.

```<code>$autoload['libraries'] = array('upload');
</code>```

Other libraries can be loaded at the same time. See the comments in autoload.php for more details.

Body:
Controller Code:

if(isset($_FILES['imageupload']) && $_FILES['imageupload']['size'] > 0){
    echo 'inside if';
    if ( ! $this->upload->do_upload('imageupload'))
    {
    echo 'inside if';
    $error = array('error' => $this->upload->display_errors());
    }
    else
    {
    echo 'inside else';
    $upload_data = $this->upload->data();
    $file_name[] = $upload_data['file_name'];
    }
}

View Code:

<input type="file" class="default" id="imageupload" name="imageupload">

ERROR: Call to a member function do_upload() on a non-object

Hoow can I resolve this error please help me.

Body:
The error indicates that the upload library is not loaded. You need to load the upload library somewhere and in the constructor of the controller is one possible choice. Add the following to the controller code.

function __construct()
{
  parent::__construct();
  $this->load->library('upload');
}

The other place to load this library is in application/config/autoload.php using the $autoload['libraries'] item.

$autoload['libraries'] = array('upload');

Other libraries can be loaded at the same time. See the comments in autoload.php for more details.


问:
Subtract one circle from another in SVG
I'm trying to find a way to subtract one shape from another in SVG, creating a hole in the middle or a bite out of the side of it. Kind of like a clipping path, but instead of showing the intersection, I want to show one of the parts outside the intersection. One solution involved using Adobe Flex, but I did not know how to implement it properly. I understand that there is a way to do this in Inkscape using boolean path operations, but I want to keep the circle elements the way they are instead of changing them into path elements.</p>

```<code><defs>
    <subtractPath id="hole">
        <circle r="50" cx="100" cy="100" />
    </subtractPath>
</defs>
<circle id="donut" r="100" cx="100" cy="100" subtract-path="url(#hole)" />
</code>```

答:
Two answers suggest to (1) use a <mask> or (2) use the “fill-rule=evenodd” attribute to subtract a shape B from a shape A (A ∖ B).

Both suggested answers solve the “hole in the middle” (B ⊆ A) part of the question but only the mask approach is a reasonable solution for the “bite out of the side” part (B ⊈ A). Using the evenodd fill-rule means the two shapes are treated equally, so the part of the second shape that does not intersect the first one will be part of the result. In order to bite something out of a shape the “biting” shape would have to share part of its border with the bitten shape. This might be cumbersome to achieve in practice.

An example: In order to subtract a circle from another circle you would have to create a “biting” shape that is the intersection of two circles.

The mask approach is much more universal.

Title: Subtract one circle from another in SVG

Body:
I'm trying to find a way to subtract one shape from another in SVG, creating a hole in the middle or a bite out of the side of it. Kind of like a clipping path, but instead of showing the intersection, I want to show one of the parts outside the intersection. One solution involved using Adobe Flex, but I did not know how to implement it properly. I understand that there is a way to do this in Inkscape using boolean path operations, but I want to keep the circle elements the way they are instead of changing them into path elements.

<defs>
    <subtractPath id="hole">
        <circle r="50" cx="100" cy="100" />
    </subtractPath>
</defs>
<circle id="donut" r="100" cx="100" cy="100" subtract-path="url(#hole)" />


问:
How to delete quotation marks from a text file using batch file?
I am trying to edit out the quotation marks that have been inputed into a text file using .bat.

```<code>echo %name%>./User_Records/%username%.txt
</code>```

in the text file it is saving as

```<code>"Firstname Lastname"
</code>```

I am trying to add to the batch file so that it will edit the *.txt file and delete the quotation marks if they are saved in that text file.

Can anyone help me?

I have been trying to do this for weeks. I want the output to look like

```<code>Firstname Lastname
</code>```

答:
If the name read from text file is assigned to environment variable name using set name="..." syntax, then this is the cause of the double quotes in output string.

It makes a big difference if string assigned to environment variable is enclosed in double quotes or the entire parameter string of command SET. Read answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line? to get knowledge about the big difference between using set "variable=string" versus set variable="string".

But it is of course possible to remove all double quotes from string assigned currently to environment variable name by using a string substitution:

```<code>set "name=%name:"=%"
</code>```

All occurrences of " in string of name are replaced by an empty string and resulting string is assigned again to environment variable name.

But be aware that this command line

```<code>echo %name%>"./User_Records/%username%.txt"
</code>```

could result in an unwanted behavior, for example if the name assigned to environment variable name is C&A. The ampersand found by Windows command interpreter after expanding environment variable name and before execution of command ECHO is interpreted now as AND operator and not anymore as literal character to output by ECHO.

One solution is using delayed expansion, for example:

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem Environment variable name is defined with delayed expansion disabled
rem making it possible to assign an exclamation mark as literal character
rem without the need to escape it as it would be necessary when delayed
rem expansion would be enabled already here at this time.

set "name=C&A!"

rem Enable delayed expansion which results in pushing on stack current
rem state of command extensions and of delayed expansion, the current
rem directory path and the pointer to current environment variables list
rem before creating a copy of all environment variables being used further.

setlocal EnableDelayedExpansion

rem Output the value of environment variable name using delayed expansion
rem with redirection into a text file being named like the currently used
rem user account name which of course can contain a space character or
rem other characters requiring enclosed file name with relative path in
rem double quotes.

echo !name!>".\User_Records\%username%.txt"

rem Delete all environment variables, restore pointer to previous set of
rem environment variables, restore current working directory from stack
rem restore states of command extension and delayed expansion from stack.
endlocal

rem Explicitly call ENDLOCAL once again for initial SETLOCAL command.
rem That would not be necessary because Windows command interpreter
rem runs implicitly ENDLOCAL for each local environment still being
rem pushed on stack.

endlocal
</code>```

An alternate solution is using command FOR for an implicit delayed expansion:

```<code>@echo off
set "name=C&A!"
set "name=%name:"=%"
for /F "delims=" %%I in ("%name%") do echo %%I>".\User_Records\%username%.txt"
set "name=
</code>```

See also the answers on Batch: Auto escape special characters.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

endlocal /?

for /?

set /?

setlocal /?

Read also the Microsoft article about Using Command Redirection Operators.

Body:
I am trying to edit out the quotation marks that have been inputed into a text file using .bat.

echo %name%>./User_Records/%username%.txt

in the text file it is saving as

"Firstname Lastname"

I am trying to add to the batch file so that it will edit the *.txt file and delete the quotation marks if they are saved in that text file.

Can anyone help me?

I have been trying to do this for weeks. I want the output to look like

Firstname Lastname

Body:
If the name read from text file is assigned to environment variable name using set name="..." syntax, then this is the cause of the double quotes in output string.

It makes a big difference if string assigned to environment variable is enclosed in double quotes or the entire parameter string of command SET. Read answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line? to get knowledge about the big difference between using set "variable=string" versus set variable="string".

But it is of course possible to remove all double quotes from string assigned currently to environment variable name by using a string substitution:

set "name=%name:"=%"

All occurrences of " in string of name are replaced by an empty string and resulting string is assigned again to environment variable name.

But be aware that this command line

echo %name%>"./User_Records/%username%.txt"

could result in an unwanted behavior, for example if the name assigned to environment variable name is C&A. The ampersand found by Windows command interpreter after expanding environment variable name and before execution of command ECHO is interpreted now as AND operator and not anymore as literal character to output by ECHO.

One solution is using delayed expansion, for example:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem Environment variable name is defined with delayed expansion disabled
rem making it possible to assign an exclamation mark as literal character
rem without the need to escape it as it would be necessary when delayed
rem expansion would be enabled already here at this time.

set "name=C&A!"

rem Enable delayed expansion which results in pushing on stack current
rem state of command extensions and of delayed expansion, the current
rem directory path and the pointer to current environment variables list
rem before creating a copy of all environment variables being used further.

setlocal EnableDelayedExpansion

rem Output the value of environment variable name using delayed expansion
rem with redirection into a text file being named like the currently used
rem user account name which of course can contain a space character or
rem other characters requiring enclosed file name with relative path in
rem double quotes.

echo !name!>".\User_Records\%username%.txt"

rem Delete all environment variables, restore pointer to previous set of
rem environment variables, restore current working directory from stack
rem restore states of command extension and delayed expansion from stack.
endlocal

rem Explicitly call ENDLOCAL once again for initial SETLOCAL command.
rem That would not be necessary because Windows command interpreter
rem runs implicitly ENDLOCAL for each local environment still being
rem pushed on stack.

endlocal

An alternate solution is using command FOR for an implicit delayed expansion:

@echo off
set "name=C&A!"
set "name=%name:"=%"
for /F "delims=" %%I in ("%name%") do echo %%I>".\User_Records\%username%.txt"
set "name=

See also the answers on Batch: Auto escape special characters.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

endlocal /?

for /?

set /?

setlocal /?

Read also the Microsoft article about Using Command Redirection Operators.


问:
Python. Cannot make a request to simple site api. Flask and requests
I am trying to create simple API for my site. I created the route with flask:

```<code>@api.route('/api/rate&message_id=<message_id>&performer=<performer_login>', methods=['POST'])
def api_rate_msg(message_id, performer_login):
    print("RATE API ", message_id, ' ', performer_id)
    return 400
</code>```

print(...) function don't execute...

I use flask-socketio to communicate between client and server.

I send json from client and process it with:

```<code>@socket.on('rate')
def handle_rate(data):
    print(data)
    payload = {'message_id':data['message_id'], 'performer':data['performer']}
    r = requests.post('/api/rate', params=payload)
    print (r.status_code)
</code>```

Note, that data variable is sending from client and is correct(I've checked it).

print(r.status_code) don't exec too...

Where I'm wrong?
Please, sorry for my bad english :(

This api function must increase rate of message, which stored in mongodb, if interesting.

答:
Don't put &message_id=<message_id>&performer=<performer_login> in your route string. Instead, get these arguments from request.args.

Try it:

```<code>from flask import request

...

@api.route('/api/rate', methods=['POST'])
def api_rate_msg():
    print(request.args)
    return ''
</code>```

I've tested it with httpie:

```<code>$ http -v POST :5000/api/rate message_id==123 performer_login==foo
POST /api/rate?message_id=123&performer_login=foo HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 0
Host: localhost:5000
User-Agent: HTTPie/0.9.8

HTTP/1.0 200 OK
Content-Length: 0
Content-Type: text/html; charset=utf-8
Date: Sun, 02 Apr 2017 13:54:40 GMT
Server: Werkzeug/0.11.11 Python/2.7.13
</code>```

And from flask's log:

```<code>ImmutableMultiDict([('message_id', u'123'), ('performer_login', u'foo')])
127.0.0.1 - - [02/Apr/2017 22:54:40] "POST /api/rate?message_id=123&performer_login=foo HTTP/1.1" 200 -
</code>```

Body:
I am trying to create simple API for my site. I created the route with flask:

@api.route('/api/rate&message_id=<message_id>&performer=<performer_login>', methods=['POST'])
def api_rate_msg(message_id, performer_login):
    print("RATE API ", message_id, ' ', performer_id)
    return 400

print(...) function don't execute...

I use flask-socketio to communicate between client and server.

I send json from client and process it with:

@socket.on('rate')
def handle_rate(data):
    print(data)
    payload = {'message_id':data['message_id'], 'performer':data['performer']}
    r = requests.post('/api/rate', params=payload)
    print (r.status_code)

Note, that data variable is sending from client and is correct(I've checked it).

print(r.status_code) don't exec too...

Where I'm wrong?
Please, sorry for my bad english :(

This api function must increase rate of message, which stored in mongodb, if interesting.

Body:
Don't put &message_id=<message_id>&performer=<performer_login> in your route string. Instead, get these arguments from request.args.

Try it:

from flask import request

...

@api.route('/api/rate', methods=['POST'])
def api_rate_msg():
    print(request.args)
    return ''

I've tested it with httpie:

$ http -v POST :5000/api/rate message_id==123 performer_login==foo
POST /api/rate?message_id=123&performer_login=foo HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 0
Host: localhost:5000
User-Agent: HTTPie/0.9.8

HTTP/1.0 200 OK
Content-Length: 0
Content-Type: text/html; charset=utf-8
Date: Sun, 02 Apr 2017 13:54:40 GMT
Server: Werkzeug/0.11.11 Python/2.7.13

And from flask's log:

ImmutableMultiDict([('message_id', u'123'), ('performer_login', u'foo')])
127.0.0.1 - - [02/Apr/2017 22:54:40] "POST /api/rate?message_id=123&performer_login=foo HTTP/1.1" 200 -


问:
MySQL Workbench with Heroku
I have made an application with CodeIgniter with a MySQL database. I'm using Heroku to deploy my application, and have done so successfully. However, I'm having problems with using my database on Heroku. Locally I'm using XAMPP and phpmyadmin for all database work.

In Heroku, I've used a clearDB add on to support MySQL and have gotten all necessary credentials in the format:

mysql://DB_USERNAME:DB_PASSWORD@BD_HOST/DB_DATABASE?reconnect=true

I've used MySQL Workbench and have created a database using the above supplied host name, username, password and have successfully imported the tables, columns and data from my already existing database.

Now, I'm unsure on how to proceed. Do I export my database from Workbench? or what am I supposed to do to be able to use my database on Heroku.

Any and all help appreciated. Thanks.

P.S. please don't tell me to use Postgres

答: Update: So I figued I didn't have to do anything, once the databse is configured on Workbench, all I had to do was refresh my heroku web page and it works.</p>

Title: MySQL Workbench with Heroku


问:
Order by in union clause
Could any one please help me I have been working on a query containing unions n joins of multiple tables.. I have got the desired results but I want to get these results in some specific order so the whole result is being orderd according to one column.
Here is the snippet of code I am working on:</p>

```<code>select name, age
from UserUni
order by age
union all
select age, Name
from UserOffice
order by age
</code>```

答:
Just add an ORDER BY clause at the very end of the UNION query, and it should be applied to the entire query:

```<code>select name, age
from UserUni
union all
select name, age
from UserOffice
order by age
</code>```

Note that I swapped the order of the columns appearing in the second half of the UNION query because it doesn't make sense to put age and name into the same column.  It is generally a requirement in a UNION query that the types and number of all columns be the same in boths halves of the query.  One exception might be MySQL, which might appear to allow mixing numbers and text, but even in this case some implicit type conversion would be happening underneath the hood.

Title: Order by in union clause

Body:
Could any one please help me I have been working on a query containing unions n joins of multiple tables.. I have got the desired results but I want to get these results in some specific order so the whole result is being orderd according to one column.
Here is the snippet of code I am working on:

select name, age
from UserUni
order by age
union all
select age, Name
from UserOffice
order by age

Body:
Just add an ORDER BY clause at the very end of the UNION query, and it should be applied to the entire query:

select name, age
from UserUni
union all
select name, age
from UserOffice
order by age

Note that I swapped the order of the columns appearing in the second half of the UNION query because it doesn't make sense to put age and name into the same column.  It is generally a requirement in a UNION query that the types and number of all columns be the same in boths halves of the query.  One exception might be MySQL, which might appear to allow mixing numbers and text, but even in this case some implicit type conversion would be happening underneath the hood.


问:
read data from a file rjags
My data file looks something like this:

```<code>list(y=structure(.Data=c(26, 228, 31, ...)), .Dim=c(413,9))
</code>```

Let's say this file is saved as "data.txt".

If I'm working in 'R2OpenBUGS', it allows me to pass the data as a file with no problem:

```<code>mcmc <- bugs(data = "data.txt", inits=...)
</code>```

But in JAGS, if I pass data as "data.txt", it says: "data must be a list or environment". What's the problem here? Also, if there is no way around it, is there a way I can read the data as list in R?

My model is:

```<code>model {
for (i in 1:413) {
    for (j in 1:9) {
        logy[i,j] <- log(y[i,j])
        logy[i,j] ~ dnorm(m[i], s)
    }
}

# priors
for (i in 1:413) {
    m[i] ~ dgamma(0.001, 0.001)
}

s ~ dgamma(0.001, 0.001)

}
</code>```

答:
From the JAGS user manual

7.0.4    Data transformations

JAGS allows data transformations, but the syntax is different from BUGS.
BUGS allows you to put a stochastic node twice on the left hand side of a relation, as in this example taken from the manual

```<code>for (i in 1:N) {
   z[i] <- sqrt(y[i])
   z[i] ~ dnorm(mu, tau)
}
</code>```

This is forbidden in JAGS. You must put data transformations in a separate block of relations preceded by the keyword data:

```<code>data {
   for (i in 1:N) {
     z[i] <- sqrt(y[i])
   }
}
model {
   for (i in 1:N) {
      z[i] ~ dnorm(mu, tau)
   }
   ...
}
</code>```

Title: read data from a file rjags

Body:
My data file looks something like this:

list(y=structure(.Data=c(26, 228, 31, ...)), .Dim=c(413,9))

Let's say this file is saved as "data.txt".

If I'm working in 'R2OpenBUGS', it allows me to pass the data as a file with no problem:

mcmc <- bugs(data = "data.txt", inits=...)

But in JAGS, if I pass data as "data.txt", it says: "data must be a list or environment". What's the problem here? Also, if there is no way around it, is there a way I can read the data as list in R?

My model is:

model {
for (i in 1:413) {
    for (j in 1:9) {
        logy[i,j] <- log(y[i,j])
        logy[i,j] ~ dnorm(m[i], s)
    }
}

# priors
for (i in 1:413) {
    m[i] ~ dgamma(0.001, 0.001)
}

s ~ dgamma(0.001, 0.001)

}

Body:
From the JAGS user manual

7.0.4    Data transformations

JAGS allows data transformations, but the syntax is different from BUGS.
BUGS allows you to put a stochastic node twice on the left hand side of a relation, as in this example taken from the manual

for (i in 1:N) {
   z[i] <- sqrt(y[i])
   z[i] ~ dnorm(mu, tau)
}

This is forbidden in JAGS. You must put data transformations in a separate block of relations preceded by the keyword data:

data {
   for (i in 1:N) {
     z[i] <- sqrt(y[i])
   }
}
model {
   for (i in 1:N) {
      z[i] ~ dnorm(mu, tau)
   }
   ...
}


答:
when we are using we can not use order by with both statements. because union at the end give one result end so how is it possible to use two order by statements.
you can check details here.

https://finalcodingtutorials.blogspot.ae/2017/03/order-by-clause-with-union-in-sql-server.html

hopefully it will resolve your issue will let you know complete details or union and order by statement.

Title: Order by in union clause


问:
JavaScript: Simple subtraction returns NaN
I have a problem,
my collision detection function sometimes sets entity position to NaN.
When I open console (on chrome) position of entity and collision are valid numbers but subtracting them from each other sometimes returns NaN.

```<code>updateCollision = function(entity,rect) {
var a = entity.x - rect.x; // a = NaN , entity.x = 3117.2646499953607 , rect.x = 3296.976967651385
var b = entity.y - rect.y; // b = NaN , entity.y = 3024.105915848102 , rect.y = 3144.4270586199345

if( isNaN(a) ) // isNaN(a) = true
{
    console.log("not again >:("); // but console doesn't log
}

//the code continues but its not important
</code>```

screenshot of console:

So I am really confused, and don't know what to do with this issue.

答:
I have rewriten the code one more time and I dont get the NaN values anymore

Fixed function:

```<code>updateCollision = function(entity,rect) {
var a = entity.x - rect.x;
var b = entity.y - rect.y;

var unrotatedCircleY = Math.sin((-rect.angle)/180*Math.PI)*a + Math.cos((-rect.angle)/180*Math.PI)*b +rect.y;
var unrotatedCircleX = Math.cos((-rect.angle)/180*Math.PI)*a - Math.sin((-rect.angle)/180*Math.PI)*b +rect.x;
var r = entity.collRad/2;

var closestX, closestY, aX, aY;

if (unrotatedCircleX < rect.x - rect.width/2 )
{
    closestX = rect.x - rect.width/2;
    aX = closestX;
}
else if (unrotatedCircleX  > rect.x + rect.width/2 )
{
    closestX = rect.x + rect.width/2;
    aX = closestX;
}
else
{
    closestX = unrotatedCircleX;
    aX=rect.x;
}

if (unrotatedCircleY < rect.y - rect.height/2 )
{
    closestY = rect.y - rect.height/2;
    aY = closestY;
}
else if (unrotatedCircleY > rect.y + rect.height/2 )
{
    closestY = rect.y + rect.height/2;
    aY = closestY;
}
else
{
    closestY = unrotatedCircleY;
    aY = rect.y;
}

var collision = false;

var distance = getDistance(unrotatedCircleX , unrotatedCircleY, closestX, closestY);
if (distance < r)
collision = true;
else
collision = false;

if( collision && entity.type == "bullet")
{
    entity.hp = 0;
}
else if(collision)
{
    if( entity.type == "bullet")
    {
        DeleteEntity(entity);
        return;
    }
    if( rect.collType == "solid" )
    {

        var positionAngle = Math.atan2( -closestY + unrotatedCircleY , -closestX + unrotatedCircleX );

        var y_vel = Math.sin((-rect.angle)/180*Math.PI)*entity.x_vel + Math.cos((-rect.angle)/180*Math.PI)*entity.y_vel;
        var x_vel = Math.cos((-rect.angle)/180*Math.PI)*entity.x_vel - Math.sin((-rect.angle)/180*Math.PI)*entity.y_vel;

        y_vel *= 0.9;
        x_vel *= 0.9;

        unrotatedCircleX = closestX + Math.cos(positionAngle)*(r);
        unrotatedCircleY = closestY + Math.sin(positionAngle)*(r);

        a = unrotatedCircleX - rect.x;
        b = unrotatedCircleY - rect.y;

        entity.y = Math.sin((rect.angle)/180*Math.PI)*a + Math.cos((rect.angle)/180*Math.PI)*b + rect.y;
        entity.x = Math.cos((rect.angle)/180*Math.PI)*a - Math.sin((rect.angle)/180*Math.PI)*b + rect.x;

        entity.y_vel = Math.sin((rect.angle)/180*Math.PI)*x_vel + Math.cos((rect.angle)/180*Math.PI)*y_vel;
        entity.x_vel = Math.cos((rect.angle)/180*Math.PI)*x_vel - Math.sin((rect.angle)/180*Math.PI)*y_vel;
    }
    if( rect.collType == "trigger" )
    {
        if( level["commandList"][rect.data].command == "tp" )
        {
            entity.x = level["commandList"][rect.data].x;
            entity.y = level["commandList"][rect.data].y;
        }
        if( level["commandList"][rect.data].command == "loadLevel" )
        {
            levelToLoad = level["commandList"][rect.data].x;
        }
    }
}
</code>```

But thanks for the help :)

Body:
I have a problem,
my collision detection function sometimes sets entity position to NaN.
When I open console (on chrome) position of entity and collision are valid numbers but subtracting them from each other sometimes returns NaN.

updateCollision = function(entity,rect) {
var a = entity.x - rect.x; // a = NaN , entity.x = 3117.2646499953607 , rect.x = 3296.976967651385
var b = entity.y - rect.y; // b = NaN , entity.y = 3024.105915848102 , rect.y = 3144.4270586199345

if( isNaN(a) ) // isNaN(a) = true
{
    console.log("not again >:("); // but console doesn't log
}

//the code continues but its not important

screenshot of console:

So I am really confused, and don't know what to do with this issue.

Body:
I have rewriten the code one more time and I dont get the NaN values anymore

Fixed function:

updateCollision = function(entity,rect) {
var a = entity.x - rect.x;
var b = entity.y - rect.y;

var unrotatedCircleY = Math.sin((-rect.angle)/180*Math.PI)*a + Math.cos((-rect.angle)/180*Math.PI)*b +rect.y;
var unrotatedCircleX = Math.cos((-rect.angle)/180*Math.PI)*a - Math.sin((-rect.angle)/180*Math.PI)*b +rect.x;
var r = entity.collRad/2;

var closestX, closestY, aX, aY;

if (unrotatedCircleX < rect.x - rect.width/2 )
{
    closestX = rect.x - rect.width/2;
    aX = closestX;
}
else if (unrotatedCircleX  > rect.x + rect.width/2 )
{
    closestX = rect.x + rect.width/2;
    aX = closestX;
}
else
{
    closestX = unrotatedCircleX;
    aX=rect.x;
}

if (unrotatedCircleY < rect.y - rect.height/2 )
{
    closestY = rect.y - rect.height/2;
    aY = closestY;
}
else if (unrotatedCircleY > rect.y + rect.height/2 )
{
    closestY = rect.y + rect.height/2;
    aY = closestY;
}
else
{
    closestY = unrotatedCircleY;
    aY = rect.y;
}

var collision = false;

var distance = getDistance(unrotatedCircleX , unrotatedCircleY, closestX, closestY);
if (distance < r)
collision = true;
else
collision = false;

if( collision && entity.type == "bullet")
{
    entity.hp = 0;
}
else if(collision)
{
    if( entity.type == "bullet")
    {
        DeleteEntity(entity);
        return;
    }
    if( rect.collType == "solid" )
    {

        var positionAngle = Math.atan2( -closestY + unrotatedCircleY , -closestX + unrotatedCircleX );

        var y_vel = Math.sin((-rect.angle)/180*Math.PI)*entity.x_vel + Math.cos((-rect.angle)/180*Math.PI)*entity.y_vel;
        var x_vel = Math.cos((-rect.angle)/180*Math.PI)*entity.x_vel - Math.sin((-rect.angle)/180*Math.PI)*entity.y_vel;

        y_vel *= 0.9;
        x_vel *= 0.9;

        unrotatedCircleX = closestX + Math.cos(positionAngle)*(r);
        unrotatedCircleY = closestY + Math.sin(positionAngle)*(r);

        a = unrotatedCircleX - rect.x;
        b = unrotatedCircleY - rect.y;

        entity.y = Math.sin((rect.angle)/180*Math.PI)*a + Math.cos((rect.angle)/180*Math.PI)*b + rect.y;
        entity.x = Math.cos((rect.angle)/180*Math.PI)*a - Math.sin((rect.angle)/180*Math.PI)*b + rect.x;

        entity.y_vel = Math.sin((rect.angle)/180*Math.PI)*x_vel + Math.cos((rect.angle)/180*Math.PI)*y_vel;
        entity.x_vel = Math.cos((rect.angle)/180*Math.PI)*x_vel - Math.sin((rect.angle)/180*Math.PI)*y_vel;
    }
    if( rect.collType == "trigger" )
    {
        if( level["commandList"][rect.data].command == "tp" )
        {
            entity.x = level["commandList"][rect.data].x;
            entity.y = level["commandList"][rect.data].y;
        }
        if( level["commandList"][rect.data].command == "loadLevel" )
        {
            levelToLoad = level["commandList"][rect.data].x;
        }
    }
}

But thanks for the help :)


问:
Constraining associated types in Swift protocol
I'm writing a little code snippet to learn about how associated types work, but I've come across an error I'm not sure how to interpret. The code I've written is posted below for reference.

```<code>// A basic protocol
protocol Doable {
    func doSomething() -> Bool
}

// An extension that adds a method to arrays containing Doables
extension Array where Element: Doable {

    func modify(using function:(Array<Doable>)->Array<Doable>) -> Array<Doable> {
        return function(self)
    }
}

// Another protocol with an associated type constrained to be Doable
protocol MyProtocol {
    associatedtype MyType: Doable

    func doers() -> Array<MyType>

    func change(_:Array<MyType>) -> Array<MyType>
}

// An simple extension
extension MyProtocol {

    func modifyDoers() -> Array<MyType> {
        return doers().modify(using: change)
    }
}
</code>```

I've constrained MyType to be Doable, but the compiler complains that it cannot convert (Array<Self.MyType>) -> Array<Self.MyType> to expected argument type (Array<Doable>) -> Array<Doable>. Can anybody explain what's going on here and how I can make the compiler happy?

答:
As the error message says, the modify function expects arguments with the type Array<Doable> and you're passing arguments with the type Array<MyType>.

The issue stems from the definition of modify, where you're explicitly using Doable in the parameters, which excludes all other types but Doable – and as associated types are not typealiases, MyType can't be converted to Doable.

The fix is to change all occurrences of Doable in the modify function to Element, as is portrayed in the Swift documentation: Extensions with a Generic Where Clause.

Body:
I'm writing a little code snippet to learn about how associated types work, but I've come across an error I'm not sure how to interpret. The code I've written is posted below for reference.

// A basic protocol
protocol Doable {
    func doSomething() -> Bool
}

// An extension that adds a method to arrays containing Doables
extension Array where Element: Doable {

    func modify(using function:(Array<Doable>)->Array<Doable>) -> Array<Doable> {
        return function(self)
    }
}

// Another protocol with an associated type constrained to be Doable
protocol MyProtocol {
    associatedtype MyType: Doable

    func doers() -> Array<MyType>

    func change(_:Array<MyType>) -> Array<MyType>
}

// An simple extension
extension MyProtocol {

    func modifyDoers() -> Array<MyType> {
        return doers().modify(using: change)
    }
}

I've constrained MyType to be Doable, but the compiler complains that it cannot convert (Array<Self.MyType>) -> Array<Self.MyType> to expected argument type (Array<Doable>) -> Array<Doable>. Can anybody explain what's going on here and how I can make the compiler happy?


问:
IBM/BlueMix move node-red to existing Cloudant NoSQL DB
I successfully set up the node-red starter on my IBM/BlueMix account. However, during the creation I did not have the choice to use a new Cloudant NoSQL DB instance (I guess this is where node-red stores its settings, and if I look at it via the web ui of IBM/BlueMix, I can indeed see only one database in it called "nodered").
I already had a Cloudant NoSQL DB instance which I want to use to centralize all my data.

How can I move the installed node-red to this Cloudant NoSQL DB instance?

Or did I overlook some setting during creation of the node-red that makes it possible during creation to point to an already existing Cloudant NoSQL DB instance?

答:
The Node-RED instance deployed by the boilerplate has a small wrapper which sets up the storage of flows and other settings in the Cloudant instance. The boilerplate creates a Cloudant instance as part of the install.

You can override the Cloudant instance by binding the new instance to the Node-RED instance and then setting the following environment variable to the name of the Cloudant instance:

```<code>NODE_RED_STORAGE_NAME=<Cloudant Instance Name>
</code>```

Details can be found here:

https://github.com/ibmets/node-red-bluemix/blob/master/public/app/bluemix-settings.js

Body:
The Node-RED instance deployed by the boilerplate has a small wrapper which sets up the storage of flows and other settings in the Cloudant instance. The boilerplate creates a Cloudant instance as part of the install.

You can override the Cloudant instance by binding the new instance to the Node-RED instance and then setting the following environment variable to the name of the Cloudant instance:

NODE_RED_STORAGE_NAME=<Cloudant Instance Name>

Details can be found here:

https://github.com/ibmets/node-red-bluemix/blob/master/public/app/bluemix-settings.js


问:
How to access a return value from a node script in BASH?
Let's say I have a bash script that calls a node script. I've tried to do it like this:

b.sh file:

```<code>#!/bin/bash
v=$(node app.js)
echo "$v"
</code>```

app.js file:

```<code>#!/usr/bin/env node
function f() {
   return "test";
}
return f();
</code>```

How do I access the value returned by the node script ("test") from my bash script ?

答:
@Daniel Lizik gave an good answer (now deleted) for the part: how to output the value, e.g. using his answer:

```<code>#!/usr/bin/env node
function f() {
   return "test";
}
console.log(f())
</code>```

And for the part how to capture the value in bash, do exactly as in your question:

```<code>#!/bin/bash
val=$(node app.js)
echo "node returned: $val"
</code>```

the above prints:

```<code>node returned: test
</code>```

Body:
Let's say I have a bash script that calls a node script. I've tried to do it like this:

b.sh file:

#!/bin/bash
v=$(node app.js)
echo "$v"

app.js file:

#!/usr/bin/env node
function f() {
   return "test";
}
return f();

How do I access the value returned by the node script ("test") from my bash script ?

Body:
@Daniel Lizik gave an good answer (now deleted) for the part: how to output the value, e.g. using his answer:

#!/usr/bin/env node
function f() {
   return "test";
}
console.log(f())

And for the part how to capture the value in bash, do exactly as in your question:

#!/bin/bash
val=$(node app.js)
echo "node returned: $val"

the above prints:

node returned: test


问:
Break-Inside and Break-After not working
I have a list of titles and definitions:

```<code><dl>
<dt>Item 1</dt>
<dd>Nulla at neque blandit, pretium sapien vitae, ornare neque.</dd>
<dt>Item 2</dt>
<dd>Quisque fermentum augue nec rutrum suscipit.</dd>
<dt>Item 3</dt>
<dd>Sed facilisis eros ac lorem bibendum, id tristique ipsum rhoncus.</dd>
<dt>Item 4</dt>
<dd>Duis scelerisque risus sit amet metus placerat volutpat.</dd>
<dt>Item 5</dt>
<dd>Duis tristique erat at leo lacinia, nec fringilla risus rhoncus.</dd>
<dt>Item 6</dt>
<dd>Cras rutrum eros dictum nulla tempus, in consequat tellus dignissim.</dd>
<dt>Item 7</dt>
<dd>Maecenas et erat vitae metus euismod luctus.</dd>
</code>```

If the browser is wide enough, I'd like to present this in a multi column layout. I'm able to do that, however, I'd like column breaks to happen only after s and never in the middle of s and s, or after s.

Right now I'm using:

```<code>dl{column-count:2}
dt,dd{break-inside:avoid;column-break-inside:avoid;-webkit-column-break-inside:avoid}
dt{break-after:never;column-break-after:never;-webkit-column-break-after:never}
</code>```

At least in chrome this doesn't seem to have any effect.

答:
You have to put dt and dd into a div. Moreover, you have to use break-inside also for this div. Note that you have to use also other declaration for compatibility trough browsers. For example, you have to add page-break-inside for Firefox. See here for further examples. See also the snippet.

I hope I was of any help.

dl {
  column-count: 2
}

dt,
dd,
.all {
  break-inside: avoid;
  page-break-inside: avoid;
  -webkit-column-break-inside: avoid
}

dt {
  break-after: never;
  column-break-after: never;
  -webkit-column-break-after: never
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><dl>
  <div class="all">
    <dt>Item 1</dt>
    <dd>Nulla at neque blandit, pretium sapien vitae, ornare neque.</dd>
  </div>
  <div class="all">
    <dt>Item 2</dt>
    <dd>Quisque fermentum augue nec rutrum suscipit.</dd>
  </div>
  <div class="all">
    <dt>Item 3</dt>
    <dd>Sed facilisis eros ac lorem bibendum, id tristique ipsum rhoncus.</dd>
  </div>
  <div class="all">
    <dt>Item 4</dt>
    <dd>Duis scelerisque risus sit amet metus placerat volutpat.</dd>
  </div>
  <div class="all">
    <dt>Item 5</dt>
    <dd>Duis tristique erat at leo lacinia, nec fringilla risus rhoncus.</dd>
  </div>
  <div class="all">
    <dt>Item 6</dt>
    <dd>Cras rutrum eros dictum nulla tempus, in consequat tellus dignissim.</dd>
  </div>
  <div class="all">
    <dt>Item 7</dt>
    <dd>Maecenas et erat vitae metus euismod luctus.</dd>
  </div>
</dl></code>```

Body:
I have a list of titles and definitions:

Item 1

Nulla at neque blandit, pretium sapien vitae, ornare neque.

Item 2

Quisque fermentum augue nec rutrum suscipit.

Item 3

Sed facilisis eros ac lorem bibendum, id tristique ipsum rhoncus.

Item 4

Duis scelerisque risus sit amet metus placerat volutpat.

Item 5

Duis tristique erat at leo lacinia, nec fringilla risus rhoncus.

Item 6

Cras rutrum eros dictum nulla tempus, in consequat tellus dignissim.

Item 7

Maecenas et erat vitae metus euismod luctus.

If the browser is wide enough, I'd like to present this in a multi column layout. I'm able to do that, however, I'd like column breaks to happen only after s and never in the middle of s and s, or after s.

Right now I'm using:

dl{column-count:2}
dt,dd{break-inside:avoid;column-break-inside:avoid;-webkit-column-break-inside:avoid}
dt{break-after:never;column-break-after:never;-webkit-column-break-after:never}

At least in chrome this doesn't seem to have any effect.

Body:
You have to put dt and dd into a div. Moreover, you have to use break-inside also for this div. Note that you have to use also other declaration for compatibility trough browsers. For example, you have to add page-break-inside for Firefox. See here for further examples. See also the snippet.

I hope I was of any help.

dl {
  column-count: 2
}

dt,
dd,
.all {
  break-inside: avoid;
  page-break-inside: avoid;
  -webkit-column-break-inside: avoid
}

dt {
  break-after: never;
  column-break-after: never;
  -webkit-column-break-after: never
}

<dl>
  <div class="all">
    <dt>Item 1</dt>
    <dd>Nulla at neque blandit, pretium sapien vitae, ornare neque.</dd>
  </div>
  <div class="all">
    <dt>Item 2</dt>
    <dd>Quisque fermentum augue nec rutrum suscipit.</dd>
  </div>
  <div class="all">
    <dt>Item 3</dt>
    <dd>Sed facilisis eros ac lorem bibendum, id tristique ipsum rhoncus.</dd>
  </div>
  <div class="all">
    <dt>Item 4</dt>
    <dd>Duis scelerisque risus sit amet metus placerat volutpat.</dd>
  </div>
  <div class="all">
    <dt>Item 5</dt>
    <dd>Duis tristique erat at leo lacinia, nec fringilla risus rhoncus.</dd>
  </div>
  <div class="all">
    <dt>Item 6</dt>
    <dd>Cras rutrum eros dictum nulla tempus, in consequat tellus dignissim.</dd>
  </div>
  <div class="all">
    <dt>Item 7</dt>
    <dd>Maecenas et erat vitae metus euismod luctus.</dd>
  </div>
</dl>


问:
Pointer tho another Object
I  have a little problem ..  I want to do car registration and i want to have owner(pointer to a Person object) but when i want to take the owner with get function i can't do that ... and this is mystery for me ... Maybe i have a little mistake somewhere and i can't find it .. Please help :) </p>

```<code>class Person
{
    friend class Cars;
public:
    Person(){}
    Person(uint8_t age, string name) :m_age(age), m_name(name)
    {
        m_idGener = s_idGenerator++;
    }

    int getId()
    {
        return m_idGener;
     }
    uint8_t getAge()
    {
        return m_age;
    }
    string getName()
    {
     return m_name;
    }
 private:
    string m_name;
    uint8_t m_age;
    static int s_idGenerator;
    int m_idGener;

 };
 class Cars:public Person
 {

 public:
     Person *m_owner; // this is my pointer which i want to point to cars     Object
  it will stay public for the test after the test i will move it in the     private section
    Cars()
    {
    }
   // getters and setters

    Cars setOwner(Cars &object, Person &owner) // with this function i set the owner
    {
      object.m_owner = &owner;
    }
    Cars getOwner(Cars &object) /// here is my problem i can't take the owner
    {
       return *(object.m_owner); // but i can't take the owner
    }

     uint16_t getHorsePower()
    {
       return horsePower;
    }
     string getRegNumber()
    {
       return registrationNumber;
    }
  private:
     string m_manufacturerName;
     string modelName;
     uint16_t horsePower;
    string registrationNumber;

};

int Person::s_idGenerator = 0;
</code>```

答:
You have made more mistakes. At least the followings should be corrected:

```<code>Cars setOwner(Cars &object,  .....
</code>```

This method doest not return a value, so it should be void. The car object should be the object for which the method will be called, not a parameter.

```<code>Cars getOwner(Cars &object) /// here is my problem i can't take the owner
{
   return *(object.m_owner); // but i can't take the owner
}
</code>```

In this method I would change the return type to Person *, then return simply m_owner. Parameter is not needed.

A modified working example:

```<code>#include <string>
#include <iostream>
using namespace std;
class Person
{
    friend class Cars;
public:
    Person(){}
    Person(uint8_t age, string name) :m_age(age), m_name(name)
    {
        m_idGener = s_idGenerator++;
    }

    int getId()
    {
        return m_idGener;
     }
    uint8_t getAge()
    {
        return m_age;
    }
    string getName()
    {
     return m_name;
    }
 private:
    string m_name;
    uint8_t m_age;
    static int s_idGenerator;
    int m_idGener;

 };
 class Cars:public Person
 {

 public:
     Person *m_owner; // this is my pointer which i want to point to cars     Object
                      // it will stay public for the test after the test i will move it in the     private section
    Cars()
    {
    }
   // getters and setters

    void setOwner(Person &owner) // with this function i set the owner
    {
      m_owner = &owner;
    }
    Person *getOwner() /// here is my problem i can't take the owner
    {
       return (m_owner); // but i can't take the owner
    }

     uint16_t getHorsePower()
    {
       return horsePower;
    }
     string getRegNumber()
    {
       return registrationNumber;
    }
  private:
     string m_manufacturerName;
     string modelName;
     uint16_t horsePower;
    string registrationNumber;

};

int Person::s_idGenerator = 0;

int main() {
  Person p(5,"Bill");
  Cars c;

  c.setOwner(p);
  cout << c.getOwner()->getName();
}
</code>```

Title: Pointer tho another Object

Body:
I  have a little problem ..  I want to do car registration and i want to have owner(pointer to a Person object) but when i want to take the owner with get function i can't do that ... and this is mystery for me ... Maybe i have a little mistake somewhere and i can't find it .. Please help :)

class Person
{
    friend class Cars;
public:
    Person(){}
    Person(uint8_t age, string name) :m_age(age), m_name(name)
    {
        m_idGener = s_idGenerator++;
    }

    int getId()
    {
        return m_idGener;
     }
    uint8_t getAge()
    {
        return m_age;
    }
    string getName()
    {
     return m_name;
    }
 private:
    string m_name;
    uint8_t m_age;
    static int s_idGenerator;
    int m_idGener;

 };
 class Cars:public Person
 {

 public:
     Person *m_owner; // this is my pointer which i want to point to cars     Object
  it will stay public for the test after the test i will move it in the     private section
    Cars()
    {
    }
   // getters and setters

    Cars setOwner(Cars &object, Person &owner) // with this function i set the owner
    {
      object.m_owner = &owner;
    }
    Cars getOwner(Cars &object) /// here is my problem i can't take the owner
    {
       return *(object.m_owner); // but i can't take the owner
    }

     uint16_t getHorsePower()
    {
       return horsePower;
    }
     string getRegNumber()
    {
       return registrationNumber;
    }
  private:
     string m_manufacturerName;
     string modelName;
     uint16_t horsePower;
    string registrationNumber;

};

int Person::s_idGenerator = 0;

Body:
You have made more mistakes. At least the followings should be corrected:

Cars setOwner(Cars &object,  .....

This method doest not return a value, so it should be void. The car object should be the object for which the method will be called, not a parameter.

Cars getOwner(Cars &object) /// here is my problem i can't take the owner
{
   return *(object.m_owner); // but i can't take the owner
}

In this method I would change the return type to Person *, then return simply m_owner. Parameter is not needed.

A modified working example:

#include <string>
#include <iostream>
using namespace std;
class Person
{
    friend class Cars;
public:
    Person(){}
    Person(uint8_t age, string name) :m_age(age), m_name(name)
    {
        m_idGener = s_idGenerator++;
    }

    int getId()
    {
        return m_idGener;
     }
    uint8_t getAge()
    {
        return m_age;
    }
    string getName()
    {
     return m_name;
    }
 private:
    string m_name;
    uint8_t m_age;
    static int s_idGenerator;
    int m_idGener;

 };
 class Cars:public Person
 {

 public:
     Person *m_owner; // this is my pointer which i want to point to cars     Object
                      // it will stay public for the test after the test i will move it in the     private section
    Cars()
    {
    }
   // getters and setters

    void setOwner(Person &owner) // with this function i set the owner
    {
      m_owner = &owner;
    }
    Person *getOwner() /// here is my problem i can't take the owner
    {
       return (m_owner); // but i can't take the owner
    }

     uint16_t getHorsePower()
    {
       return horsePower;
    }
     string getRegNumber()
    {
       return registrationNumber;
    }
  private:
     string m_manufacturerName;
     string modelName;
     uint16_t horsePower;
    string registrationNumber;

};

int Person::s_idGenerator = 0;

int main() {
  Person p(5,"Bill");
  Cars c;

  c.setOwner(p);
  cout << c.getOwner()->getName();
}


问:
Template parse errors:Parser Error: Unexpected token - RouterLink
On the below error . Am getting template parse error on RouterLink .

What is the correct way to use the  RouterLink in Angular 2 ?

```<code>      Unhandled Promise rejection: Template parse errors:Parser Error: Unexpected token / at column 2 in [[/events]] in ng:///t/e.html@30:46 ("r">
                 <ul class="nav nav-sidebar">
                    <li class="active"><a [ERROR ->][routerLink]="[/events]">Events</a></li>
                    <li><a [routerLink]="[/task"]>Tasks<"): ng:///t/e.html@30:46Parser Error: Unexpected token / at column 2 in [[/events]] in ng:///t/e.html@30:46 ("ebar">                     <ul class="nav nav-sidebar">
                    <li class="active">[ERROR ->]<a [routerLink]="[/events]">Events</a></li>
                    <li><a [routerLink]="[/task"]>Tas"): ng:///t/e.html@30:43, Directive tParser Error: Unexpected token / at column 2 in [[/events]] in ng:///t/e.html@30:46 ("ebar">
                 <ul class="nav nav-sidebar">
</code>```

答:
The syntax error the symbol / is not a string. Add quotes around the string to resolve error. [] is for array declaration (on the value), if you use it then add string value otherwise you don't need an array just use the attribute value which is string by default in HTML. You also don't need routerLink binding with [] in the resent verisons released by Angular.

So, the code simplifies to

Events
```

Body:
On the below error . Am getting template parse error on RouterLink .

What is the correct way to use the  RouterLink in Angular 2 ?

      Unhandled Promise rejection: Template parse errors:Parser Error: Unexpected token / at column 2 in [[/events]] in ng:///t/e.html@30:46 ("r">

][routerLink]="[/events]">Events

Tasks<"): ng:///t/e.html@30:46Parser Error: Unexpected token / at column 2 in [[/events]] in ng:///t/e.html@30:46 ("ebar">

[ERROR ->]Events

Tas"): ng:///t/e.html@30:43, Directive tParser Error: Unexpected token / at column 2 in [[/events]] in ng:///t/e.html@30:46 ("ebar">

Body:
The syntax error the symbol / is not a string. Add quotes around the string to resolve error. [] is for array declaration (on the value), if you use it then add string value otherwise you don't need an array just use the attribute value which is string by default in HTML. You also don't need routerLink binding with [] in the resent verisons released by Angular.

So, the code simplifies to

<a routerLink="/events">Events</a>


答:
Add upload library before you could call do_upload with config</p>

```<code>$config['upload_path'] = '/path/';
$config['allowed_types'] = '*';
$config['file_name'] = 'file_name';
$config['overwrite'] = TRUE|FALSE;

$this->load->library('upload', $config);
</code>```

Title: Codeigniter file upload code not working

Body:
Controller Code:

if(isset($_FILES['imageupload']) && $_FILES['imageupload']['size'] > 0){
    echo 'inside if';
    if ( ! $this->upload->do_upload('imageupload'))
    {
    echo 'inside if';
    $error = array('error' => $this->upload->display_errors());
    }
    else
    {
    echo 'inside else';
    $upload_data = $this->upload->data();
    $file_name[] = $upload_data['file_name'];
    }
}

View Code:

<input type="file" class="default" id="imageupload" name="imageupload">

ERROR: Call to a member function do_upload() on a non-object

Hoow can I resolve this error please help me.

Body:
Add upload library before you could call do_upload with config

$config['upload_path'] = '/path/';
$config['allowed_types'] = '*';
$config['file_name'] = 'file_name';
$config['overwrite'] = TRUE|FALSE;

$this->load->library('upload', $config);


问:
TwitterCore sdk: buildToolsVersion is not specified
I'm trying to add TwitterCore Kit to my android app. I used this in my project level build.gradle:

```<code>buildscript {
  repositories {
    jcenter()
    maven { url 'https://maven.fabric.io/public' }
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:1.5.0'
    // The Fabric Gradle plugin uses an open ended version to react
    // quickly to Android tooling updates
    classpath 'io.fabric.tools:gradle:1.+'
  }
}

apply plugin: 'com.android.application'
//Put Fabric plugin after Android plugin
apply plugin: 'io.fabric'

repositories {
    jcenter()
    maven { url 'https://maven.fabric.io/public' }
}
</code>```

and this in app level build.gradle:

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

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.abhishek.cleartaxtask"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile project(':volley')
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile('com.twitter.sdk.android:twitter-core:1.6.6@aar') {
        transitive = true;
    }
}
</code>```

When I sync gradle an error occurs buildToolsVersion is not specified. What am I doing wrong? How to add twitter sdk?

答:
For those who face same problem, add maven dependency at root(project) level build.gradle file.

```<code> allprojects {
     repositories {
         jcenter()
         maven { url 'https://maven.fabric.io/public' }
     } }
</code>```

Body:
I'm trying to add TwitterCore Kit to my android app. I used this in my project level build.gradle:

buildscript {
  repositories {
    jcenter()
    maven { url 'https://maven.fabric.io/public' }
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:1.5.0'
    // The Fabric Gradle plugin uses an open ended version to react
    // quickly to Android tooling updates
    classpath 'io.fabric.tools:gradle:1.+'
  }
}

apply plugin: 'com.android.application'
//Put Fabric plugin after Android plugin
apply plugin: 'io.fabric'

repositories {
    jcenter()
    maven { url 'https://maven.fabric.io/public' }
}

and this in app level build.gradle:

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.abhishek.cleartaxtask"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile project(':volley')
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile('com.twitter.sdk.android:twitter-core:1.6.6@aar') {
        transitive = true;
    }
}

When I sync gradle an error occurs buildToolsVersion is not specified. What am I doing wrong? How to add twitter sdk?

Body:
For those who face same problem, add maven dependency at root(project) level build.gradle file.

 allprojects {
     repositories {
         jcenter()
         maven { url 'https://maven.fabric.io/public' }
     } }


问:
Trying all possibilities for a number grid
I'm trying to solve a maths problem programmatically. I have a 6x5 grid, with a few predefined numbers, and I have to find the rest of the numbers with the condition of all rows and columns should total 34.

//Grid

```<code>    static int[][] sq;

    static void Main(string[] args)
    {
        sq = new int[6][];

        for (int i = 0; i < sq.Length; i++)
        {
            sq[i] = new int[5] { -250, -250, -250, -250, -250, };
        }

        SetDefaults();

        Print();

        Console.WriteLine("Press enter to quit...");
        Console.ReadLine();
    }

    static void SetDefaults()
    {
        sq[0][0] = 7;
        sq[0][1] = 6;
        sq[0][2] = 8;

        sq[2][2] = 9;
        sq[2][3] = 8;
        sq[2][4] = 5;

        sq[3][1] = 9;
        sq[3][3] = 7;
        sq[3][4] = 5;

        sq[4][0] = 4;
        sq[4][1] = 4;
        sq[4][4] = 9;

        sq[5][0] = 8;
        sq[5][2] = 3;
        sq[5][3] = 6;
        sq[5][4] = 8;
    }

    static void Print()
    {
        Console.WriteLine();
        for (int i = 0; i<sq.Length; i++)
        {
            for (int ii = 0; ii < sq[i].Length; ii++)
            {
                Console.Write("[" + sq[i][ii] + "\t]");
            }
            Console.WriteLine();
        }
        Console.WriteLine();
    }
</code>```

I think one method is try all the possibilities, with a range of 500 numbers, from -250 to 250, or an incremental range (-1,1, then -2,2, etc), but I don't know how to do this programmatically and much less efficiently.

答:
I have a 6x5 grid

The number of columns and rows is different?
Then, no matter what's in the grid, there is no solution at all to make all sums equal. Consequently there is nothing to code.

Not putting too much effort in it, but if you are really thinking of enumerating something, you could (but shouldn't) try this naive and unoptimized approach (for a range of integers between 0 and 15):

```<code>for (int a = 0; a < 16; a++) {
for (int b = 0; b < 16; b++) {
for (int c = 0; c < 16; c++) {
for (int d = 0; d < 16; d++) {
for (int e = 0; e < 16; e++) {
for (int f = 0; f < 16; f++) {
for (int g = 0; g < 16; g++) {
for (int h = 0; h < 16; h++) {
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
for (int k = 0; k < 16; k++) {
for (int l = 0; l < 16; l++) {
for (int m = 0; m < 16; m++) {
for (int n = 0; n < 16; n++) {
// test all columns and rows:
// test if 7 + 8 + 9 + a + b == 34
// test if c + d + e + f + g == 34
...
}}}}}}}}}}}}}}
</code>```

Certainly possible to optimize a lot, like:

```<code>for (int a = 0; a < 16; a++) {
var b = 34 - 7 - 8 - 9 - a;
for (int c = 0; c < 16; c++) {
for (int d = 0; d < 16; d++) {
for (int e = 0; e < 16; e++) {
for (int f = 0; f < 16; f++) {
var g = 34 - c - d - e - f;
for (int h = 0; h < 16; h++) {
var i = 34 - 9 - 8 - 5 - h;
for (int j = 0; j < 16; j++) {
var k = 34 - 9 - 7 - 5 - j;
for (int l = 0; l < 16; l++) {
var m = 34 - 4 - 4 - 9 - l;
var n = 34 - 8 - 3 - 6 - 8;
// test all columns only:
// test if 7 + c + h + 4 + 8 == 34
...
}}}}}}}}
</code>```

But in the end, best optimization is to return "no solution" directly.

Body:
I'm trying to solve a maths problem programmatically. I have a 6x5 grid, with a few predefined numbers, and I have to find the rest of the numbers with the condition of all rows and columns should total 34.

//Grid

    static int[][] sq;

    static void Main(string[] args)
    {
        sq = new int[6][];

        for (int i = 0; i < sq.Length; i++)
        {
            sq[i] = new int[5] { -250, -250, -250, -250, -250, };
        }

        SetDefaults();

        Print();

        Console.WriteLine("Press enter to quit...");
        Console.ReadLine();
    }

    static void SetDefaults()
    {
        sq[0][0] = 7;
        sq[0][1] = 6;
        sq[0][2] = 8;

        sq[2][2] = 9;
        sq[2][3] = 8;
        sq[2][4] = 5;

        sq[3][1] = 9;
        sq[3][3] = 7;
        sq[3][4] = 5;

        sq[4][0] = 4;
        sq[4][1] = 4;
        sq[4][4] = 9;

        sq[5][0] = 8;
        sq[5][2] = 3;
        sq[5][3] = 6;
        sq[5][4] = 8;
    }

    static void Print()
    {
        Console.WriteLine();
        for (int i = 0; i<sq.Length; i++)
        {
            for (int ii = 0; ii < sq[i].Length; ii++)
            {
                Console.Write("[" + sq[i][ii] + "\t]");
            }
            Console.WriteLine();
        }
        Console.WriteLine();
    }

I think one method is try all the possibilities, with a range of 500 numbers, from -250 to 250, or an incremental range (-1,1, then -2,2, etc), but I don't know how to do this programmatically and much less efficiently.

Body:
I have a 6x5 grid

The number of columns and rows is different?
Then, no matter what's in the grid, there is no solution at all to make all sums equal. Consequently there is nothing to code.

Not putting too much effort in it, but if you are really thinking of enumerating something, you could (but shouldn't) try this naive and unoptimized approach (for a range of integers between 0 and 15):

for (int a = 0; a < 16; a++) {
for (int b = 0; b < 16; b++) {
for (int c = 0; c < 16; c++) {
for (int d = 0; d < 16; d++) {
for (int e = 0; e < 16; e++) {
for (int f = 0; f < 16; f++) {
for (int g = 0; g < 16; g++) {
for (int h = 0; h < 16; h++) {
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
for (int k = 0; k < 16; k++) {
for (int l = 0; l < 16; l++) {
for (int m = 0; m < 16; m++) {
for (int n = 0; n < 16; n++) {
// test all columns and rows:
// test if 7 + 8 + 9 + a + b == 34
// test if c + d + e + f + g == 34
...
}}}}}}}}}}}}}}

Certainly possible to optimize a lot, like:

for (int a = 0; a < 16; a++) {
var b = 34 - 7 - 8 - 9 - a;
for (int c = 0; c < 16; c++) {
for (int d = 0; d < 16; d++) {
for (int e = 0; e < 16; e++) {
for (int f = 0; f < 16; f++) {
var g = 34 - c - d - e - f;
for (int h = 0; h < 16; h++) {
var i = 34 - 9 - 8 - 5 - h;
for (int j = 0; j < 16; j++) {
var k = 34 - 9 - 7 - 5 - j;
for (int l = 0; l < 16; l++) {
var m = 34 - 4 - 4 - 9 - l;
var n = 34 - 8 - 3 - 6 - 8;
// test all columns only:
// test if 7 + c + h + 4 + 8 == 34
...
}}}}}}}}

But in the end, best optimization is to return "no solution" directly.


问:
Get another component input value React js
I have two components one is app component and other one is sidebar component i have been using input field in side bar and i want to get the value of that input field in my app component  on click how this could be possible ?</p>

答:
You can try lifting the state up.

Create a new component that will contain your two components. In that new component, create a function that you will pass as props inside the sidebar component.

```<code>class ContainerComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            valueThatNeedsToBeShared: ''
        }
    }

    handleChange(e) {
        this.setState({valueThatNeedsToBeShared: e.target.value})
    }

    render() {
        return (
            <div>
                <AppComponent value={this.state.valueThatNeedsToBeShared} />
                <SidebarComponent handleChange={this.handleClick.bind(this)} value={this.state.valueThatNeedsToBeShared} />
            </div>
        )
    }
}

const SidebarComponent = ({handleChange, value}) => <aside>
    <input value={value} onChange={handleChange} />
</aside>

const AppComponent = ({value}) => <div>
    value from sidebar: {value}
</div>
</code>```

Body:
You can try lifting the state up.

Create a new component that will contain your two components. In that new component, create a function that you will pass as props inside the sidebar component.

class ContainerComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            valueThatNeedsToBeShared: ''
        }
    }

    handleChange(e) {
        this.setState({valueThatNeedsToBeShared: e.target.value})
    }

    render() {
        return (
            <div>
                <AppComponent value={this.state.valueThatNeedsToBeShared} />
                <SidebarComponent handleChange={this.handleClick.bind(this)} value={this.state.valueThatNeedsToBeShared} />
            </div>
        )
    }
}

const SidebarComponent = ({handleChange, value}) => <aside>
    <input value={value} onChange={handleChange} />
</aside>

const AppComponent = ({value}) => <div>
    value from sidebar: {value}
</div>


答:
Correspond to the documentation (see description of the data parameter)

It can replace addRowData method which
  is slow on relative big data

I don't made any measure myself, but the usage of data parameter seems me also as one of the most effective ways. It is important how many rows of data you want to add. The parameter datastr used together with datatype:jsonstring is relatively old way existing before introducing in the version 3.7 the local paging of data. With respect of the data parameter you can add large set of pure data, sort it and display the first page of the data. The filling of the first page with the data from the data parameter will be done with respect of addJSONData function so the part of work is the same in all cases. Only the filling of data which size is grater as the page size makes the way with the data parameter more effective.

If you will use data parameter you should don't forget to define additional id property in the data array. It can be either the property with default id name or another name defined in localReader. If you defined key:true for one column of the jqGrid, then including of additional id property is not needed.

Title: Best way to load jqGrid with static data?

Body:
We load 10 rows of static data into our jqGrid by creating a JSON string:

var d = "{\"page\":1,\"records\":10,\"total\":1,\"rows\":[" +
                "{\"id\":\"1\",\"cell\":[\"\"]}," +
                "{\"id\":\"2\",\"cell\":[\"\"]}," +
                "{\"id\":\"3\",\"cell\":[\"\"]}," +
                "{\"id\":\"4\",\"cell\":[\"\"]}," +
                "{\"id\":\"5\",\"cell\":[\"\"]}," +
                "{\"id\":\"6\",\"cell\":[\"\"]}," +
                "{\"id\":\"7\",\"cell\":[\"\"]}," +
                "{\"id\":\"8\",\"cell\":[\"\"]}," +
                "{\"id\":\"9\",\"cell\":[\"\"]}," +
                "{\"id\":\"10\",\"cell\":[\"\"]}" +
            "]}";

And loading that into a grid with datatype:jsonstring and datastr:d where our grid has 15 columns and each column is created using a custom formatter.

Is there a better way to do this?


问:
PHP merge sort not working
I made a merge sort in python which works fine and I've tried recreating the logic in PHP but it is not working correctly. Here is the python code:

```<code>def merge(array):
    if len(array) > 1:
        arrayL = []
        arrayR = []
        for i in range(int(len(array)/2)):
            arrayL.append(array[i])
        for i in range(int(len(array)/2),len(array)):
            arrayR.append(array[i])
        arrayL = merge(arrayL)
        arrayR = merge(arrayR)
        left = right = insert = 0
        while left < len(arrayL) and right < len(arrayR):
            if arrayL[left] < arrayR[right]:
                array[insert] = arrayL[left]
                left += 1
            else:
                array[insert] = arrayR[right]
                right += 1
            insert += 1
        while left < len(arrayL):
            array[insert] = arrayL[left]
            left += 1
            insert += 1
        while right < len(arrayR):
            array[insert] = arrayR[right]
            right += 1
            insert += 1
    return array
</code>```

And this is from the shell:

```<code>>>> merge([23,21,5,111,32,11,7,1,45])
[1, 5, 7, 11, 21, 23, 32, 45, 111]
</code>```

Here is the PHP code:

```<code>function merge($array) {
    $arrayLength = count($array);
    if ($arrayLength > 1) {
        $arrayLeft = array_slice($array, 0, $arrayLength/2);
        $arrayRight = array_slice($array, $arrayLength/2);
        $arrayLeft = merge($arrayLeft);
        $arrayRight = merge($arrayRight);
        $left = 0;
        $right = 0;
        $insert = 0;
        while ($left < count($arrayLeft) and $right < count($arrayRight)){
            if ($arrayLeft[$left] < $arrayRight[$right]) {
                $array[$insert] = $arrayLeft[$left];
                $left += 1;
            } else {
                $array[$insert] = $arrayRight[$right];
                $right += 1;
            }
            $insert += 1;
        }
        while ($left < count($arrayLeft)) {
            $array[$insert] = $arrayLeft[$left];
            $left += 1;
            $insert += 1;
        }
        while ($right < count($arrayRight)) {
            $array[$insert] = $arrayRight[$right];
            $right += 1;
            $insert += 1;
        }
        return $array;
    }

}

print_r(merge(array(23,21,5,111,32,11,7,1,45)));
</code>```

And this is what it outputs:

```<code>Array ( [0] => 1 [1] => 5 [2] => 23 [3] => 21 [4] => 32 [5] => 11 [6] => 45 [7] => 45 [8] => 111 )
</code>```

Any help would be very much appreciated

答: The return $array; statement should be outside the if scope.

Title: PHP merge sort not working

Body:
I made a merge sort in python which works fine and I've tried recreating the logic in PHP but it is not working correctly. Here is the python code:

def merge(array):
    if len(array) > 1:
        arrayL = []
        arrayR = []
        for i in range(int(len(array)/2)):
            arrayL.append(array[i])
        for i in range(int(len(array)/2),len(array)):
            arrayR.append(array[i])
        arrayL = merge(arrayL)
        arrayR = merge(arrayR)
        left = right = insert = 0
        while left < len(arrayL) and right < len(arrayR):
            if arrayL[left] < arrayR[right]:
                array[insert] = arrayL[left]
                left += 1
            else:
                array[insert] = arrayR[right]
                right += 1
            insert += 1
        while left < len(arrayL):
            array[insert] = arrayL[left]
            left += 1
            insert += 1
        while right < len(arrayR):
            array[insert] = arrayR[right]
            right += 1
            insert += 1
    return array

And this is from the shell:

>>> merge([23,21,5,111,32,11,7,1,45])
[1, 5, 7, 11, 21, 23, 32, 45, 111]

Here is the PHP code:

function merge($array) {
    $arrayLength = count($array);
    if ($arrayLength > 1) {
        $arrayLeft = array_slice($array, 0, $arrayLength/2);
        $arrayRight = array_slice($array, $arrayLength/2);
        $arrayLeft = merge($arrayLeft);
        $arrayRight = merge($arrayRight);
        $left = 0;
        $right = 0;
        $insert = 0;
        while ($left < count($arrayLeft) and $right < count($arrayRight)){
            if ($arrayLeft[$left] < $arrayRight[$right]) {
                $array[$insert] = $arrayLeft[$left];
                $left += 1;
            } else {
                $array[$insert] = $arrayRight[$right];
                $right += 1;
            }
            $insert += 1;
        }
        while ($left < count($arrayLeft)) {
            $array[$insert] = $arrayLeft[$left];
            $left += 1;
            $insert += 1;
        }
        while ($right < count($arrayRight)) {
            $array[$insert] = $arrayRight[$right];
            $right += 1;
            $insert += 1;
        }
        return $array;
    }

}

print_r(merge(array(23,21,5,111,32,11,7,1,45)));

And this is what it outputs:

Array ( [0] => 1 [1] => 5 [2] => 23 [3] => 21 [4] => 32 [5] => 11 [6] => 45 [7] => 45 [8] => 111 )

Any help would be very much appreciated


问:
Has .txt file been closed?
I have a slight problem. I have a project that I'm working on and that requires two programs to read/write into some .txt files.

Python writes into one .txt file, C++ reads from it. C++ does what it needs to do and then writes its own information into another .txt file that Python has to read.

What I want to know is how can I check with C++ if Python has closed the .txt file before opening the same file, as Python may still be writing stuff into it and vice versa?

If you need any extra information about this conundrum, feel free to contact me.

答:
whenever, in python, you use:

```<code>f.open()
</code>```

always follow it with

```<code>f.close()
</code>```

then you know its closed

see:

https://docs.python.org/2/tutorial/inputoutput.html

https://www.tutorialspoint.com/python/file_close.htm

re: comment

ETA

How to check if a file has been opened by another application in C++?

Is there a way to check if a file is in use?

C/C++ Standard Function to Check if a file is used by another process?

Way to check in C/C++ if a file is in use?

albeit hacky, I think my favorite after reading through was this one:

```<code>  if (  0 != rename("c:/foo.txt", "c:/foo.txt")  ) {
     printf("already opened\n");
  }
</code>```

https://stackoverflow.com/a/1048721/3680588

Title: Has .txt file been closed?

Body:
whenever, in python, you use:

f.open()

always follow it with

f.close()

then you know its closed

see:

https://docs.python.org/2/tutorial/inputoutput.html

https://www.tutorialspoint.com/python/file_close.htm

re: comment

ETA

How to check if a file has been opened by another application in C++?

Is there a way to check if a file is in use?

C/C++ Standard Function to Check if a file is used by another process?

Way to check in C/C++ if a file is in use?

albeit hacky, I think my favorite after reading through was this one:

  if (  0 != rename("c:/foo.txt", "c:/foo.txt")  ) {
     printf("already opened\n");
  }

https://stackoverflow.com/a/1048721/3680588