问:
identical word alignment using for loop
I'm trying to align words from two list

```<code>sentence1 = ['boy','motorcycle','people','play']
sentence2 = ['run','boy','people','boy','play','play']
</code>```

and this is my codes :

```<code>def identicalWordsIndex(self, sentence1, sentence2):
    identical_index = []
    for i in xrange(len(sentence1)):
        for j in xrange(len(sentence2)):
            if sentence1[i] == sentence2[j]:
                idenNew1 = [i,j]
                identical_index.append(idenNew1)
            if sentence2[j] == sentence1[i]:
                idenNew2 = [j,i]
                identical_index.append(idenNew2)
    return identical_index
</code>```

what i'm trying to do is get the index number of align words from sentence1 and sentence2.

1st is the aligned words index from sentence1 towards sentence2.
2nd is the aligned words index from sentence2 towards sentence1.

but the result from the codes above is like this :

```<code>1st : [[0, 1], [1, 0], [0, 3], [3, 0], [2, 2], [2, 2], [3, 4], [4, 3], [3, 5], [5, 3]]
2nd : [[0, 1], [1, 0], [0, 3], [3, 0], [2, 2], [2, 2], [3, 4], [4, 3], [3, 5], [5, 3]]
</code>```

what I expect from the result is like this :

```<code>1st : [[0,1],[2,2],[3,4]]
2nd : [[1,0],[2,2],[3,0],[4,3],[5,3]]
</code>```

anyone can solve? thanks

答:
See if this suits you. At the last two lines, you can just swap the arguments to get what you want.

```<code>sentence1 = ['boy','motorcycle','people','play']
sentence2 = ['run','boy','people','boy','play','play']

def identicalWordsIndex(sentence1, sentence2):
    identical_index = []
    for i in range(len(sentence1)):
        for j in range(len(sentence2)):
            if sentence1[i] == sentence2[j]:
            identical_index.append([i, j])
                break
    return identical_index

print(identicalWordsIndex(sentence1, sentence2))
print(identicalWordsIndex(sentence2, sentence1))
</code>```

output:

```<code>>>>[[0, 1], [2, 2], [3, 4]]
>>>[[1, 0], [2, 2], [3, 0], [4, 3], [5, 3]]
</code>```

Title: identical word alignment using for loop

Body:
I'm trying to align words from two list

sentence1 = ['boy','motorcycle','people','play']
sentence2 = ['run','boy','people','boy','play','play']

and this is my codes :

def identicalWordsIndex(self, sentence1, sentence2):
    identical_index = []
    for i in xrange(len(sentence1)):
        for j in xrange(len(sentence2)):
            if sentence1[i] == sentence2[j]:
                idenNew1 = [i,j]
                identical_index.append(idenNew1)
            if sentence2[j] == sentence1[i]:
                idenNew2 = [j,i]
                identical_index.append(idenNew2)
    return identical_index

what i'm trying to do is get the index number of align words from sentence1 and sentence2.

1st is the aligned words index from sentence1 towards sentence2.
2nd is the aligned words index from sentence2 towards sentence1.

but the result from the codes above is like this :

1st : [[0, 1], [1, 0], [0, 3], [3, 0], [2, 2], [2, 2], [3, 4], [4, 3], [3, 5], [5, 3]]
2nd : [[0, 1], [1, 0], [0, 3], [3, 0], [2, 2], [2, 2], [3, 4], [4, 3], [3, 5], [5, 3]]

what I expect from the result is like this :

1st : [[0,1],[2,2],[3,4]]
2nd : [[1,0],[2,2],[3,0],[4,3],[5,3]]

anyone can solve? thanks

Body:
See if this suits you. At the last two lines, you can just swap the arguments to get what you want.

sentence1 = ['boy','motorcycle','people','play']
sentence2 = ['run','boy','people','boy','play','play']

def identicalWordsIndex(sentence1, sentence2):
    identical_index = []
    for i in range(len(sentence1)):
        for j in range(len(sentence2)):
            if sentence1[i] == sentence2[j]:
            identical_index.append([i, j])
                break
    return identical_index

print(identicalWordsIndex(sentence1, sentence2))
print(identicalWordsIndex(sentence2, sentence1))

output:

>>>[[0, 1], [2, 2], [3, 4]]
>>>[[1, 0], [2, 2], [3, 0], [4, 3], [5, 3]]


来源: stackexchange

问:
Laravel / VirtualBox / Mac permissions error
I am running debian on my virtualbox on my Macbook Pro.

When building my Laravel application - I have set my permissions locally to be 777 on public, storage and bootstrap.

Every time I logout / in I then get another permissions error:

My mount permissions are:

```<code>sudo mount -t vboxsf -o auto,exec,rw,uid=1000,gid=33 BASE ./BASE
</code>```

Can anyone advise what I need to do to fix this? I've tried sticky bit, but no joy.

Thanks

答:
777 on storage does not mean 777 on storage/framework/sessions.

CHMOD the following directories to 0777 as well: storage/framework/sessions and storage/framework/cache

ContentLicense: CC BY-SA 3.0

Body:
I am running debian on my virtualbox on my Macbook Pro.

When building my Laravel application - I have set my permissions locally to be 777 on public, storage and bootstrap.

Every time I logout / in I then get another permissions error:

My mount permissions are:

sudo mount -t vboxsf -o auto,exec,rw,uid=1000,gid=33 BASE ./BASE

Can anyone advise what I need to do to fix this? I've tried sticky bit, but no joy.

Thanks


问:
How do I modify an AWS Step function?
From the AWS console it seems like AWS Step functions are immutable. Is there a way to modify it ? If not how does the version control work ? Do I have to create a new State machine every time I have to make incremental changes to the state machine ?</p>

答: As per this forum entry, there is no way yet to modify an existing state machine. You need to create a new one every time.

Title: How do I modify an AWS Step function?


问:
numpy array of zeros or empty
I am writing code and efficiency is very important.
Actually I need 2d array, that I am filling with 0 and 1 in for loop. What is better and why?

Make empty array and fill it with "0" and "1". It's pseudocode, my array will be much bigger.

Make array filled by zeros and make if() and if not zero - put one.

So I need information what is more efficiency:
1. Put every element "0" and "1" to empty array
or
2. Make if() (efficiency of 'if') and then put only "1" element.

答:
empty() does not initialize the memory, therefore your array will be filled with garbage and you will have to initialize all cells.

zeros() initializes everything to 0. Therefore, if your final result includes lots of zeros, this will save you the time to set all those array cells to zero manually.

I would go with zeros(). The performance bottleneck will be your python for loop anyway.

Fortunately, Numpy now as a JIT compiler, which can turn your crummy and slow python for loop into machine code:

http://numba.pydata.org/

I tried it. It's a bit rough around the edges, but the speedups can be quite spectacular compared to bare python code. Of course the best choice is to vectorize using numpy, but you don't always have a choice.

Title: numpy array of zeros or empty


问:
SQL Developer Where Query
I have tables for Sales, Vehicles and Customers and I am trying to create a query that will give the most sold vehicle make with the first and last names of customers that bought that type of vehicle. I created the following as a subquery to find the vehicle sales in descending order:

```<code>SELECT Vehicles.Vehicle_Make,
COUNT(Sales.VIN) AS NumberOfSales
FROM Sales
INNER JOIN Vehicles ON Sales.VIN = Vehicles.VIN
GROUP BY Vehicles.Vehicle_Make
ORDER BY NumberOfSales DESC;
</code>```

The Customers and Sales tables share the common Cust_ID Column from which I can get the Customers First and Last names. Since the first row would give me the most sold vehicle make, how would I query to get just the first row and join the results from this subquery to the Customers table to get the first and last names?  Thank you for your advice in advance.

答:
Something like this:</p>

```<code>select c.*
from (
  select top 1
      vehicles.vehicle_make
    , count(sales.vin) as numberofsales
  from sales
    inner join vehicles
      on sales.vin = vehicles.vin
  group by vehicles.vehicle_make
  order by numberofsales desc
  ) t
  inner join vehicles v
    on v.vehicle_make = t.vehicle_make
  inner join sales s
     on s.vehicle_vin = v.vehicle_vin
  inner join customer c
     on c.cust_id = s.cust_id
</code>```

Title: SQL Developer Where Query

Body:
I have tables for Sales, Vehicles and Customers and I am trying to create a query that will give the most sold vehicle make with the first and last names of customers that bought that type of vehicle. I created the following as a subquery to find the vehicle sales in descending order:

SELECT Vehicles.Vehicle_Make,
COUNT(Sales.VIN) AS NumberOfSales
FROM Sales
INNER JOIN Vehicles ON Sales.VIN = Vehicles.VIN
GROUP BY Vehicles.Vehicle_Make
ORDER BY NumberOfSales DESC;

The Customers and Sales tables share the common Cust_ID Column from which I can get the Customers First and Last names. Since the first row would give me the most sold vehicle make, how would I query to get just the first row and join the results from this subquery to the Customers table to get the first and last names?  Thank you for your advice in advance.

Body:
Something like this:

select c.*
from (
  select top 1
      vehicles.vehicle_make
    , count(sales.vin) as numberofsales
  from sales
    inner join vehicles
      on sales.vin = vehicles.vin
  group by vehicles.vehicle_make
  order by numberofsales desc
  ) t
  inner join vehicles v
    on v.vehicle_make = t.vehicle_make
  inner join sales s
     on s.vehicle_vin = v.vehicle_vin
  inner join customer c
     on c.cust_id = s.cust_id


问:
Import one android app into other app
I have implemented certain android app, this app has some several activities, views,fragments,google analytycs, crashlytics, gcm(cloud messaging, realm, retrofit, rx java and etc.).

I need to import this app as a module/library into other app in order to use the resources,activity,view and other classes of the imported app.

I think i should add is a module, and then add compile project('asdasd') to dependencies in the main :app module.

I'm not sure actually about the AndroidManifest.xml. Should i move all data from AndroidManifest.xml of the imported project to the main project? How to deal with google analytycs, gcm(it's connected to package name), plugins(fabric,realm,...)

What i want is to use the activities of the imported project in the main project. But what about Application class? Where it should be declared? as i use some instantiations when app starts.

Also i don't understand what will happen to imported project package name.

答:
You need to create AAR Android Archive file of your current project. Basically .aar bundle is the binary distribution of an Android Library Project. An AAR is similar to a JAR file, but it can contain resources as well as compiled byte-code. A AAR file can be included in the build process of an Android application similar to a JAR file. Later you can add it as module dependency in your new project and you will able to reuse its components.

You can also import it as module in your new project as you said.

Query relating to GCM and other third party library merging will be taken care by Android Studio when manifest merger will happen.

Title: Import one android app into other app


问:
TypeScript - implode a string dictionary
I'd like to have a key-value dictionary of strings (or should I use Map?), for example:

```<code>private queryStringParams : { [key:string] : string } = {
  "x":"y",
  "foo":"bar"
};
</code>```

and then implode\join\flatmap\zip it into a string such that each key\value pair is joined by a delimiter, and then all the pairs are joined by a delimiter.

For example the previous dictionary would turn into this with '&' as 1st level delimiter and '=' as 2nd level delimiter:

```<code>"foo=bar&x=y"
</code>```

I can do that with arrays and loops but was thinking maybe theres a more elegant way to do that with TypeScript. (I'll take no as an answer as well)

答:
I cannot immediately recall, but you might need the hasOwnProperty check depending on how complex your object hierarchy is. Nevertheless, a combination of map, Typescript template strings, and join can simplify this:

```<code>var value = Object.keys(queryStringParams)
    .map((property) => `${property}=${queryStringParams[property]}`)
    .join('&');
</code>```

Body:
I'd like to have a key-value dictionary of strings (or should I use Map?), for example:

private queryStringParams : { [key:string] : string } = {
  "x":"y",
  "foo":"bar"
};

and then implode\join\flatmap\zip it into a string such that each key\value pair is joined by a delimiter, and then all the pairs are joined by a delimiter.

For example the previous dictionary would turn into this with '&' as 1st level delimiter and '=' as 2nd level delimiter:

"foo=bar&x=y"

I can do that with arrays and loops but was thinking maybe theres a more elegant way to do that with TypeScript. (I'll take no as an answer as well)

Body:
I cannot immediately recall, but you might need the hasOwnProperty check depending on how complex your object hierarchy is. Nevertheless, a combination of map, Typescript template strings, and join can simplify this:

var value = Object.keys(queryStringParams)
    .map((property) => `${property}=${queryStringParams[property]}`)
    .join('&');


问:
Need to list all triggers in SQL Server database with table name and table's schema
I need to list all triggers in SQL Server database with table name and table's schema.

I'm almost there with this:

```<code>SELECT trigger_name = name, trigger_owner = USER_NAME(uid),table_schema = , table_name = OBJECT_NAME(parent_obj),
  isupdate = OBJECTPROPERTY( id, 'ExecIsUpdateTrigger'), isdelete = OBJECTPROPERTY( id, 'ExecIsDeleteTrigger'),
  isinsert = OBJECTPROPERTY( id, 'ExecIsInsertTrigger'), isafter = OBJECTPROPERTY( id, 'ExecIsAfterTrigger'),
  isinsteadof = OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger'),
  [disabled] = OBJECTPROPERTY(id, 'ExecIsTriggerDisabled')
FROM sysobjects INNER JOIN sysusers ON sysobjects.uid = sysusers.uid
WHERE type = 'TR'
</code>```

I just need to get the table's schema also.

答:
One difficulty is that the text, or description has line feeds. My clumsy kludge, to get it in something more tabular, is to add an HTML literal to the SELECT clause, copy and paste everything to notepad, save with an html extension, open in a browser, then copy and paste to a spreadsheet.
example

```<code>SELECT obj.NAME AS TBL,trg.name,sm.definition,'<br>'
FROM SYS.OBJECTS obj
LEFT JOIN (SELECT trg1.object_id,trg1.parent_object_id,trg1.name FROM sys.objects trg1 WHERE trg1.type='tr' AND trg1.name like 'update%') trg
 ON obj.object_id=trg.parent_object_id
LEFT JOIN (SELECT sm1.object_id,sm1.definition FROM sys.sql_modules sm1 where sm1.definition like '%suser_sname()%') sm ON trg.object_id=sm.object_id
WHERE obj.type='u'
ORDER BY obj.name;
</code>```

you may still need to fool around with tabs to get the description into one field, but at least it'll be on one line, which I find very helpful.

ContentLicense: CC BY-SA 2.5

Body:
I need to list all triggers in SQL Server database with table name and table's schema.

I'm almost there with this:

SELECT trigger_name = name, trigger_owner = USER_NAME(uid),table_schema = , table_name = OBJECT_NAME(parent_obj),
  isupdate = OBJECTPROPERTY( id, 'ExecIsUpdateTrigger'), isdelete = OBJECTPROPERTY( id, 'ExecIsDeleteTrigger'),
  isinsert = OBJECTPROPERTY( id, 'ExecIsInsertTrigger'), isafter = OBJECTPROPERTY( id, 'ExecIsAfterTrigger'),
  isinsteadof = OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger'),
  [disabled] = OBJECTPROPERTY(id, 'ExecIsTriggerDisabled')
FROM sysobjects INNER JOIN sysusers ON sysobjects.uid = sysusers.uid
WHERE type = 'TR'

I just need to get the table's schema also.

Body:
One difficulty is that the text, or description has line feeds. My clumsy kludge, to get it in something more tabular, is to add an HTML literal to the SELECT clause, copy and paste everything to notepad, save with an html extension, open in a browser, then copy and paste to a spreadsheet.
example

SELECT obj.NAME AS TBL,trg.name,sm.definition,'<br>'
FROM SYS.OBJECTS obj
LEFT JOIN (SELECT trg1.object_id,trg1.parent_object_id,trg1.name FROM sys.objects trg1 WHERE trg1.type='tr' AND trg1.name like 'update%') trg
 ON obj.object_id=trg.parent_object_id
LEFT JOIN (SELECT sm1.object_id,sm1.definition FROM sys.sql_modules sm1 where sm1.definition like '%suser_sname()%') sm ON trg.object_id=sm.object_id
WHERE obj.type='u'
ORDER BY obj.name;

you may still need to fool around with tabs to get the description into one field, but at least it'll be on one line, which I find very helpful.


问:
Calling a function in Django after saving a model
Context: I'm making a blog. This blog stores information on articles in a database via a Django model. I have a FileField in said model that takes an archive of all the assets that go with this file. I add articles through the admin site.

I want to call a function that unpacks this file immediately after the the object is saved to the model. Where would I write this function?

答:
You can use signal dispatcher included in Django.

```<code>from django.db.models.signals import post_save
from django.dispatch import receiver

from myapp.models import Blog

@receiver(post_save, sender=Blog)
def my_handler(sender, **kwargs):
    print('post save callback')
</code>```

See https://docs.djangoproject.com/en/stable/ref/signals/#post-save for more information.

Body:
You can use signal dispatcher included in Django.

from django.db.models.signals import post_save
from django.dispatch import receiver

from myapp.models import Blog

@receiver(post_save, sender=Blog)
def my_handler(sender, **kwargs):
    print('post save callback')

See https://docs.djangoproject.com/en/stable/ref/signals/#post-save for more information.

ContentLicense: CC BY-SA 4.0


问:
html5 drag and drop upload broken in chrome
I have been working on this bug for a while now , for some reason the drag and drop uploading I implemented on my site has not been working in chrome.  No error messages or anything.  Just when you try to drag a file over the designated area you get the mouse icon of the circle with the line through it.  So after testing and testing and testing I came to realize that even if I go to the html5 Official demo page for the drag and drop it does not work there either in Google Chrome.

Has anyone ran into this?  is there some type of security setting that got triggered in my Chrome browser that is preventing the drag-n-drop ??  I am concerned now that there may be other user that may run into this.  Currently I check if the user's browser if HTML5 compatable and then only offer the drag-n-drop option, if not I fall back to the choose a file button.  But now I'm learning that there may be a third case - which is mine now .  I have the newest version of Chrome , but it just for some reason started blocking drag-n-drop a few days ago. It used to work just fine.

EDIT

the  HTML5 drag-n-drop demo site

and I'm using Chrome Version 39.0.2171.65 m

答:
I found strangely enough (on version 57.0.2987.110) that closing all instances of chrome, opening task manager and making sure it is fully closed, then restarting it seemed to get the dropping working again.

I'm not sure of a fix when this is occurring but I did see a bug report about this at https://productforums.google.com/forum/#!topic/gmail/RgPdExhVPMs but it looks to me like a browser update (as this was originally posted in 2015 and likely isn't a problem anymore) would fix it right up.


问:
Any faster, simpler alternative to php preg_match
I am using cakephp 1.3 and I have textarea where users submit articles. On submit, I want to look into the article for certain key words and and add respective tags to the article.

I was thinking of preg_match, But preg_match pattern has to be string. So I would have to loop through an array(big).

Is there a easier way to plug in the keywords array for the pattern.

I appreciate all your help.

Thanks.

答:
Of course, you could try matching all the keywords using one single regexp, like /word1|word2|word3/, but I'm not sure it is what you are looking for. And also I think it would be quite heavy and resource-consuming.

Instead, you can try with a different approach, such as splitting the text into words and checking if the words are interesting or not. I would make use of str_word_count() using someting like:

```<code>$text = 'this is my string containing some words, some of the words in this string are duplicated, some others are not.';
$words_freq = array_count_values(str_word_count($text, 1));
</code>```

that splits the text into words and counts occurrences. Then you can check with in_array($keyword, $words_freq) or array_intersect(array_keys($words_freq), $my_keywords).

If you are not interested, as I guess, to the keywords case, you can strtolower() the whole text before proceeding with words splitting.

Of course, the only way to determine which approach is the best is to setup some testing, by running various search functions against some "representative" and quite long text and measuring the execution time and resource usage (try microtime(TRUE) and memory_get_peak_usage() to benchmark this).

EDIT: I cleaned up a bit the code and added a missing semi-colon :)

Body:
Of course, you could try matching all the keywords using one single regexp, like /word1|word2|word3/, but I'm not sure it is what you are looking for. And also I think it would be quite heavy and resource-consuming.

Instead, you can try with a different approach, such as splitting the text into words and checking if the words are interesting or not. I would make use of str_word_count() using someting like:

$text = 'this is my string containing some words, some of the words in this string are duplicated, some others are not.';
$words_freq = array_count_values(str_word_count($text, 1));

that splits the text into words and counts occurrences. Then you can check with in_array($keyword, $words_freq) or array_intersect(array_keys($words_freq), $my_keywords).

If you are not interested, as I guess, to the keywords case, you can strtolower() the whole text before proceeding with words splitting.

Of course, the only way to determine which approach is the best is to setup some testing, by running various search functions against some "representative" and quite long text and measuring the execution time and resource usage (try microtime(TRUE) and memory_get_peak_usage() to benchmark this).

EDIT: I cleaned up a bit the code and added a missing semi-colon :)


问:
Detect swipe using onTouchListener in ScrollView
I'm using the following code to detect swipe in my Activity:

```<code>getWindow().getDecorView().getRootView().setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                if(action == MotionEvent.ACTION_DOWN){

                    downX = event.getX();
                    downY = event.getY();
                    //mSwipeDetected = Action.None;
                    return true; // allow other events like Click to be processed
                }
                else if(action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL){
                     upX = event.getX();
                     upY = event.getY();

                     float deltaX = downX - upX;
                     float deltaY = downY - upY;

                    // horizontal swipe detection
                    if (Math.abs(deltaX) > MIN_DISTANCE) {
                        // left or right
                        if (deltaX < 0) {
                            Log.i(TAG, "Swipe Left to Right");
                            //mSwipeDetected = Action.LR;
                            onClickPrevQues(getWindow().getDecorView().getRootView());

                            return false;
                        }
                        if (deltaX > 0) {
                            Log.i(TAG, "Swipe Right to Left");
                            onClickNextQues(getWindow().getDecorView().getRootView());
                           // mSwipeDetected = Action.RL;
                            return false;
                        }
                    } else if (Math.abs(deltaY) > MIN_DISTANCE) { // vertical swipe
                                                                    // detection
                        // top or down
                        if (deltaY < 0) {
                            Log.i(TAG, "Swipe Top to Bottom");
                            //mSwipeDetected = Action.TB;
                            return false;
                        }
                        if (deltaY > 0) {
                            Log.i(TAG, "Swipe Bottom to Top");
                            //mSwipeDetected = Action.BT;
                            return false;
                        }
                    }
                    return false;
                }
                else if(action == MotionEvent.ACTION_MOVE){
                    return true;
                }
                return false;
            }
        });
</code>```

The code is working fine in case of LinearLayout. Surprisingly the same is not working in case if I wrap the Linearlayout inside ScrollView. What is the problem here?

Edit:

Layout:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<ScrollView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
<RelativeLayout
    android:id="@+id/RelativeLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:gravity="center_horizontal" >

    <RelativeLayout
        android:id="@+id/RelativeLayout2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:paddingBottom="0dp"
        android:paddingLeft="620dip"
        android:paddingTop="15dip" >

        <TextView
            android:id="@+id/text_unattempted"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:paddingTop="2dp"
            android:text="TextView"
            android:textColor="#b4cacc"
            android:textStyle="bold" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/LinearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/RelativeLayout2"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:paddingBottom="5dip"
        android:paddingTop="5dip" >

        <RelativeLayout
            android:id="@+id/relative_group"
            android:layout_width="fill_parent"
            android:layout_height="260dp"
            android:layout_marginLeft="20dp"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/txt_question_nu"
                android:layout_width="180dp"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:paddingTop="0dp"
                android:text="Question 1"
                android:textColor="#b4cacc"
                android:textSize="28dp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/question"
                android:layout_width="fill_parent"
                android:layout_height="400dp"
                android:layout_alignLeft="@+id/txt_question_nu"
                android:layout_below="@+id/txt_question_nu"
                android:layout_marginBottom="20dp"
                android:layout_marginTop="24dp"
                android:textColor="#000000"
                android:textSize="20dp" />

            <WebView
                android:id="@+id/questionimage"
                android:layout_width="wrap_content"
                android:layout_height="400dp"
                android:layout_alignLeft="@+id/txt_question_nu"
                android:layout_alignParentBottom="true"
                android:layout_below="@+id/txt_question_nu"
                android:layout_marginTop="24dp"
                android:fadeScrollbars="false"
                android:textColor="#000000"
                android:textSize="20dp"
                android:textStyle="bold" />

            <Button
                android:id="@+id/hintSolBtn"
                style="@style/HomeButton"
                android:layout_width="40dp"
                android:layout_height="30dp"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/txt_question_nu"
                android:background="#90b7bb"
                android:onClick="onClickHintSol"
                android:scaleType="centerInside"
                android:text="Hint"
                android:textColor="#ffffff" />
        </RelativeLayout>
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/LinearLayout2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="15dp"
        android:layout_below="@+id/radio_question_group"
        android:layout_alignParentLeft="true"
        android:orientation="horizontal"
        android:paddingTop="5dip" >

        <ImageButton
            android:id="@+id/abandonButton"
            style="@style/HomeButton"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_alignParentRight="true"
            android:layout_marginRight="45dp"
            android:onClick="onAbandonAssess"
            android:paddingLeft="6dp"
            android:scaleType="centerInside"
            android:src="@drawable/abandon"
            android:visibility="gone" />

        <Button
            android:id="@+id/submitBtn"
            android:layout_width="150dp"
            android:layout_height="50dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="63dp"
            android:background="#00b6c6"
            android:onClick="onSubmitAssess"
            android:paddingLeft="6dp"
            android:scaleType="centerInside"
            android:text="Submit"
            android:textColor="#ffffff"
            android:textSize="22dp" />

        <ImageButton
            android:id="@+id/prevBtn"
            style="@style/HomeButton"
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_weight="0.01"
            android:onClick="onClickPrevQues"
            android:scaleType="centerInside"
            android:src="@drawable/previous" />

        <ImageButton
            android:id="@+id/nextBtn"
            style="@style/HomeButton"
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/prevBtn"
            android:onClick="onClickNextQues"
            android:scaleType="centerInside"
            android:src="@drawable/next" />
    </RelativeLayout>

    <TextView
        android:id="@+id/answer_choices"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/LinearLayout1"
        android:layout_marginLeft="37dp"
        android:text="Answer Choices"
        android:textColor="#b4cacc"
        android:textSize="20dp"
        android:textStyle="bold" />

    <RadioGroup
        android:id="@+id/radio_question_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/answer_choices"
        android:layout_below="@+id/answer_choices" >

        <RadioButton
            android:id="@+id/answer1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:button="@drawable/radiostate"
            android:checked="false"
            android:layout_marginTop="10dp"
            android:hapticFeedbackEnabled="true"
            android:height="100dp"
            android:textColor="#000000" />

        <RadioButton
            android:id="@+id/answer2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:button="@drawable/radiostate"
            android:layout_marginTop="10dp"
            android:checked="false"
            android:hapticFeedbackEnabled="true"
            android:textColor="#000000" />

        <RadioButton
            android:id="@+id/answer3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:button="@drawable/radiostate"
            android:layout_marginTop="10dp"
            android:checked="false"
            android:hapticFeedbackEnabled="true"
            android:textColor="#000000" />

        <RadioButton
            android:id="@+id/answer4"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:button="@drawable/radiostate"
            android:layout_marginTop="10dp"
            android:checked="false"
            android:hapticFeedbackEnabled="true"
            android:textColor="#000000" />
    </RadioGroup>

    <!-- <ImageView
        android:id="@+id/pen_and_paper_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/pen_paper"
        android:visibility="gone" /> -->

    <ImageButton
        android:id="@+id/erase"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:layout_above="@+id/radio_question_group"
        android:layout_below="@+id/LinearLayout1"
        android:layout_toRightOf="@+id/answer_choices"
        android:onClick="onEraseChoice"
        android:src="@drawable/eraser"
        android:visibility="visible" />

</RelativeLayout>
</ScrollView>
</code>```

答:
```<code>mSlop = ViewConfiguration.get(getActivity()).getScaledTouchSlop();
boolean mIsSwiping = false;

public boolean onTouch(View v, MotionEvent event) {
    //Timber.d("onTouch, v.getId %d, event.getActionMasked %d", v.getId(), event.getActionMasked());
    switch (event.getActionMasked()) {
        case MotionEvent.ACTION_DOWN:
            mDownX = event.getX();
            mDownY = event.getY();
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_CANCEL:
            mIsSwiping = false;
            break;
        case MotionEvent.ACTION_MOVE:
            float deltaX = event.getX() - mDownX;
            float deltaY = event.getY() - mDownY;
            if (!mIsSwiping && Math.abs(deltaX) > mSlop && Math.abs(deltaY) < mSlop) {
                mIsSwiping = true;
                if (deltaX > 0) {
                    Timber.d("swipe from left to right, slop %d", mSlop);
                    // TODO:
                } else {
                    Timber.d("swipe from right to left");
                    // TODO:
                }
                return true;
            } else if (!mIsSwiping && Math.abs(deltaY) > mSlop) {
                mIsSwiping = true;
                Timber.d("swipe vertical");
                return true;
            }

    }
    return false;
}
</code>```

Body:
I'm using the following code to detect swipe in my Activity:

getWindow().getDecorView().getRootView().setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                if(action == MotionEvent.ACTION_DOWN){

                    downX = event.getX();
                    downY = event.getY();
                    //mSwipeDetected = Action.None;
                    return true; // allow other events like Click to be processed
                }
                else if(action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL){
                     upX = event.getX();
                     upY = event.getY();

                     float deltaX = downX - upX;
                     float deltaY = downY - upY;

                    // horizontal swipe detection
                    if (Math.abs(deltaX) > MIN_DISTANCE) {
                        // left or right
                        if (deltaX < 0) {
                            Log.i(TAG, "Swipe Left to Right");
                            //mSwipeDetected = Action.LR;
                            onClickPrevQues(getWindow().getDecorView().getRootView());

                            return false;
                        }
                        if (deltaX > 0) {
                            Log.i(TAG, "Swipe Right to Left");
                            onClickNextQues(getWindow().getDecorView().getRootView());
                           // mSwipeDetected = Action.RL;
                            return false;
                        }
                    } else if (Math.abs(deltaY) > MIN_DISTANCE) { // vertical swipe
                                                                    // detection
                        // top or down
                        if (deltaY < 0) {
                            Log.i(TAG, "Swipe Top to Bottom");
                            //mSwipeDetected = Action.TB;
                            return false;
                        }
                        if (deltaY > 0) {
                            Log.i(TAG, "Swipe Bottom to Top");
                            //mSwipeDetected = Action.BT;
                            return false;
                        }
                    }
                    return false;
                }
                else if(action == MotionEvent.ACTION_MOVE){
                    return true;
                }
                return false;
            }
        });

The code is working fine in case of LinearLayout. Surprisingly the same is not working in case if I wrap the Linearlayout inside ScrollView. What is the problem here?

Edit:

Layout:

    <?xml version="1.0" encoding="utf-8"?>
<ScrollView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
<RelativeLayout
    android:id="@+id/RelativeLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:gravity="center_horizontal" >

    <RelativeLayout
        android:id="@+id/RelativeLayout2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:paddingBottom="0dp"
        android:paddingLeft="620dip"
        android:paddingTop="15dip" >

        <TextView
            android:id="@+id/text_unattempted"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:paddingTop="2dp"
            android:text="TextView"
            android:textColor="#b4cacc"
            android:textStyle="bold" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/LinearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/RelativeLayout2"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:paddingBottom="5dip"
        android:paddingTop="5dip" >

        <RelativeLayout
            android:id="@+id/relative_group"
            android:layout_width="fill_parent"
            android:layout_height="260dp"
            android:layout_marginLeft="20dp"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/txt_question_nu"
                android:layout_width="180dp"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:paddingTop="0dp"
                android:text="Question 1"
                android:textColor="#b4cacc"
                android:textSize="28dp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/question"
                android:layout_width="fill_parent"
                android:layout_height="400dp"
                android:layout_alignLeft="@+id/txt_question_nu"
                android:layout_below="@+id/txt_question_nu"
                android:layout_marginBottom="20dp"
                android:layout_marginTop="24dp"
                android:textColor="#000000"
                android:textSize="20dp" />

            <WebView
                android:id="@+id/questionimage"
                android:layout_width="wrap_content"
                android:layout_height="400dp"
                android:layout_alignLeft="@+id/txt_question_nu"
                android:layout_alignParentBottom="true"
                android:layout_below="@+id/txt_question_nu"
                android:layout_marginTop="24dp"
                android:fadeScrollbars="false"
                android:textColor="#000000"
                android:textSize="20dp"
                android:textStyle="bold" />

            <Button
                android:id="@+id/hintSolBtn"
                style="@style/HomeButton"
                android:layout_width="40dp"
                android:layout_height="30dp"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/txt_question_nu"
                android:background="#90b7bb"
                android:onClick="onClickHintSol"
                android:scaleType="centerInside"
                android:text="Hint"
                android:textColor="#ffffff" />
        </RelativeLayout>
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/LinearLayout2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="15dp"
        android:layout_below="@+id/radio_question_group"
        android:layout_alignParentLeft="true"
        android:orientation="horizontal"
        android:paddingTop="5dip" >

        <ImageButton
            android:id="@+id/abandonButton"
            style="@style/HomeButton"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_alignParentRight="true"
            android:layout_marginRight="45dp"
            android:onClick="onAbandonAssess"
            android:paddingLeft="6dp"
            android:scaleType="centerInside"
            android:src="@drawable/abandon"
            android:visibility="gone" />

        <Button
            android:id="@+id/submitBtn"
            android:layout_width="150dp"
            android:layout_height="50dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="63dp"
            android:background="#00b6c6"
            android:onClick="onSubmitAssess"
            android:paddingLeft="6dp"
            android:scaleType="centerInside"
            android:text="Submit"
            android:textColor="#ffffff"
            android:textSize="22dp" />

        <ImageButton
            android:id="@+id/prevBtn"
            style="@style/HomeButton"
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_weight="0.01"
            android:onClick="onClickPrevQues"
            android:scaleType="centerInside"
            android:src="@drawable/previous" />

        <ImageButton
            android:id="@+id/nextBtn"
            style="@style/HomeButton"
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/prevBtn"
            android:onClick="onClickNextQues"
            android:scaleType="centerInside"
            android:src="@drawable/next" />
    </RelativeLayout>

    <TextView
        android:id="@+id/answer_choices"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/LinearLayout1"
        android:layout_marginLeft="37dp"
        android:text="Answer Choices"
        android:textColor="#b4cacc"
        android:textSize="20dp"
        android:textStyle="bold" />

    <RadioGroup
        android:id="@+id/radio_question_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/answer_choices"
        android:layout_below="@+id/answer_choices" >

        <RadioButton
            android:id="@+id/answer1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:button="@drawable/radiostate"
            android:checked="false"
            android:layout_marginTop="10dp"
            android:hapticFeedbackEnabled="true"
            android:height="100dp"
            android:textColor="#000000" />

        <RadioButton
            android:id="@+id/answer2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:button="@drawable/radiostate"
            android:layout_marginTop="10dp"
            android:checked="false"
            android:hapticFeedbackEnabled="true"
            android:textColor="#000000" />

        <RadioButton
            android:id="@+id/answer3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:button="@drawable/radiostate"
            android:layout_marginTop="10dp"
            android:checked="false"
            android:hapticFeedbackEnabled="true"
            android:textColor="#000000" />

        <RadioButton
            android:id="@+id/answer4"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:button="@drawable/radiostate"
            android:layout_marginTop="10dp"
            android:checked="false"
            android:hapticFeedbackEnabled="true"
            android:textColor="#000000" />
    </RadioGroup>

    <ImageButton
        android:id="@+id/erase"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:layout_above="@+id/radio_question_group"
        android:layout_below="@+id/LinearLayout1"
        android:layout_toRightOf="@+id/answer_choices"
        android:onClick="onEraseChoice"
        android:src="@drawable/eraser"
        android:visibility="visible" />

</RelativeLayout>
</ScrollView>


问:
ImportError: No module named googlemaps
I've installed this package via pip27 on macports. My OS is OSX El Capitan 10.11.6. My python install is 2.7.10.

I'm trying to run an example script that imports googlemaps module, but I keep getting that ImportError. I have a feeling that it's how pip installed it and the reason why python can't find it, but I'm relatively new to pip so I don't know where to start investigating.

I also tried googling for a fix but no dice. Any idea what's happening here?

Here's my code:

```<code>import googlemaps # can't import
import argparse
from datetime import datetime

# collect args for lat, long, # of addresses, radius of search
parser = argparse.ArgumentParser(description='Randomize addresses on Google Maps')
parser.add_argument('-lt', '--latitude')
parser.add_argument('-lng', '--longitude')
parser.add_argument('-n', '--count')
parser.add_argument('-r', '--radius')
args = parser.parse_args()

print('Results: ', vars(args))
</code>```

Error message:

```<code>Traceback (most recent call last):
  File "randomize_addresses.py", line 1, in <module>
    import googlemaps
ImportError: No module named googlemaps
</code>```

答: Found a fix. I uninstalled googlemaps via pip and then reinstalled using easy_install. Apparently OSX doesn't like pip. </p>

Title: ImportError: No module named googlemaps

Body:
I've installed this package via pip27 on macports. My OS is OSX El Capitan 10.11.6. My python install is 2.7.10.

I'm trying to run an example script that imports googlemaps module, but I keep getting that ImportError. I have a feeling that it's how pip installed it and the reason why python can't find it, but I'm relatively new to pip so I don't know where to start investigating.

I also tried googling for a fix but no dice. Any idea what's happening here?

Here's my code:

import googlemaps # can't import
import argparse
from datetime import datetime

# collect args for lat, long, # of addresses, radius of search
parser = argparse.ArgumentParser(description='Randomize addresses on Google Maps')
parser.add_argument('-lt', '--latitude')
parser.add_argument('-lng', '--longitude')
parser.add_argument('-n', '--count')
parser.add_argument('-r', '--radius')
args = parser.parse_args()

print('Results: ', vars(args))

Error message:

Traceback (most recent call last):
  File "randomize_addresses.py", line 1, in <module>
    import googlemaps
ImportError: No module named googlemaps


问:
Efficient checking of whether a point is inside a large number of triangles in 2D
I have implemented an algorithm to check whether a point is inside a triangle in 2D by calling the 1st algorithm in this question: how to determine if a point is inside a 2d triangle.

This algorithm works, but I think if I preprocess the triangle and use a smart data structure, I can make this efficient. I'm using about 10 million triangles. I think one way of making this fast is to compute bounding rectangles for the triangles and do a point in rectangle check, but I feel even this case can be made faster by making use of some data structure to only check for rectangles that are closeby.

Does such a data structure and algorithm exist?

答:
The classical approach from computational geometry is to triangulate and then do point location, but it's a lot easier to just use a k-d tree, putting triangles that intersect the partitioning line of an interior tree node in that node so that they can be checked on the way down to the leaves.

Constructing the k-d tree is a recursive process. Given a list of triangles and a coordinate to focus on (x or y, alternating with each layer), find a separating line that is vaguely in the middle, by sampling randomly, by taking a median, or by some combination or sampling and taking a median. Gather the triangles whose points are all strictly less than the separation coordinate and use them to construct the left subtree. Gather the triangles whose points are all strictly greater than the separation coordinate and use them to construct the right subtree. Store the remaining triangles (the ones that intersect the coordinate line) in the root.

To query, test whether the point belongs to any of the triangle in the root. Then, if the point is less than the separation coordinate, check the left subtree. If the point is greater, check the right.


问:
Programmatically adding root view to view controller does not position correctly
I am trying to add the root view and subviews to a viewcontroller programmatically, but the view is not filling to screen as expected:</p>

```<code>override func loadView() {
        self.view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
        self.view.backgroundColor = UIColor.blue
    }

    override func viewDidLoad() {

        let alertView = Bundle.main.loadNibNamed("CHRApptTakenAlertView", owner: self, options: nil)![0] as! CHRApptTakenAlertView

        self.view.translatesAutoresizingMaskIntoConstraints = false
        alertView.translatesAutoresizingMaskIntoConstraints = false

        self.view.addSubview(alertView)
        self.view.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0))
        self.view.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        alertView.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.width, multiplier: 1, constant: 350))
        alertView.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.height, multiplier: 1, constant: 250))

        alertView.closeBtn.addTarget(self, action: #selector(self.closeBtnTouch), for: UIControlEvents.touchUpInside)
    }
</code>```

答: Remove the line self.view.translatesAutoresizingMaskIntoConstraints = false, and call self.view.layoutIfNeeded() after the adding the constraints. </p>

Body:
I am trying to add the root view and subviews to a viewcontroller programmatically, but the view is not filling to screen as expected:

override func loadView() {
        self.view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
        self.view.backgroundColor = UIColor.blue
    }

    override func viewDidLoad() {

        let alertView = Bundle.main.loadNibNamed("CHRApptTakenAlertView", owner: self, options: nil)![0] as! CHRApptTakenAlertView

        self.view.translatesAutoresizingMaskIntoConstraints = false
        alertView.translatesAutoresizingMaskIntoConstraints = false

        self.view.addSubview(alertView)
        self.view.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0))
        self.view.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        alertView.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.width, multiplier: 1, constant: 350))
        alertView.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.height, multiplier: 1, constant: 250))

        alertView.closeBtn.addTarget(self, action: #selector(self.closeBtnTouch), for: UIControlEvents.touchUpInside)
    }


问:
What character is this in Access?
I have a user trying to export data into an XML file from Access and is getting an invalid XML error. We are looking at how to remove the invalid characters and ran across this field: .

This field is not the pipe bar, |. When I try and paste this field into Notepad++ its shows ENQ. It does not seem to be an invalid XML character based on Invalid Characters in XML.

Edit: It doesn't appear to show up, so here is a link to how it looks in my editor:

答:
Sometimes I find it necessary to hunt for the needle in the haystack - a character that doesn't display.  If you want to see what characters you may have in a string, you could try the following code.  It allows you to skip characters that are common...</p>

```<code>Dim YourString As String
Dim blnSkipNbr As Boolean
Dim blnSkipUC As Boolean
Dim blnSkipLC As Boolean
Dim blnSkipSpecial As Boolean
blnSkipNbr = True           ' Set to tru to not display numbers
blnSkipUC = True            ' Skip UC
blnSkipLC = True            ' Skip LC
blnSkipSpecial = True       ' Skip special

' 32-47 = Special (space, !, (), etc.)
' 48-57 = 0 to 9
' 65-90 = A to Z
' 97-122 = a to z

YourString = "Now is the time...!#$" & vbCrLf

For i = 1 To Len(YourString)
    char = Mid(YourString, i, 1)
    Do
    If blnSkipNbr = True And Asc(char) >= 48 And Asc(char) <= 57 Then Exit Do
    If blnSkipUC = True And Asc(char) >= 65 And Asc(char) <= 90 Then Exit Do
    If blnSkipLC = True And Asc(char) >= 97 And Asc(char) <= 122 Then Exit Do
    If blnSkipSpecial = True And Asc(char) >= 97 And Asc(char) <= 122 Then Exit Do
        Debug.Print "In position " & i & " of string: Char: " & ">" & char & "<" & vbTab & vbTab & "Asc(" & Asc(char) & ")"
        Exit Do
    Loop
Next i
</code>```

Title: What character is this in Access?

Body:
Sometimes I find it necessary to hunt for the needle in the haystack - a character that doesn't display.  If you want to see what characters you may have in a string, you could try the following code.  It allows you to skip characters that are common...

Dim YourString As String
Dim blnSkipNbr As Boolean
Dim blnSkipUC As Boolean
Dim blnSkipLC As Boolean
Dim blnSkipSpecial As Boolean
blnSkipNbr = True           ' Set to tru to not display numbers
blnSkipUC = True            ' Skip UC
blnSkipLC = True            ' Skip LC
blnSkipSpecial = True       ' Skip special

' 32-47 = Special (space, !, (), etc.)
' 48-57 = 0 to 9
' 65-90 = A to Z
' 97-122 = a to z

YourString = "Now is the time...!#$" & vbCrLf

For i = 1 To Len(YourString)
    char = Mid(YourString, i, 1)
    Do
    If blnSkipNbr = True And Asc(char) >= 48 And Asc(char) <= 57 Then Exit Do
    If blnSkipUC = True And Asc(char) >= 65 And Asc(char) <= 90 Then Exit Do
    If blnSkipLC = True And Asc(char) >= 97 And Asc(char) <= 122 Then Exit Do
    If blnSkipSpecial = True And Asc(char) >= 97 And Asc(char) <= 122 Then Exit Do
        Debug.Print "In position " & i & " of string: Char: " & ">" & char & "<" & vbTab & vbTab & "Asc(" & Asc(char) & ")"
        Exit Do
    Loop
Next i


问:
Auto remove class seconds after it becomes active
I have a script working so that the background image of a div switches at a certain distance from the top of the page. What I want is for it to switch back to the original after say 2 seconds.

The following removes the class 170px later:

```<code><script>
jQuery(document).scroll(function(){
var fromTopPx = 2800; // distance to trigger
var scrolledFromtop = jQuery(document).scrollTop();
if(scrolledFromtop > fromTopPx){
    jQuery('#image').addClass('scrolled');
}else{
    jQuery('#image').removeClass('scrolled');
}
var fromTopPx = 2970; // distance to trigger
var scrolledFromtop = jQuery(document).scrollTop();
if(scrolledFromtop > fromTopPx){
    jQuery('#image').removeClass('scrolled');
}
});
</script>
</code>```

but I was hoping for it to switch back automatically:

```<code><script>
jQuery(document).scroll(function(){
var fromTopPx = 2800; // distance to trigger
var scrolledFromtop = jQuery(document).scrollTop();
if(scrolledFromtop > fromTopPx){
    jQuery('#neediioneimg').addClass('scrolled');
}else{
    jQuery('#neediioneimg').removeClass('scrolled');
}
setTimeout(function(){
$('.scrolled').removeClass('scrolled');
},2000);
});
</script>
</code>```

I'm not sure about the setTimout part, does anyone have an idea?

答:
You can implement the same functionality using chained delays and queues.  This way you don't have to worry about rogue setTimeout functions that are missing a corresponding clearTimeout, and the removeClass is guaranteed to only occur on the DOM element you originally added the class to, because the removeClass action is applied to $(this).

Also, this logic will continue to fire for every scrolled pixel past the 2800 pixel mark.  This is probably not what you want.  So, an easy fix would be set the operator logic to an == rather than > within your if statement (see below).  But you may want to revise how you determine how far the user has scrolled and implement the functionality in a way that only fires once.

Something like this should work for your pause/auto-remove functionality:

```<code><script>
$(document).scroll(function(){
    var fromTopPx = 2800; // distance to trigger
    var scrolledFromtop = $(document).scrollTop();

    // also, I would change the > to ==, this way it only fires once.
    if(scrolledFromtop == fromTopPx){
        $('#neediioneimg').addClass('scrolled')
             .delay(2000) // pauses for n milliseconds
             .queue(function(next){
                 $(this).removeClass('scrolled');
                 next();
             });
     }

});
</script>
</code>```

Body:
I have a script working so that the background image of a div switches at a certain distance from the top of the page. What I want is for it to switch back to the original after say 2 seconds.

The following removes the class 170px later:

but I was hoping for it to switch back automatically:

I'm not sure about the setTimout part, does anyone have an idea?

Body:
You can implement the same functionality using chained delays and queues.  This way you don't have to worry about rogue setTimeout functions that are missing a corresponding clearTimeout, and the removeClass is guaranteed to only occur on the DOM element you originally added the class to, because the removeClass action is applied to $(this).

Also, this logic will continue to fire for every scrolled pixel past the 2800 pixel mark.  This is probably not what you want.  So, an easy fix would be set the operator logic to an == rather than > within your if statement (see below).  But you may want to revise how you determine how far the user has scrolled and implement the functionality in a way that only fires once.

Something like this should work for your pause/auto-remove functionality:

<script>
$(document).scroll(function(){
    var fromTopPx = 2800; // distance to trigger
    var scrolledFromtop = $(document).scrollTop();

    // also, I would change the > to ==, this way it only fires once.
    if(scrolledFromtop == fromTopPx){
        $('#neediioneimg').addClass('scrolled')
             .delay(2000) // pauses for n milliseconds
             .queue(function(next){
                 $(this).removeClass('scrolled');
                 next();
             });
     }

});
</script>


问:
Timer in VC++ for Non-GUI Applications
I want to test a code which is designed for running on a Microcontroller and it is platform independent.

Problem is I currently don't have any Embedded simulator (due to some damn reason!) and I want to test it... I am using Visual Studio 2008 (What a Pity!!).... Code is entirely in C but as VS 2008 doesn't support C, I have stored files as .cpp.... But No C++ concept is used!!

What all I require is a Timer which would generate Interrupt after every 1 millisecond!

And One more thing.... Can I configure something so that an Interrupt will be generated if I press certain key on Keyboard....

I don't want to make GUI. I searched for Timers and all were for MFC application.... If there isn't any option, I will make a rough MFC...

Regards!!

答: You can try the Boost Asio Timers too. If you don't have it setup, please refer here: Getting Started on MS Windows.</p>

Title: Timer in VC++ for Non-GUI Applications


问:
Leaflet, point very closer don't appear
I have been working with Leaflet and Tabletop.js. The main idea is put all the data in Google Spreadsheet and use Tabletop for reading that data and then show on Leaflet. Almost works fine, except for one issue: If the points are very closer (like 2 meters) I can't see two points, only the last one. There is some configuration for that?

When I created the map, i use this code:

```<code>    // Set view of Leaflet map based on screen size
    var layer = new L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
    if ($(window).width() < 626) {
    var map = new L.Map('map').setView([-35,-71],20);
    } else {
    var map = new L.Map('map').setView([-35,-71],20);
</code>```

Also, for reading the Google Spreadsheet I use

```<code>          // Group we will append our markers to
          if (window.location.hash === "#cluster") {
            // Set up cluster group
            var markers = new L.MarkerClusterGroup();
          } else {
            // Otherwise set up normal groupx`
            var markers = new L.LayerGroup();
          }

          // Google Docs spreadsheet key
          var spreadsheet_key = '1RBXvfL8A5OWKVShefgjkAlbikwnakpBzytz9fccuPzI';

          // Name of lat, long columns in Google spreadsheet
          var lat_column = 'latitude';
          var long_column = 'longitude';

          // Marker options
          var radius = 3;
          // Regular fill
          var fill_color = "#023858";
          var border_color = "#FFF";
          // Hover
          var fill_color_hover = "#FFF";
          var border_color_hover = "#333"

          var global_markers_data;

          // Function that creates our popup
          function generatePopup(content){
              // Generate header
            var popup_header = "<h4>" + toTitleCase(content['brewery']) + "</h4>"

            // Generate content
            var popup_content = '<table class="popup_table table">';
            popup_content += '<tr><td><strong>Address:</strong></td>';
            popup_content += '<td>' + content['address'] + '</td>';
            popup_content += '<tr><td><strong>City:</strong></td>';
            popup_content += '<td>' + content['city'] + '</td>';
            popup_content += '<tr><td><strong>Phone:</strong></td>';
            popup_content += '<td>' + content['phone'] + '</td>';
                popup_content += '<tr><td colspan="2"><strong><a href="http://' + content['website'] + '" target="_blank">Learn more</a></strong></td>';
            popup_content += '</tr></table>'

            return popup_header + popup_content;
          }

          // This goes through our JSON file and puts markers on map
          function loadMarkersToMap(markers_data) {
            // If we haven't captured the Tabletop data yet
            // We'll set the Tabletop data to global_markers_data
            if (global_markers_data !== undefined) {
                markers_data = global_markers_data;
            // If we have, we'll load global_markers_data instead of loading Tabletop again
            } else {
                global_markers_data = markers_data;
            }

            for (var num = 0; num < markers_data.length; num++) {
                // Capture current iteration through JSON file
                current = markers_data[num];

                // Add lat, long to marker
                var marker_location = new L.LatLng(current[lat_column], current[long_column]);

                // Determine radius of the circle by the value in total
                // radius_actual = Math.sqrt(current['total'] / 3.14) * 2.8;

                // Options for our circle marker
                var layer_marker = L.circleMarker(marker_location, {
                    radius: radius,
                    fillColor: fill_color,
                    color: border_color,
                    weight: 1,
                    opacity: 1,
                    fillOpacity: 0.8
                });

                // Generate popup
                layer_marker.bindPopup( generatePopup(current) );

                // Add events to marker
                (function (num){
                    // Must call separate popup(e) function to make sure right data is shown
                    function mouseOver(e) {
                        var layer_marker = e.target;
                        layer_marker.setStyle({
                            radius: radius + 1,
                            fillColor: fill_color_hover,
                            color: border_color_hover,
                            weight: 2,
                            opacity: 1,
                            fillOpacity: 1
                        });
                        // layer_marker.openPopup();
                    }

                    // What happens when mouse leaves the marker
                    function mouseOut(e) {
                        var layer_marker = e.target;
                        layer_marker.setStyle({
                            radius: radius + 1,
                            fillColor: fill_color,
                            color: border_color,
                            weight: 1,
                            opacity: 1,
                            fillOpacity: 0.8
                        });
                        // layer_marker.closePopup();
                    }

                    // Call mouseover, mouseout functions
                    layer_marker.on({
                        mouseover: mouseOver,
                        mouseout: mouseOut
                    });

                })(num)

                // Add to feature group
                markers.addLayer(layer_marker);
            }

            // Add feature group to map
            map.addLayer(markers);

            // Clear load text
            // $('.sidebar_text_intro').html('');
          };

          // Pull data from Google spreadsheet via Tabletop
          function initializeTabletopObjectMarkers(){
            Tabletop.init({
                key: spreadsheet_key,
                callback: loadMarkersToMap,
                simpleSheet: true,
                debug: false
              });
          }

          // Add JSON data to map
          // If not done with map-tabletop-geojson.js
          initializeTabletopObjectMarkers();
</code>```

Thanks from Chile

答:
The 2 coordinate pairs that you provided are about 3.6 meters apart.

var latLng1 = [-35.40665432600, -71.66499569600];
var latLng2 = [-35.4066848373, -71.66500860470];

L.latLng(latLng1).distanceTo(latLng2);
```

At their latitude, they are represented just a dozen pixels apart at zoom 20.

In this configuration, there is no issue in seeing them separately, even though they are still quite close and you have to zoom to level 20.

Demo: https://jsfiddle.net/3v7hd2vx/234/

If you use Leaflet.markercluster plugin, please note that the default clustering radius is 80px, so your 2 points will be merged in a common cluster even at zoom 20. You can use the "spiderfy" functionality of that plugin to see them separately, but not at their real position. Or simply decrease the clustering radius, at least from that zoom level. Or disable entirely clustering from that zoom level (see disableClusteringAtZoom option)

Title: Leaflet, point very closer don't appear

Body:
I have been working with Leaflet and Tabletop.js. The main idea is put all the data in Google Spreadsheet and use Tabletop for reading that data and then show on Leaflet. Almost works fine, except for one issue: If the points are very closer (like 2 meters) I can't see two points, only the last one. There is some configuration for that?

When I created the map, i use this code:

    // Set view of Leaflet map based on screen size
    var layer = new L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
    if ($(window).width() < 626) {
    var map = new L.Map('map').setView([-35,-71],20);
    } else {
    var map = new L.Map('map').setView([-35,-71],20);

Also, for reading the Google Spreadsheet I use

          // Group we will append our markers to
          if (window.location.hash === "#cluster") {
            // Set up cluster group
            var markers = new L.MarkerClusterGroup();
          } else {
            // Otherwise set up normal groupx`
            var markers = new L.LayerGroup();
          }

          // Google Docs spreadsheet key
          var spreadsheet_key = '1RBXvfL8A5OWKVShefgjkAlbikwnakpBzytz9fccuPzI';

          // Name of lat, long columns in Google spreadsheet
          var lat_column = 'latitude';
          var long_column = 'longitude';

          // Marker options
          var radius = 3;
          // Regular fill
          var fill_color = "#023858";
          var border_color = "#FFF";
          // Hover
          var fill_color_hover = "#FFF";
          var border_color_hover = "#333"

          var global_markers_data;

          // Function that creates our popup
          function generatePopup(content){
              // Generate header
            var popup_header = "
" + toTitleCase(content['brewery']) + "
"

            // Generate content
            var popup_content = '
';
            popup_content += '
Address:	';
            popup_content += '' + content['address'] + '	';
            popup_content += '
City:	';
            popup_content += '' + content['city'] + '	';
            popup_content += '
Phone:	';
            popup_content += '' + content['phone'] + '	';
                popup_content += '
Learn more	';
            popup_content += '

'

            return popup_header + popup_content;
          }

          // This goes through our JSON file and puts markers on map
          function loadMarkersToMap(markers_data) {
            // If we haven't captured the Tabletop data yet
            // We'll set the Tabletop data to global_markers_data
            if (global_markers_data !== undefined) {
                markers_data = global_markers_data;
            // If we have, we'll load global_markers_data instead of loading Tabletop again
            } else {
                global_markers_data = markers_data;
            }

            for (var num = 0; num < markers_data.length; num++) {
                // Capture current iteration through JSON file
                current = markers_data[num];

                // Add lat, long to marker
                var marker_location = new L.LatLng(current[lat_column], current[long_column]);

                // Determine radius of the circle by the value in total
                // radius_actual = Math.sqrt(current['total'] / 3.14) * 2.8;

                // Options for our circle marker
                var layer_marker = L.circleMarker(marker_location, {
                    radius: radius,
                    fillColor: fill_color,
                    color: border_color,
                    weight: 1,
                    opacity: 1,
                    fillOpacity: 0.8
                });

                // Generate popup
                layer_marker.bindPopup( generatePopup(current) );

                // Add events to marker
                (function (num){
                    // Must call separate popup(e) function to make sure right data is shown
                    function mouseOver(e) {
                        var layer_marker = e.target;
                        layer_marker.setStyle({
                            radius: radius + 1,
                            fillColor: fill_color_hover,
                            color: border_color_hover,
                            weight: 2,
                            opacity: 1,
                            fillOpacity: 1
                        });
                        // layer_marker.openPopup();
                    }

                    // What happens when mouse leaves the marker
                    function mouseOut(e) {
                        var layer_marker = e.target;
                        layer_marker.setStyle({
                            radius: radius + 1,
                            fillColor: fill_color,
                            color: border_color,
                            weight: 1,
                            opacity: 1,
                            fillOpacity: 0.8
                        });
                        // layer_marker.closePopup();
                    }

                    // Call mouseover, mouseout functions
                    layer_marker.on({
                        mouseover: mouseOver,
                        mouseout: mouseOut
                    });

                })(num)

                // Add to feature group
                markers.addLayer(layer_marker);
            }

            // Add feature group to map
            map.addLayer(markers);

            // Clear load text
            // $('.sidebar_text_intro').html('');
          };

          // Pull data from Google spreadsheet via Tabletop
          function initializeTabletopObjectMarkers(){
            Tabletop.init({
                key: spreadsheet_key,
                callback: loadMarkersToMap,
                simpleSheet: true,
                debug: false
              });
          }

          // Add JSON data to map
          // If not done with map-tabletop-geojson.js
          initializeTabletopObjectMarkers();

Thanks from Chile

Body:
The 2 coordinate pairs that you provided are about 3.6 meters apart.

var latLng1 = [-35.40665432600, -71.66499569600];
var latLng2 = [-35.4066848373, -71.66500860470];

L.latLng(latLng1).distanceTo(latLng2);

At their latitude, they are represented just a dozen pixels apart at zoom 20.

In this configuration, there is no issue in seeing them separately, even though they are still quite close and you have to zoom to level 20.

Demo: https://jsfiddle.net/3v7hd2vx/234/

If you use Leaflet.markercluster plugin, please note that the default clustering radius is 80px, so your 2 points will be merged in a common cluster even at zoom 20. You can use the "spiderfy" functionality of that plugin to see them separately, but not at their real position. Or simply decrease the clustering radius, at least from that zoom level. Or disable entirely clustering from that zoom level (see disableClusteringAtZoom option)


问:
Lombok added but getters and setters not recognized in Intellij IDEA
I am using IntelliJ IDEA on ubuntu. I added lombok.jar into my project and installed the Lombok plugin for IDEA. I have access to the annotations but the getters and setters aren't generated. I get the same errors I would get if I tried accessing a getter or setter method that doesn't exist. What could I be missing?

答:
Go to File > Settings > Plugins.

Click on Browse repositories...

Search for Lombok Plugin.

Click on Install plugin.

Restart Android Studio.


答:
awk to the rescue!

```<code>awk                     '{v=$7^2 + $8^2 + $9^2}
  !($6 in a) ||  v<a[$6] {a[$6]=v; line[$6]=$0}
  END                    {for(k in line) print line[k]}' file

-3.79 43 18.6279 16.5936 -1.33 CAN  1 10 100
10.51 -66 1.71937 -9.93556 1.21 CAS 4 40 400
-9.41 38 17.751 16.7401 -0.25 CASC  12 20 400
</code>```

for finding the minimum you need to set the initial values, here we're checking whether the key has been encountered before or not.

this is the critical condition  !($6 in a) ||  v<a[$6] we set/change the minimum value if it's the first encountered for the key (i.e. initial value to compare the rest against) or less than the current minimum.

Title: refering to a line containing a column-wise calculated value

Body:
I want to print, for selected pattern, only the rows with minimum value for the sum of squared columns 7,8 and 9 (as in script below, which I run as $ script.sh patterns.txt). My script prints the last row for the certain pattern and I would like to print only the line that contains minimum. How could I refer to that line?

Below is input and desired output.

while IFS='' read -r line || [[ -n "$line" ]]; do
grep -E -wr $line input.txt| awk '{ min=($7^2)+($8^2)+($9^2);} FNR==NR  {if (($7^2)+($8^2)+($9^2)<=min) min=($7^2)+($8^2)+($9^2);} END {print $0}' >> output.txt
done < "$1"

input

-3.79 43 18.6279 16.5936 -1.33 CAN  1 10 100
-3.79 43 18.6279 16.5937 -1.33 CAN  2 20 200
10.51 -66 1.71937 -9.93556 1.20 CAS 5 50 500
10.51 -66 1.71937 -9.93556 1.21 CAS 4 40 400
10.51 -66 1.71937 -9.93555 1.20 CAS 6 60 600
-9.41 38 17.751 16.7401 -0.25 CASC  12 20 400
-9.41 38 17.751 16.7401 -0.53 CASC  13 50 500
-9.41 38 17.751 16.7401 -0.25 CASC  12 20 400

output

-3.79 43 18.6279 16.5936 -1.33 CAN  1 10 100
10.51 -66 1.71937 -9.93556 1.21 CAS 4 40 400
-9.41 38 17.751 16.7401 -0.25 CASC  12 20 400

Body:
awk to the rescue!

awk                     '{v=$7^2 + $8^2 + $9^2}
  !($6 in a) ||  v<a[$6] {a[$6]=v; line[$6]=$0}
  END                    {for(k in line) print line[k]}' file

-3.79 43 18.6279 16.5936 -1.33 CAN  1 10 100
10.51 -66 1.71937 -9.93556 1.21 CAS 4 40 400
-9.41 38 17.751 16.7401 -0.25 CASC  12 20 400

for finding the minimum you need to set the initial values, here we're checking whether the key has been encountered before or not.

this is the critical condition  !($6 in a) ||  v<a[$6] we set/change the minimum value if it's the first encountered for the key (i.e. initial value to compare the rest against) or less than the current minimum.


问:
Bootstrap grid push and pull issue
I'm using Bootstrap for the first time.
Trying to learned the grid-system of push and pull.

```<code><header>
    <!-- Main component for a primary marketing message or call to action -->

    <div class ="container">
        <div class = "row">
            <div class = "col-xs-12 col-sm-8">
                <h1>RSisdtorante con Fusion</h1>
                <p style="padding:40px;"></p>
                <p>We take inspiration from the World's best cuisines, and create a unique fusion experience. Our lipsmacking creations will tickle your culinary senses!</p>
            </div >
            <div class = "col-xs-12 col-sm-4">
                <h1> hello brother</h1>

            </div>
        </div>
    </div>
</header>
</code>```

It does not change the html page at all.
is it necessary to include whole code to look at the problem?

答:
Check out this example from the bootstrap documentation: http://getbootstrap.com/css/#grid-example-mixed

The way you are using the grid classes, your divs will be full-width on xs screens, but on sm screens, the top div will be two-thirds width and the second will be one third width. Anything bigger than a small screen will be reflect this division.

If you are using Chrome, open the Developer Tools and resize your page, making it smaller, and you will see the change.

Bootstrap has a different class syntax for push and pull, read the syntax here: http://getbootstrap.com/css/#grid-column-ordering

Title: Bootstrap grid push and pull issue

Body:
I'm using Bootstrap for the first time.
Trying to learned the grid-system of push and pull.

RSisdtorante con Fusion

We take inspiration from the World's best cuisines, and create a unique fusion experience. Our lipsmacking creations will tickle your culinary senses!

 hello brother

It does not change the html page at all.
is it necessary to include whole code to look at the problem?


问:
PHP and Python static methods in objects, two different worlds...?
i'm php coder, trying to get into python world, and it's very hard for me.

Biggest enjoy of static methods in php is automatic builder of instance. No need to declare object, if you needed it once, in every file (or with different constructor params , in one line)

```<code><?php
class Foo {
    function __constructor__(){
        $this->var = 'blah';
    }
   public static function aStaticMethod() {
       return $this->var;
   }
}

echo Foo::aStaticMethod();
?>
</code>```

we can call constructor from static method don't we? and we can access everything in class as it would be simple method ... we can even have STATIC CONSTRUCTOR in php class and call it like so: Object::construct()->myMethod(); (to pass different params every time)

but not in python???? @staticmethod makes method in class a simple function that doesn't see totally anything ??

```<code>class socket(object):

def __init__(self):
    self.oclass = otherclass()
    print 'test' # does this constructor called at all when calling static method??

@staticmethod
def ping():
    return self.oclass.send('PING') # i can't access anything!!!

print Anidb.ping()
</code>```

I can't access anything from that god damned static method, it's like a standalone function or something like this..??

Maybe I'm using the wrong decorator? Maybe there's something like php offers with static methods in python?

1) Please tell why static methods is isolated
2) Please tell me how to make the same behavior like php static methods have.
3) Please tell me alternative practical use of this, if php static methods behavior is a bad thing

P.s. the goal of all this to write totally less code as much as possible.
P.p.s Heavy commenting of sample code is appreciated

Thank you.

答:
static methods in PHP are not as you believe, they can't access to instance members. No $this! with them.

```<code><?php
class Foo {

    public static $var = 'foo ';

    function __construct(){
        echo 'constructing ';
        $this->var = 'blah ';
    }

    public function aMethod() {
        return $this->var;
    }
    public static function aStaticMethod() {
        #return $this->$var;  -> you can't do that,
        # $this can be accessed only in instance methods, not static
        return self::$var;
    }
}

$foo = new Foo();
echo $foo->aMethod();

echo Foo::aStaticMethod();

?>
</code>```

Python has three kind of methods in objects static methods are like functions defined ouside classes, the only use to put them in object is to keep them with the class as helper functions. class methods can access only to variables defined in the class (decorator @classmethod). This is more or less what PHP calls static members or methods. The first parameter of such methods sould be cls, and content of class can be accessed through cls. Normal methods must get self as first parameter and are the only ones to be able to access to instance members.

If you want several objects of the same type you definitely need instances, and the other types are not what you are looking for. If you only have one instance of an object, you could use class methods instead (or PHP static methods).

But in most case you should not bother doing that if you don't know why and just stick with instances of objects and normal methods, doing otherwise is premature optimization and your code is likely to bite you later because of the many restrictions you introduce.

Body:
i'm php coder, trying to get into python world, and it's very hard for me.

Biggest enjoy of static methods in php is automatic builder of instance. No need to declare object, if you needed it once, in every file (or with different constructor params , in one line)

<?php
class Foo {
    function __constructor__(){
        $this->var = 'blah';
    }
   public static function aStaticMethod() {
       return $this->var;
   }
}

echo Foo::aStaticMethod();
?>

we can call constructor from static method don't we? and we can access everything in class as it would be simple method ... we can even have STATIC CONSTRUCTOR in php class and call it like so: Object::construct()->myMethod(); (to pass different params every time)

but not in python???? @staticmethod makes method in class a simple function that doesn't see totally anything ??

class socket(object):

def __init__(self):
    self.oclass = otherclass()
    print 'test' # does this constructor called at all when calling static method??

@staticmethod
def ping():
    return self.oclass.send('PING') # i can't access anything!!!

print Anidb.ping()

I can't access anything from that god damned static method, it's like a standalone function or something like this..??

Maybe I'm using the wrong decorator? Maybe there's something like php offers with static methods in python?

1) Please tell why static methods is isolated
2) Please tell me how to make the same behavior like php static methods have.
3) Please tell me alternative practical use of this, if php static methods behavior is a bad thing

P.s. the goal of all this to write totally less code as much as possible.
P.p.s Heavy commenting of sample code is appreciated

Thank you.

Body:
static methods in PHP are not as you believe, they can't access to instance members. No $this! with them.

<?php
class Foo {

    public static $var = 'foo ';

    function __construct(){
        echo 'constructing ';
        $this->var = 'blah ';
    }

    public function aMethod() {
        return $this->var;
    }
    public static function aStaticMethod() {
        #return $this->$var;  -> you can't do that,
        # $this can be accessed only in instance methods, not static
        return self::$var;
    }
}

$foo = new Foo();
echo $foo->aMethod();

echo Foo::aStaticMethod();

?>

Python has three kind of methods in objects static methods are like functions defined ouside classes, the only use to put them in object is to keep them with the class as helper functions. class methods can access only to variables defined in the class (decorator @classmethod). This is more or less what PHP calls static members or methods. The first parameter of such methods sould be cls, and content of class can be accessed through cls. Normal methods must get self as first parameter and are the only ones to be able to access to instance members.

If you want several objects of the same type you definitely need instances, and the other types are not what you are looking for. If you only have one instance of an object, you could use class methods instead (or PHP static methods).

But in most case you should not bother doing that if you don't know why and just stick with instances of objects and normal methods, doing otherwise is premature optimization and your code is likely to bite you later because of the many restrictions you introduce.


问:
Update statement with joins
I must create migration to update question image attribute but i need to check some attributes from other tables, my schema looks like this:

```<code>question {
id,
name,
groupId,
imageUrl -> i need to update this
}

group {
id,
name,
quizId
}

quiz {
id,
name,
type -> where type is 'History'
}
</code>```

And i need to update attribute imageUrl from table question WHERE quiz type is for example 'History', i'm not sure how i can join this tables when using UPDATE. I tried something like this but it's not working like i want.

```<code>UPDATE question SET image_url = 'pathToImage' FROM quiz q WHERE q.type = 'History'
</code>```

答:
So this is best solution that i came up with, and it worked perfectly for my migration.

```<code>UPDATE question SET image_url = 'https://path_to_image.com' WHERE id IN (SELECT q.id FROM question q
            JOIN group AS g ON q.groupi_id = g.id
            JOIN quiz AS qu ON qu.id = g.quiz_id
            WHERE qu.type = 'Lifestyle')
</code>```

So basically i update image_url to all questions with ID's in sub query, and this is easiest way to do this.

Title: Update statement with joins

Body:
I must create migration to update question image attribute but i need to check some attributes from other tables, my schema looks like this:

question {
id,
name,
groupId,
imageUrl -> i need to update this
}

group {
id,
name,
quizId
}

quiz {
id,
name,
type -> where type is 'History'
}

And i need to update attribute imageUrl from table question WHERE quiz type is for example 'History', i'm not sure how i can join this tables when using UPDATE. I tried something like this but it's not working like i want.

UPDATE question SET image_url = 'pathToImage' FROM quiz q WHERE q.type = 'History'

Body:
So this is best solution that i came up with, and it worked perfectly for my migration.

UPDATE question SET image_url = 'https://path_to_image.com' WHERE id IN (SELECT q.id FROM question q
            JOIN group AS g ON q.groupi_id = g.id
            JOIN quiz AS qu ON qu.id = g.quiz_id
            WHERE qu.type = 'Lifestyle')

So basically i update image_url to all questions with ID's in sub query, and this is easiest way to do this.


问:
populate expandable listview from sqlite database
This is my first time here in this site. I already did searched the web on how to populate sqlite database into expandable listview but i failed.

I follow
these steps on how to create an expandable listview and modify some codes to make it dynamic.

Here is my modified code. This is only to set parent text on expandable listview:

```<code>public void setGroupParents() {

    String selectQuery = "select * from " + DbHelper.TABLE_NAME + " ORDER BY "+DbHelperTablon.KEY_FNAME+" ASC ";
    SQLiteDatabase db = mHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
        do {
            parentItems.add(cursor.getString(1));
        } while (cursor.moveToNext());
    }

    cursor.close();
    db.close();
    return;
}
</code>```

When i tried to run the emulator, the program crashed.

I am a newbie in android development and i need any help from you experts.. Thanks in advance.

Oh.. im sorry. This is the results of my LogCat... This is only the error portion..

03-12 07:25:10.059: ERROR/AndroidRuntime(367): FATAL EXCEPTION: main
  03-12 07:25:10.059: ERROR/AndroidRuntime(367): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Sample/com.Sample.MainListview}: java.lang.NullPointerException
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1622)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.os.Handler.dispatchMessage(Handler.java:99)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.os.Looper.loop(Looper.java:123)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.app.ActivityThread.main(ActivityThread.java:3647)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at java.lang.reflect.Method.invokeNative(Native Method)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at java.lang.reflect.Method.invoke(Method.java:507)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at dalvik.system.NativeStart.main(Native Method)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367): Caused by: java.lang.NullPointerException
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at com.Sample.MainListview.setGroupParents(MainListview.java:56)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at com.Sample.MainListview.onCreate(MainListview.java:39)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     ... 11 more
  03-12 07:25:12.428: ERROR/InputDispatcher(59): channel '40703be0 com.Sample/com.Sample.Drawer (server)' ~ Consumer closed input channel or an error occurred.  events=0x8
  03-12 07:25:12.428: ERROR/InputDispatcher(59): channel '40703be0 com.Sample/com.Sample.Drawer (server)' ~ Channel is unrecoverably broken and will be disposed!

答: well i guess if you initiate the database object outside your class your problem might be solved...</p>

Body:
This is my first time here in this site. I already did searched the web on how to populate sqlite database into expandable listview but i failed.

I follow
these steps on how to create an expandable listview and modify some codes to make it dynamic.

Here is my modified code. This is only to set parent text on expandable listview:

public void setGroupParents() {

    String selectQuery = "select * from " + DbHelper.TABLE_NAME + " ORDER BY "+DbHelperTablon.KEY_FNAME+" ASC ";
    SQLiteDatabase db = mHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
        do {
            parentItems.add(cursor.getString(1));
        } while (cursor.moveToNext());
    }

    cursor.close();
    db.close();
    return;
}

When i tried to run the emulator, the program crashed.

I am a newbie in android development and i need any help from you experts.. Thanks in advance.

Oh.. im sorry. This is the results of my LogCat... This is only the error portion..

03-12 07:25:10.059: ERROR/AndroidRuntime(367): FATAL EXCEPTION: main
  03-12 07:25:10.059: ERROR/AndroidRuntime(367): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Sample/com.Sample.MainListview}: java.lang.NullPointerException
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1622)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.os.Handler.dispatchMessage(Handler.java:99)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.os.Looper.loop(Looper.java:123)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.app.ActivityThread.main(ActivityThread.java:3647)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at java.lang.reflect.Method.invokeNative(Native Method)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at java.lang.reflect.Method.invoke(Method.java:507)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at dalvik.system.NativeStart.main(Native Method)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367): Caused by: java.lang.NullPointerException
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at com.Sample.MainListview.setGroupParents(MainListview.java:56)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at com.Sample.MainListview.onCreate(MainListview.java:39)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
  03-12 07:25:10.059: ERROR/AndroidRuntime(367):     ... 11 more
  03-12 07:25:12.428: ERROR/InputDispatcher(59): channel '40703be0 com.Sample/com.Sample.Drawer (server)' ~ Consumer closed input channel or an error occurred.  events=0x8
  03-12 07:25:12.428: ERROR/InputDispatcher(59): channel '40703be0 com.Sample/com.Sample.Drawer (server)' ~ Channel is unrecoverably broken and will be disposed!