问:
Exception- Writing exception to parcel
This is a small assignment to insert simple text data to sqlite database. I have used SQLiteOpenHelper class for this and used given code.
I've found some similiar questions here but not the exact same. Please help me out. Here is the exception-

```<code>11-14 21:59:17.786 5746-5763/? E/DatabaseUtils: Writing exception to parcel
                                            java.lang.SecurityException: Neither user 10169 nor current process has android.permission.READ_PROFILE.
                                                at android.app.ContextImpl.enforce(ContextImpl.java:1921)
                                                at android.app.ContextImpl.enforceCallingOrSelfPermission(ContextImpl.java:1950)
                                                at android.content.ContextWrapper.enforceCallingOrSelfPermission(ContextWrapper.java:600)
                                                at com.android.providers.contacts.ProfileProvider.enforceReadPermission(ProfileProvider.java:54)
                                                at com.android.providers.contacts.ProfileProvider.query(ProfileProvider.java:84)
                                                at com.android.providers.contacts.ContactsProvider2.query(ContactsProvider2.java:5066)
                                                at android.content.ContentProvider$Transport.query(ContentProvider.java:214)
                                                at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112)
                                                at android.os.Binder.execTransact(Binder.java:446)
</code>```

I've used following permissions in my AndroidManifest.XML file:

```<code><uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.Manifest.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

this is my DBHelper class-

```<code>public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "CANDIDATES";
public static final String TABLE_NAME = "CANDIDATES_TABLE";
public static final String NAME = "NAME";
public static final String AGE = "AGE";
public static final String QUAL = "QUALIFICATION";
public static final String SALARY = "SALARY";
public static final String ADD = "ADDRESS";
public static final String DES = "DESCRIPTION";
Context context;

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
    this.context=context;
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table "+ TABLE_NAME +" ("+NAME+" TEXT,"+AGE+" INTEGER,"+QUAL+" TEXT,"+SALARY+" INTEGER,"+ADD+" TEXT,"+DES+" TEXT )");

}

public boolean insertData(String name,int age,String qual,int salary, String add, String des){
    SQLiteDatabase db=this.getWritableDatabase();
    ContentValues contentValues=new ContentValues();
    contentValues.put(NAME,name);
    contentValues.put(AGE,age);
    contentValues.put(QUAL,qual);
    contentValues.put(SALARY,salary);
    contentValues.put(ADD,add);
    contentValues.put(DES,des);
    long result=db.insert(TABLE_NAME,null,contentValues);
    Log.v("check",name+age+""+qual+salary+""+add+des);
    if(result==-1){
        return false;
    }
    else return true;
}

public Cursor getData(){
    SQLiteDatabase db=this.getWritableDatabase();
    Cursor cursor=db.rawQuery("Select * from"+TABLE_NAME,null);
    return cursor;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);
}
</code>```

}

答:
You need to add this line to your manifest:

```<code><uses-permission android:name="android.permission.READ_PROFILE"/>
</code>```

Title: Exception- Writing exception to parcel

Body:
This is a small assignment to insert simple text data to sqlite database. I have used SQLiteOpenHelper class for this and used given code.
I've found some similiar questions here but not the exact same. Please help me out. Here is the exception-

11-14 21:59:17.786 5746-5763/? E/DatabaseUtils: Writing exception to parcel
                                            java.lang.SecurityException: Neither user 10169 nor current process has android.permission.READ_PROFILE.
                                                at android.app.ContextImpl.enforce(ContextImpl.java:1921)
                                                at android.app.ContextImpl.enforceCallingOrSelfPermission(ContextImpl.java:1950)
                                                at android.content.ContextWrapper.enforceCallingOrSelfPermission(ContextWrapper.java:600)
                                                at com.android.providers.contacts.ProfileProvider.enforceReadPermission(ProfileProvider.java:54)
                                                at com.android.providers.contacts.ProfileProvider.query(ProfileProvider.java:84)
                                                at com.android.providers.contacts.ContactsProvider2.query(ContactsProvider2.java:5066)
                                                at android.content.ContentProvider$Transport.query(ContentProvider.java:214)
                                                at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112)
                                                at android.os.Binder.execTransact(Binder.java:446)

I've used following permissions in my AndroidManifest.XML file:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.Manifest.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

this is my DBHelper class-

public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "CANDIDATES";
public static final String TABLE_NAME = "CANDIDATES_TABLE";
public static final String NAME = "NAME";
public static final String AGE = "AGE";
public static final String QUAL = "QUALIFICATION";
public static final String SALARY = "SALARY";
public static final String ADD = "ADDRESS";
public static final String DES = "DESCRIPTION";
Context context;

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
    this.context=context;
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table "+ TABLE_NAME +" ("+NAME+" TEXT,"+AGE+" INTEGER,"+QUAL+" TEXT,"+SALARY+" INTEGER,"+ADD+" TEXT,"+DES+" TEXT )");

}

public boolean insertData(String name,int age,String qual,int salary, String add, String des){
    SQLiteDatabase db=this.getWritableDatabase();
    ContentValues contentValues=new ContentValues();
    contentValues.put(NAME,name);
    contentValues.put(AGE,age);
    contentValues.put(QUAL,qual);
    contentValues.put(SALARY,salary);
    contentValues.put(ADD,add);
    contentValues.put(DES,des);
    long result=db.insert(TABLE_NAME,null,contentValues);
    Log.v("check",name+age+""+qual+salary+""+add+des);
    if(result==-1){
        return false;
    }
    else return true;
}

public Cursor getData(){
    SQLiteDatabase db=this.getWritableDatabase();
    Cursor cursor=db.rawQuery("Select * from"+TABLE_NAME,null);
    return cursor;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);
}

}

Body:
You need to add this line to your manifest:

<uses-permission android:name="android.permission.READ_PROFILE"/>


来源: stackexchange

问:
Custom SVG directive inside button Component
I created a simple Directive that can be added to an  tag :

```<code><i svg-icon="menu"></i>
</code>```

It takes the name of the SVG file (in the exemple: menu.svg). Wherever I use it, it's works perfectly, the icon is correctly shown, except inside a <button> Component :

```<code><button ion-button menuToggle>
    <i svg-icon="menu"></i>
</button>
</code>```

In this context, the icon is not displayed.

Here is the content the SvgIconDirective :

```<code>import ...

@Directive({
    selector: '[svg-icon]'
})
export class SvgIconDirective implements OnInit {

    @Input('svg-icon') name: string;
    @Input() class: string;

    constructor(
        private el: ElementRef,
        private http: Http
    ) { }

    ngOnInit() {
        this.http.get(`assets/icon/ic_${this.name}.svg`).map(response => response.text()).subscribe(data => {
            let element = $(this.el.nativeElement);

            const id = element.attr('id');
            const className = element.attr('class');

            let newElement = $('<div />').html(data).find('svg');

            if (typeof id !== 'undefined') {
                newElement.attr('id', id);
            }
            if (typeof className !== 'undefined') {
                newElement.addClass(className);
            }

            $(this.el.nativeElement).replaceWith(newElement);
        });
    }
}
</code>```

And the DOM render inside <button> tag :

```<code><button ion-button="" menutoggle="" class="disable-hover bar-buttons bar-buttons-md bar-button bar-button-md bar-button-default bar-button-default-md bar-button-menutoggle bar-button-menutoggle-md" ng-reflect-menu-toggle="" style="transition: none;">
    <span class="button-inner">
        <svg version="1.1" id="Calque_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 52.4 44.1" style="enable-background:new 0 0 52.4 44.1;" xml:space="preserve">
            <style type="text/css">
                .ic_menu .st0{fill:#444444;}
            </style>
            <g class="ic_menu">
                <g transform="translate(312, 312)">
                    <path class="st0" d="M-259.6-312H-312v6.4h52.4V-312z"/>
                </g>
                <g transform="translate(312, 312)">
                    <path class="st0" d="M-259.6-293.1H-312v6.4h52.4V-293.1z"/>
                </g>
                <g transform="translate(312, 312)">
                    <path class="st0" d="M-259.6-274.3H-312v6.4h52.4V-274.3z"/>
                </g>
            </g>
        </svg>
    </span>
    <div class="button-effect">
    </div>
</button>
</code>```

答:
I found a solution by simply replacing the <button ion-button ...></button> with a div :

```<code><div class="CustomClass" menuToggle>
    <i svg-icon="menu"></i>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I created a simple Directive that can be added to an  tag :

It takes the name of the SVG file (in the exemple: menu.svg). Wherever I use it, it's works perfectly, the icon is correctly shown, except inside a <button> Component :

<button ion-button menuToggle>

</button>

In this context, the icon is not displayed.

Here is the content the SvgIconDirective :

import ...

@Directive({
    selector: '[svg-icon]'
})
export class SvgIconDirective implements OnInit {

    @Input('svg-icon') name: string;
    @Input() class: string;

    constructor(
        private el: ElementRef,
        private http: Http
    ) { }

    ngOnInit() {
        this.http.get(`assets/icon/ic_${this.name}.svg`).map(response => response.text()).subscribe(data => {
            let element = $(this.el.nativeElement);

            const id = element.attr('id');
            const className = element.attr('class');

            let newElement = $('
').html(data).find('svg');

            if (typeof id !== 'undefined') {
                newElement.attr('id', id);
            }
            if (typeof className !== 'undefined') {
                newElement.addClass(className);
            }

            $(this.el.nativeElement).replaceWith(newElement);
        });
    }
}

And the DOM render inside <button> tag :

<button ion-button="" menutoggle="" class="disable-hover bar-buttons bar-buttons-md bar-button bar-button-md bar-button-default bar-button-default-md bar-button-menutoggle bar-button-menutoggle-md" ng-reflect-menu-toggle="" style="transition: none;">

        <svg version="1.1" id="Calque_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 52.4 44.1" style="enable-background:new 0 0 52.4 44.1;" xml:space="preserve">

            <g class="ic_menu">
                <g transform="translate(312, 312)">
                    <path class="st0" d="M-259.6-312H-312v6.4h52.4V-312z"/>
                </g>
                <g transform="translate(312, 312)">
                    <path class="st0" d="M-259.6-293.1H-312v6.4h52.4V-293.1z"/>
                </g>
                <g transform="translate(312, 312)">
                    <path class="st0" d="M-259.6-274.3H-312v6.4h52.4V-274.3z"/>
                </g>
            </g>
        </svg>

</button>

Body:
I found a solution by simply replacing the <button ion-button ...></button> with a div :

<div class="CustomClass" menuToggle>
    <i svg-icon="menu"></i>
</div>


问:
Plotting weights vs iteration of a neural network
I would like to build a deep learning visualization tool.

But i'm stuck on the plot of weights vs iteration. Typically, I want to do this: mean magnitude weights vs iteration.

This photo is taken from this website visualization tool.
If I understand well, the document says that this is the log of the mean magnitude of the weights.

So, for each layer of my neural network, I will have a curve?
But I'm not sure if the formula to compute one point of one curve is : mean magnitude formula.

Where w1, w2, ... wn are the weights of one layer given a specified iteration.

Thank you for your help!

答:
Yes, each layer will have its own curve. Maybe an important point to recognize when building a deep learning visualization tool is why would someone want to visualize mean magnitude weight vs iteration.

The answer is: to see if the model is overfitting. Each layer of the model will converge (hopefully, not guaranteed) to some fixed point magnitude. The magnitude of each layer will be different based on the type of layer, the size of the model, etc. As such, it is only interesting to view the mean magnitude on a per layer basis. If the magnitude of a layer (especially the last) begins getting large, then the network is likely overfitting to its training data.

To answer the question about the formula, the goal is the find the average (mean) weight of every weight in that layer. So yes, sum up the weights for a layer, divide by the number of weights in that layer, and maybe take the log of that to make the scale easier to read (though that last is a design decision more than it is a mathematical decision, if anything we would assume that the weights are gaussian distribution and a natural log would make more sense than log base 10).


问:
Value types inherit from System.Object...why?

Possible Duplicates:

  Is everything in .NET an object?

  How do ValueTypes derive from Object (ReferenceType) and still be ValueTypes?

Hi,
I just do not get it. System.Object is (I think) reference type but all data types in .NET inherit from it. Also value types do as well. I do not understand it - value type has its value on the stack but its inherited from Object?
Hope anyone could help me to understand

答:
You are correct that, while Object is a reference type, value types do inherit from it implicitly, as stated on msdn's reference for Value Types (according to the reference, they technically inherit from the ValueType class, which in turn inherits from Object.

C# made a special case for this so value types can benefit from Object's methods (like ToString) and properties. Also, this way, you can treat value types just like other reference types--nothing stopping you from plugging in an int inside an array of Objects.

ContentLicense: CC BY-SA 2.5


问:
What is the use of component without VOB (Clearcase UCM)?
I was told to create component in UCM.

How would you explain a difference between component and VOB to a beginner?

Also It asks two option.

Components in VOB and Components without VOB.

What is the use of having Component without VOB?

答:
I don't think the question is answered. VonC described two types of VOBs can be created, a single component VOB and multi-component VOB, to store the files. The question however is asking what's the use of creating a component w/o a VOB, one of the options when you create a component.

This type of rootless components are normally used to store the composite baseline. I am not aware of other usages.

I found this post because today I got an issue with my IIB projects. When loading dependency projects from another component, IIB toolkit will complain the dependency project is not from the same root directory (due to from different components in CC). This is really an IIB toolkit issue, but I am looking for a way to resolve this from CC.


问:
using the typedef keyword with a struct
What exactly is the purpose of using a typedef together with a struct and giving it two names, often one in capital letters?

Today I was looking at a winsock tutorial and came across the struct definition below.

```<code>// IPv4 AF_INET sockets:
struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

typedef struct in_addr {
  union {
    struct {
      u_char s_b1,s_b2,s_b3,s_b4;
    } S_un_b;
    struct {
      u_short s_w1,s_w2;
    } S_un_w;
    u_long S_addr;
  } S_un;
} IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;

struct sockaddr {
    unsigned short    sa_family;    // address family, AF_xxx
    char              sa_data[14];  // 14 bytes of protocol address
};
</code>```

What exactly does this line do?

IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;

答: You use typedef to create an alias for the struct type, so that you don't have to type it out fully the next time you want to use it. If you didn't have the typedef, any time you want to use in_addr you would have to declare it as struct in_addr. The typedef allows you to declare it as IN_ADDR. When the typedefed name does not have an asterisk, it creates an alias for the type, and a name preceded by an asterisk, as in *IN_ADDR creates an alias for a pointer to the type, so you can write PIN_ADDR instead of struct in_addr*.

Title: using the typedef keyword with a struct

Body:
What exactly is the purpose of using a typedef together with a struct and giving it two names, often one in capital letters?

Today I was looking at a winsock tutorial and came across the struct definition below.

// IPv4 AF_INET sockets:
struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

typedef struct in_addr {
  union {
    struct {
      u_char s_b1,s_b2,s_b3,s_b4;
    } S_un_b;
    struct {
      u_short s_w1,s_w2;
    } S_un_w;
    u_long S_addr;
  } S_un;
} IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;

struct sockaddr {
    unsigned short    sa_family;    // address family, AF_xxx
    char              sa_data[14];  // 14 bytes of protocol address
};

What exactly does this line do?

IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;


问:
Boolean Algebra - How to Simplify
Working in JS and just started learning about boolean algebra. Wondering if there is a way to simplify this expression:

(!variableOne || !variableTwo)

I recall hearing something about how two 'nots' means you can change the sign, but I'm not seeing much about this when I google 'boolean algebra'.

Thanks!

答:
Late answer but to put further explanation:

The negation of an and statement is logically equivalent to the or statement in which each component is negated.

Symbolically:
!(A && B) = !A || !B

The negation of an or statement is logically equivalent to the and statement in which each component is negated.

Symbolically:
 !(A || B) = !A && !B

In your case you had used !variableOne || !variableTwo so it's equivalent to the first Law !(variableOne && variableTwo) == !variableOne || !variableTwo.

Title: Boolean Algebra - How to Simplify


问:
RequestParam value in spring MVC to be case insensitive
Am sending data from JSP to controller using query string.

My controller is annotation driven.

The value of the the request parameter should be case-insensitive.

The method which i use for welcome page is

```<code>public String welcome(@RequestParam("orgID") String orgID, ModelMap model)
</code>```

The request parameter "orgID" should be case insensitive. How to do this ?.

I should be able to give the query-string as "orgid" or "orgId". The parameter should be completely case-insensitive. Looking for your help friends.

Thanks in Advance :-)

答:
It might be nice for Spring to support this, but I can also understand why they wouldn't since it could result in a weakening of an interface contract between a supplier and consumer.  In the meantime, here's a fairly straightforward way to take the first value using the parameter name regardless of its case.</p>

```<code>    String myVal = null;
    for (String pname : request.getParameterMap().keySet() ) {
        if ( pname != null && pname.toLowerCase().equals("your_lc_pname") ) {
            for (String v : request.getParameterValues(pname) ) {
                // do something with your value(s)
            }
        }
    }
</code>```

Body:
Am sending data from JSP to controller using query string.

My controller is annotation driven.

The value of the the request parameter should be case-insensitive.

The method which i use for welcome page is

public String welcome(@RequestParam("orgID") String orgID, ModelMap model)

The request parameter "orgID" should be case insensitive. How to do this ?.

I should be able to give the query-string as "orgid" or "orgId". The parameter should be completely case-insensitive. Looking for your help friends.

Thanks in Advance :-)

Body:
It might be nice for Spring to support this, but I can also understand why they wouldn't since it could result in a weakening of an interface contract between a supplier and consumer.  In the meantime, here's a fairly straightforward way to take the first value using the parameter name regardless of its case.

    String myVal = null;
    for (String pname : request.getParameterMap().keySet() ) {
        if ( pname != null && pname.toLowerCase().equals("your_lc_pname") ) {
            for (String v : request.getParameterValues(pname) ) {
                // do something with your value(s)
            }
        }
    }


问:
Hashing Access time with multi variable key
Suppose a dictionary has 2 variable keys instead of 1 like

```<code>dictionary[3,5] = Something
dictionry[1,2] = Something
dictionary[3,1] = Something
</code>```

Would the search time still be O(1).In case I need to find if dictionary[1,5] exists would it yield constant time?

Thanks in advance.

答: Yes. This is not new. In usual, you can have a dictionary with string keys. If you see string as an array of characters, you have a list of chars as key. So, in the same situation, you can say your dictionary works in O(1) too (if length of string is constant).

Body:
Suppose a dictionary has 2 variable keys instead of 1 like

dictionary[3,5] = Something
dictionry[1,2] = Something
dictionary[3,1] = Something

Would the search time still be O(1).In case I need to find if dictionary[1,5] exists would it yield constant time?

Thanks in advance.


问:
automatically update php output through browsers
I have a live table where it's possible to edit/save realtime data like google spreadsheet and I'm looking to display the updated datas through other browsers.
Actually this is my code:

```<code>  // DB AND USERS VERIFICATION....
  <table>
  <tbody>
<?php foreach($datas as $k => $v){ ?>
   <tr>
     <td contenteditable="true" id="<?php echo $v['my_id']; ?>" ></td>
     <td contenteditable="true" name="myData"> SOME TEXT </td>
   </tr>
</code>```

Then I'm using jquery to save the contenteditable text to DB.
My question now is how can I automatically output the updated "TD" text through different browsers without having to refresh page?
Is there anyway to do it directly with PHP?
Thank you for your Help!!!

答:
Is there anyway to do it directly with PHP?

Unfortunately not. PHP is a server side scripted language. You will need a client side scripted language to do this, and that usually means JavaScript, or other alternatives.

Getting Started with AJAX

Or you could use Websockets with HTML5.

Or you could use Webhooks with HTTP POST.

Here is a comparison of them.

Body:
I have a live table where it's possible to edit/save realtime data like google spreadsheet and I'm looking to display the updated datas through other browsers.
Actually this is my code:

  // DB AND USERS VERIFICATION....

<?php foreach($datas as $k => $v){ ?>

     <td contenteditable="true" id="<?php echo $v['my_id']; ?>" >
      SOME TEXT

Then I'm using jquery to save the contenteditable text to DB.
My question now is how can I automatically output the updated "TD" text through different browsers without having to refresh page?
Is there anyway to do it directly with PHP?
Thank you for your Help!!!


问:
How to query List of Maps in DynamoDb
I have of the non-primary key column in DynamoDb which is of List type as this:

```<code>logs=[{
m1:{"key1":"pair1",
"key2":"pair2",
"timestamp":2189321.212
},
m2:{"key1":"pair1",
"key2":"pair2",
"timestamp":2112321.212
},
...
}]
</code>```

So problem statement is I want to get a list of items, which are 30 days old.
I am not able to query this one.

答:
From DynamoDB you cannot query based on the values of document types like you desire. Not unless you want to scan the whole table and do it in memory which I'm guessing you don't.

An alternate solution would be for you to index your data in AWS Elasticsearch service as well as DynamoDB. You can feed ES the full JSON and it will index every property so that you can run the kind of queries your are talking about. Obviously this is a project of its own but you have that option if you want to keep the JSON structure you currently have in DynamoDB.

Title: How to query List of Maps in DynamoDb

Body:
I have of the non-primary key column in DynamoDb which is of List type as this:

logs=[{
m1:{"key1":"pair1",
"key2":"pair2",
"timestamp":2189321.212
},
m2:{"key1":"pair1",
"key2":"pair2",
"timestamp":2112321.212
},
...
}]

So problem statement is I want to get a list of items, which are 30 days old.
I am not able to query this one.


问:
Python Regex Date
I'm trying create a regex that looks for all dates in the format MM-DD-YYYY, and this is what I came up with so far:

```<code>dateRegex = re.compile(r'''
            (0[1-9]|1[0-2])                  # Month
            -
            (10|20|[0-2][1-9]|3[01])         # Day: not [0-2][0-9]|3[01] to avoid 00 matching
            -
            ((198[0-9]|20(0[0-9]|1[0-6])'''  # Year: matches 1980 - 2016
            , re.VERBOSE)
</code>```

Is there an easier way that allows me to create a range of numbers? And say I wanted to create one that only allows legal dates (for example, June shouldn't have 31 days), would the easiest way just be to match the months with different days, like:

```<code>((01|03|05|07|08|10|12)-(31 day regex pattern)-(year regex) # for 31-day months
|
(04|06|09|11)-(30 day regex pattern)-(year regex)           # for 30-day months
|
02-(regex depending on leap year))                          # 28 or 29 days
</code>```

Not even sure how I would do the February besides putting all leaps years and 29 days together, and the remaining years with 28 days.

Title: Python Regex Date

Body:
I'm trying create a regex that looks for all dates in the format MM-DD-YYYY, and this is what I came up with so far:

dateRegex = re.compile(r'''
            (0[1-9]|1[0-2])                  # Month
            -
            (10|20|[0-2][1-9]|3[01])         # Day: not [0-2][0-9]|3[01] to avoid 00 matching
            -
            ((198[0-9]|20(0[0-9]|1[0-6])'''  # Year: matches 1980 - 2016
            , re.VERBOSE)

Is there an easier way that allows me to create a range of numbers? And say I wanted to create one that only allows legal dates (for example, June shouldn't have 31 days), would the easiest way just be to match the months with different days, like:

((01|03|05|07|08|10|12)-(31 day regex pattern)-(year regex) # for 31-day months
|
(04|06|09|11)-(30 day regex pattern)-(year regex)           # for 30-day months
|
02-(regex depending on leap year))                          # 28 or 29 days

Not even sure how I would do the February besides putting all leaps years and 29 days together, and the remaining years with 28 days.

Body:
I find the below RE working fine for Date in the following format;

14-11-2017

14.11.2017

14|11|2017

It can accept year from 2000-2099

Please do not forget to add $ at the end, if not it accept 14-11-201 or 20177

date="13-11-2017"

x=re.search("^([1-9] |1[0-9]| 2[0-9]|3[0-1])(.|-)([1-9] |1[0-2])(.|-|)20[0-9][0-9]$",date)

x.group()

Output:

13-11-2017


问:
Rebind DOM Event with jQuery
This is purely a theoretical question so I'm not looking for alternative solutions.

Is there some way of getting the default handler to do something like this

```<code>var defaultHandler = $("#test").click;
$('#test').unbind('click');
$('#test').bind('click', defaultHandler);
</code>```

答:
You can access the .data('events') object, which is used to store all event handler information:

```<code>$(document).ready(function() {
    var $test = $('#test');

    $test.bind('click', function() {
        alert('default handler');
    });

    var storedClick = $test.data('events').click[0].handler;

    $test.unbind('click');

    $('#restore').click(function() {
        $test.bind('click', storedClick);
    });
});
</code>```

See this in action: http://www.jsfiddle.net/76GPF/

Remember, the events object is holding Arrays, so in the real world you should store the complete array information. I just stored the very first handler in this example.

Title: Rebind DOM Event with jQuery

Body:
This is purely a theoretical question so I'm not looking for alternative solutions.

Is there some way of getting the default handler to do something like this

var defaultHandler = $("#test").click;
$('#test').unbind('click');
$('#test').bind('click', defaultHandler);

Body:
You can access the .data('events') object, which is used to store all event handler information:

$(document).ready(function() {
    var $test = $('#test');

    $test.bind('click', function() {
        alert('default handler');
    });

    var storedClick = $test.data('events').click[0].handler;

    $test.unbind('click');

    $('#restore').click(function() {
        $test.bind('click', storedClick);
    });
});

See this in action: http://www.jsfiddle.net/76GPF/

Remember, the events object is holding Arrays, so in the real world you should store the complete array information. I just stored the very first handler in this example.


问:
I have problems with my app alignment when i launch it
When I launch my app on my device every thing get ordered as right to left but when I launch it on the emulator it stays the way it is. I know that the problem is that my device's main language is Hebrew (and Hebrew is a language where you write from right to left ) and the emulator's language is English.

picture 1

picture 2

I want it to be the same in all languages.

Thanks in advance

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mahmood.morsecode.TextToMorse">

<EditText
    android:id="@+id/editText"
    android:layout_width="0dp"
    android:layout_height="180dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:ems="10"
    android:inputType="textMultiLine"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<EditText
    android:id="@+id/editText2"
    android:layout_width="0dp"
    android:layout_height="180dp"
    android:layout_marginBottom="80dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:ems="10"
    android:inputType="textMultiLine"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent" />

<LinearLayout
    android:layout_width="344dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="BackSpace" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button" />

    <Button
        android:id="@+id/button7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Space" />
</LinearLayout>

</android.support.constraint.ConstraintLayout>
</code>```

答:
Check your AndroidManifest.xml. By default, Android Studio will add this attribute to the <application> tag:

```<code>android:supportsRtl="true"
</code>```

Change that to false, and layout direction based on language will be ignored.

Documentation: https://developer.android.com/guide/topics/manifest/application-element.html#supportsrtl

ContentLicense: CC BY-SA 4.0

Body:
When I launch my app on my device every thing get ordered as right to left but when I launch it on the emulator it stays the way it is. I know that the problem is that my device's main language is Hebrew (and Hebrew is a language where you write from right to left ) and the emulator's language is English.

picture 1

picture 2

I want it to be the same in all languages.

Thanks in advance

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mahmood.morsecode.TextToMorse">

<EditText
    android:id="@+id/editText"
    android:layout_width="0dp"
    android:layout_height="180dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:ems="10"
    android:inputType="textMultiLine"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<EditText
    android:id="@+id/editText2"
    android:layout_width="0dp"
    android:layout_height="180dp"
    android:layout_marginBottom="80dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:ems="10"
    android:inputType="textMultiLine"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent" />

<LinearLayout
    android:layout_width="344dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="BackSpace" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button" />

    <Button
        android:id="@+id/button7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Space" />
</LinearLayout>

</android.support.constraint.ConstraintLayout>

Body:
Check your AndroidManifest.xml. By default, Android Studio will add this attribute to the <application> tag:

android:supportsRtl="true"

Change that to false, and layout direction based on language will be ignored.

Documentation: https://developer.android.com/guide/topics/manifest/application-element.html#supportsrtl


问:
How to use docker passed environment variable in log4j2?
I have a spring-boot based application that uses log4j2.xml in a dockerized environment.

When I launch the docker I pass -e "LOG4J_PATH=/tmp/app.log" to specify where the logs should go to.

Next, in the log4j2.xml I use fileName="${env:LOG4J_PATH}" but this doesn't work. I searched the web for hours and thus tried double $ and tried sys instead of env... nothing.

This System.getenv("LOG4J_PATH") and (new EnvironmentLookup()).lookup("LOG4J_PATH") work fine, so I know that the variable is being passed to the running image ok, but from some reason the log4j doesn't seem to pick it up.

If I run this not via a docker and set the LOG4J_PATH environment variable in my .bash_profile it works fine so this is something between docker and log4j.

What am I doing wrong?

答:
I believe you need to change the key value structure a bit for your passed environment variable.  Can you try </p>

```<code>docker run -e LOG4J_PATH='/tmp/app.log'
</code>```

Body:
I believe you need to change the key value structure a bit for your passed environment variable.  Can you try

docker run -e LOG4J_PATH='/tmp/app.log'


问:
Scheme lambda and let errors
A beginner in scheme.. trying out the following code to test the equivalence of lambda and let

```<code>(lambda (x y)
  (+ x y)
  10
  (* x 2))

(let ((k 10)
      (y (* 2 k)))
  (+ k y))
</code>```

the output is

```<code>#<procedure>
. . k: undefined;
 cannot reference undefined identifier
>
</code>```

Any help would be appreciated

答:
FWIW, the equivalent lambda construction to

```<code>(let ((k 10))
  (let ((y (* 2 k)))
    (+ k y)))
</code>```

is

```<code>((lambda (k)
   ((lambda (y)
      (+ k y))
    (* 2 k)))
 10)
</code>```

Title: Scheme lambda and let errors

Body:
A beginner in scheme.. trying out the following code to test the equivalence of lambda and let

(lambda (x y)
  (+ x y)
  10
  (* x 2))

(let ((k 10)
      (y (* 2 k)))
  (+ k y))

the output is

#<procedure>
. . k: undefined;
 cannot reference undefined identifier
>

Any help would be appreciated

Body:
FWIW, the equivalent lambda construction to

(let ((k 10))
  (let ((y (* 2 k)))
    (+ k y)))

is

((lambda (k)
   ((lambda (y)
      (+ k y))
    (* 2 k)))
 10)


问:
Update variables for each row in a dataframe
I have a dataframe that looks like this:

```<code>chr    alleles    position
2      [A/T]      123456
3      [C/T]      5678910
8      [A/G]      8765435334
</code>```

I'd like to load each row into variables such as:

```<code>library('BSgenome.Hsapiens.UCSC.hg19')
chr <- 'chr2'
alleles <- '[T/C]'
position <- 123456
offset <- 60
</code>```

and then use them iteratively in:

```<code>seq <- paste(getSeq(Hsapiens,chr,position-offset,position-1),
+              alleles,
+              getSeq(Hsapiens,chr,position+1,position+offset),
+              sep='')
</code>```

and finally have the output as another dataframe containing:

```<code>chr    allele    position     seq
2      [A/T]      123456      "ACTTGGAGATTTGGAGGAAGCTCCAGAGAGAGAGAGGCTTCCCAGCGTGGACTTGAAAGA[A/T]GAAACCAGCATAGATAGCACCGTGAATGGTGAGTTGGAATTCCTGGTTTCACTTTTGTTA"
</code>```

I have read this thread, but appreciate a solution that doesnt require indices!

答:
I think you should be using a map()-type function from purrr.

I don't have access to your getSeq() function or your Hsapiens data, but something like this should work if I understand your problem correctly.

```<code># define helper function to simply syntax and make code readable
seq_extractor <- function(data, chr, position, alleles, offset=60){
    pre_seq <- getSeq(data, chr, position-offset, position-1)
    post_seq <- getSeq(data, chr, position+1, position+offset)
    paste(pre_seq, alleles, post_seq, sep='')
}

# use pmap_chr() to map your function onto your existing data
df %>%
    mutate(seq = pmap_chr(list(chr, alleles, position),
                          ~seq_extractor(Hsapiens, ..1, ..3, ..2))
</code>```

Body:
I have a dataframe that looks like this:

chr    alleles    position
2      [A/T]      123456
3      [C/T]      5678910
8      [A/G]      8765435334

I'd like to load each row into variables such as:

library('BSgenome.Hsapiens.UCSC.hg19')
chr <- 'chr2'
alleles <- '[T/C]'
position <- 123456
offset <- 60

and then use them iteratively in:

seq <- paste(getSeq(Hsapiens,chr,position-offset,position-1),
+              alleles,
+              getSeq(Hsapiens,chr,position+1,position+offset),
+              sep='')

and finally have the output as another dataframe containing:

chr    allele    position     seq
2      [A/T]      123456      "ACTTGGAGATTTGGAGGAAGCTCCAGAGAGAGAGAGGCTTCCCAGCGTGGACTTGAAAGA[A/T]GAAACCAGCATAGATAGCACCGTGAATGGTGAGTTGGAATTCCTGGTTTCACTTTTGTTA"

I have read this thread, but appreciate a solution that doesnt require indices!

Body:
I think you should be using a map()-type function from purrr.

I don't have access to your getSeq() function or your Hsapiens data, but something like this should work if I understand your problem correctly.

# define helper function to simply syntax and make code readable
seq_extractor <- function(data, chr, position, alleles, offset=60){
    pre_seq <- getSeq(data, chr, position-offset, position-1)
    post_seq <- getSeq(data, chr, position+1, position+offset)
    paste(pre_seq, alleles, post_seq, sep='')
}

# use pmap_chr() to map your function onto your existing data
df %>%
    mutate(seq = pmap_chr(list(chr, alleles, position),
                          ~seq_extractor(Hsapiens, ..1, ..3, ..2))


答:
This creates the types IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR, which are synonymous with struct in_addr which in turn refers to the structure definintion given.  This practice is is useful when you want to typedef a structure with a self reference, but don't want to add the struct keyword before each declaration::

```<code>typedef struct _SomeStruct_t{
    int                    someVal;
    struct _SomeStruct_t  *pNext;
} SomeStruct_t;

SomeStruct_t  gSomeStruct;
</code>```

You can't set pNext to be a pointer to SomeStruct_t because it hasn't been defined at that point, so you use struct _SomeStruct_t instead.

Title: using the typedef keyword with a struct

Body:
What exactly is the purpose of using a typedef together with a struct and giving it two names, often one in capital letters?

Today I was looking at a winsock tutorial and came across the struct definition below.

// IPv4 AF_INET sockets:
struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

typedef struct in_addr {
  union {
    struct {
      u_char s_b1,s_b2,s_b3,s_b4;
    } S_un_b;
    struct {
      u_short s_w1,s_w2;
    } S_un_w;
    u_long S_addr;
  } S_un;
} IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;

struct sockaddr {
    unsigned short    sa_family;    // address family, AF_xxx
    char              sa_data[14];  // 14 bytes of protocol address
};

What exactly does this line do?

IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;

Body:
This creates the types IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR, which are synonymous with struct in_addr which in turn refers to the structure definintion given.  This practice is is useful when you want to typedef a structure with a self reference, but don't want to add the struct keyword before each declaration::

typedef struct _SomeStruct_t{
    int                    someVal;
    struct _SomeStruct_t  *pNext;
} SomeStruct_t;

SomeStruct_t  gSomeStruct;

You can't set pNext to be a pointer to SomeStruct_t because it hasn't been defined at that point, so you use struct _SomeStruct_t instead.


问:
Apache Drill | How to configure Spill on disk
I doing R&D on Apache drill by querying on 20 million data on 8GB RAM with MySQL and Mongo data source and getting out of memory exception.

Then,tried to configure Spill on disk by following configuration in drill-override.conf.

```<code>drill.exec: {
 cluster-id: "APDCluster1",
 zk.connect: "192.168.1.16:2181",
 spill: {
  directories: ["/data/enliven/installations/ApacheD/drill/spill"],
  fs: "file:///"
 }
 sort: {
  external: {
   batch.size: 4000,
   spill: {
    batch.size: 4000,
    group.size: 100,
    threshold: 200,
    directories: ["/data/enliven/installations/ApacheD/drill/spill"],
    fs: "file:///"
   }
  }
 },
 hashagg: {
  spill: {
   directories: ["/data/enliven/installations/ApacheD/drill/spill"],
   fs: "file:///"
  }
 }
}
</code>```

Still am getting same out of memory exception .

Any one can help me on this.

答:
According to http://www.openkb.info/2015/05/drill-workshop-spill.html, to test the effectiveness of a Drill Spill, you should reduce the provided memory amount to e.g. 20 MB:

```<code>alter session set `planner.memory.max_query_memory_per_node`=20971520;
</code>```

Then test a query and check the file system if the spill is working at all.

Also, it might be wise to check if you provided enough heap in the first place if you have 8 GB available (from https://drill.apache.org/docs/configuring-drill-memory/):

The drill-env.sh file contains the following options:

```<code>#export DRILL_HEAP=${DRILL_HEAP:-"4G”}
#export DRILL_MAX_DIRECT_MEMORY=${DRILL_MAX_DIRECT_MEMORY:-"8G"}
</code>```

To customize memory limits, uncomment the line needed and change the setting:

```<code>export DRILL_HEAP=${DRILL_HEAP:-"<limit>”}
export DRILL_MAX_DIRECT_MEMORY=${DRILL_MAX_DIRECT_MEMORY:-“<limit>"}
</code>```

Body:
I doing R&D on Apache drill by querying on 20 million data on 8GB RAM with MySQL and Mongo data source and getting out of memory exception.

Then,tried to configure Spill on disk by following configuration in drill-override.conf.

drill.exec: {
 cluster-id: "APDCluster1",
 zk.connect: "192.168.1.16:2181",
 spill: {
  directories: ["/data/enliven/installations/ApacheD/drill/spill"],
  fs: "file:///"
 }
 sort: {
  external: {
   batch.size: 4000,
   spill: {
    batch.size: 4000,
    group.size: 100,
    threshold: 200,
    directories: ["/data/enliven/installations/ApacheD/drill/spill"],
    fs: "file:///"
   }
  }
 },
 hashagg: {
  spill: {
   directories: ["/data/enliven/installations/ApacheD/drill/spill"],
   fs: "file:///"
  }
 }
}

Still am getting same out of memory exception .

Any one can help me on this.

Body:
According to http://www.openkb.info/2015/05/drill-workshop-spill.html, to test the effectiveness of a Drill Spill, you should reduce the provided memory amount to e.g. 20 MB:

alter session set `planner.memory.max_query_memory_per_node`=20971520;

Then test a query and check the file system if the spill is working at all.

Also, it might be wise to check if you provided enough heap in the first place if you have 8 GB available (from https://drill.apache.org/docs/configuring-drill-memory/):

The drill-env.sh file contains the following options:

#export DRILL_HEAP=${DRILL_HEAP:-"4G”}
#export DRILL_MAX_DIRECT_MEMORY=${DRILL_MAX_DIRECT_MEMORY:-"8G"}

To customize memory limits, uncomment the line needed and change the setting:

export DRILL_HEAP=${DRILL_HEAP:-"<limit>”}
export DRILL_MAX_DIRECT_MEMORY=${DRILL_MAX_DIRECT_MEMORY:-“<limit>"}


问:
Not sure why typedef is being used when a struct tag has been set
Considering the following code:

```<code>struct TreeNode {
  int key;
  struct TreeNode *left;
  struct TreeNode *right;
};

struct ListNode {
  int key;
  struct ListNode *next;
};
</code>```

I understand this as two structs with individual struct tags. And that the declaration (if I understand correctly):

```<code>struct ListNode *next;
</code>```

Is creating a pointer that points to a struct of type ListNode. And that

```<code>struct ListNode node1;
</code>```

Is creating a struct of type ListNode.
However, I do not understand the following two lines:

```<code>typedef struct TreeNode *TreeNodePtr;
typedef struct ListNode *ListNodePtr;
</code>```

If this is creating a pointer that points to a struct node of type TreeNode/ListNode I do not understand the purpose of typedef in this situation.

答:
The typedef in this context is for the pointer (so that you can write TreeNodePtr and have a pointer type instead of struct TreeNode *). This sort of definition is commonplace in the Windows header files:

```<code>typedef struct _WINUSB_SETUP_PACKET {
UCHAR   RequestType;
UCHAR   Request;
USHORT  Value;
USHORT  Index;
USHORT  Length;
} WINUSB_SETUP_PACKET, *PWINUSB_SETUP_PACKET;
</code>```

Body:
Considering the following code:

struct TreeNode {
  int key;
  struct TreeNode *left;
  struct TreeNode *right;
};

struct ListNode {
  int key;
  struct ListNode *next;
};

I understand this as two structs with individual struct tags. And that the declaration (if I understand correctly):

struct ListNode *next;

Is creating a pointer that points to a struct of type ListNode. And that

struct ListNode node1;

Is creating a struct of type ListNode.
However, I do not understand the following two lines:

typedef struct TreeNode *TreeNodePtr;
typedef struct ListNode *ListNodePtr;

If this is creating a pointer that points to a struct node of type TreeNode/ListNode I do not understand the purpose of typedef in this situation.

Body:
The typedef in this context is for the pointer (so that you can write TreeNodePtr and have a pointer type instead of struct TreeNode *). This sort of definition is commonplace in the Windows header files:

typedef struct _WINUSB_SETUP_PACKET {
UCHAR   RequestType;
UCHAR   Request;
USHORT  Value;
USHORT  Index;
USHORT  Length;
} WINUSB_SETUP_PACKET, *PWINUSB_SETUP_PACKET;


问:
Remove ouline on PrimeNG checkbox
I would like to remove the glow, a.k.a outline, of the PrimeNG checkbox component. (I know, I know. It's for accessability and all, but I'm implementing this indicator myself)

I've tried to set every thinkable class or selector to outline: none, and even the big bang approach with

```<code>*:focus {
  outline: none !important;
}
</code>```

But nothing seems to work...

What do I need to do to get rid of it?

Thanks!

Edit, My angular-cli.json:

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "test"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.sass",
        "../node_modules/font-awesome/css/font-awesome.min.css",
        "../node_modules/primeng/resources/primeng.min.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "src/tsconfig.spec.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "e2e/tsconfig.e2e.json",
      "exclude": "**/node_modules/**"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "sass",
    "class": {
      "spec": false
    },
    "component": {}
  }
}
</code>```

And at the top of my styles.sass I import my primeng.scss file:

```<code>@import 'primeng'
</code>```

答:
In the omege theme.scss line 242 you will see:

```<code>.ui-chkbox-box.ui-state-focus,
.ui-radiobutton-box.ui-state-focus  {
    -moz-box-shadow: 0px 0px 5px #1f89ce;
    -webkit-box-shadow: 0px 0px 5px #1f89ce;
    box-shadow: 0px 0px 5px #1f89ce;
 }
</code>```

This is the style giving the checkbox the glow. You can set those properties to none to stop this.

```<code>.ui-chkbox-box.ui-state-focus,
.ui-radiobutton-box.ui-state-focus  {
   -moz-box-shadow: none;
   -webkit-box-shadow: none;
   box-shadow: none;
 }
</code>```

If you don't want to edit the theme file you can override the css by doing something like:

```<code>.ui-chkbox-box.ui-state-focus {
   -moz-box-shadow: none;
   -webkit-box-shadow: none;
    box-shadow: none;
}
</code>```

The example above also includes radio buttons. Just reformat the css to exclude it: .ui-radiobutton-box.ui-state-focus

Title: Remove ouline on PrimeNG checkbox

Body:
I would like to remove the glow, a.k.a outline, of the PrimeNG checkbox component. (I know, I know. It's for accessability and all, but I'm implementing this indicator myself)

I've tried to set every thinkable class or selector to outline: none, and even the big bang approach with

*:focus {
  outline: none !important;
}

But nothing seems to work...

What do I need to do to get rid of it?

Thanks!

Edit, My angular-cli.json:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "test"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.sass",
        "../node_modules/font-awesome/css/font-awesome.min.css",
        "../node_modules/primeng/resources/primeng.min.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "src/tsconfig.spec.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "e2e/tsconfig.e2e.json",
      "exclude": "**/node_modules/**"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "sass",
    "class": {
      "spec": false
    },
    "component": {}
  }
}

And at the top of my styles.sass I import my primeng.scss file:

@import 'primeng'

Body:
In the omege theme.scss line 242 you will see:

.ui-chkbox-box.ui-state-focus,
.ui-radiobutton-box.ui-state-focus  {
    -moz-box-shadow: 0px 0px 5px #1f89ce;
    -webkit-box-shadow: 0px 0px 5px #1f89ce;
    box-shadow: 0px 0px 5px #1f89ce;
 }

This is the style giving the checkbox the glow. You can set those properties to none to stop this.

.ui-chkbox-box.ui-state-focus,
.ui-radiobutton-box.ui-state-focus  {
   -moz-box-shadow: none;
   -webkit-box-shadow: none;
   box-shadow: none;
 }

If you don't want to edit the theme file you can override the css by doing something like:

.ui-chkbox-box.ui-state-focus {
   -moz-box-shadow: none;
   -webkit-box-shadow: none;
    box-shadow: none;
}

The example above also includes radio buttons. Just reformat the css to exclude it: .ui-radiobutton-box.ui-state-focus


问:
Incomplete history of a file in git (git-svn)
How should one go about viewing full history of a file's content in git?

A file has a very short history in git, repository synced over git-svn, but a long history in svn. The history in git reaches to the point where the file was moved. To view the history I use the following command:

```<code>git log PATH_TO_FILE
</code>```

Am I doing it right? Git is supposed to track content not files, I was imagining it would be good at tracking history of files across renames.

答:
Try</p>

```<code>git log --follow PATH_TO_FILE
</code>```

Body:
How should one go about viewing full history of a file's content in git?

A file has a very short history in git, repository synced over git-svn, but a long history in svn. The history in git reaches to the point where the file was moved. To view the history I use the following command:

git log PATH_TO_FILE

Am I doing it right? Git is supposed to track content not files, I was imagining it would be good at tracking history of files across renames.

Body:
Try

git log --follow PATH_TO_FILE


问:
SQL for determining true/false based on two table rows
Consider a table that contains a row for each field on a form that is submitted.

```<code>CREATE TABLE `FormResponses` (
  `responseID` char(35) COLLATE utf8_unicode_ci DEFAULT NULL,
  `formID` char(35) COLLATE utf8_unicode_ci DEFAULT NULL,
  `formField` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `formValue` longtext COLLATE utf8_unicode_ci
)
</code>```

If a submitted form had 2 fields (user_id, and audio_file_id), there would be two rows, both having the same responseID and formId.

Now, I need to query the table to determine if a user_id has submitted the form for a particular audio_file_id (to prevent duplicate submissions for an audio file, while allowing submissions for other audio files using the same form).

The pseudoquery might look like:

```<code>SELECT responseId
FROM FormResponses
WHERE formId = FORM_ID_VALUE AND EXISTS

( SELECT responseID
  FROM FormResponses
  WHERE formField = "user_id" AND formValue = USER_ID_VALUE

AND

 SELECT responseID
 FROM FormResponses
 WHERE formField = "audio_file_id" AND formValue = AUDIO_FILE_ID_VALUE AND responseID = RESPONSE_ID_OF_USER_ID_QUERY_ABOVE

)
</code>```

Basically, the plain English query would be "give me the response ID of the two rows where the formId = 123, and one of those two rows represents a user_id of 456 and the other of those two rows represents an audio_file_id of 789."

Of note:  If a user submits the same form for two different audio files, the responseID for those two submits will be different, but the formID will be the same.

I hope I am asking this clearly enough... hopefully it's just harder to explain than to do!

答:
Whenever you have to combine data from two rows in the same table you do an auto join, i.e. you query the table twice and call them for instance a and b. Then you get the one row from table a and the other from table b. If all the criteria are met, you will get a resulting row:</p>

```<code>SELECT a.responseId
FROM FormResponses a
JOIN FormResponses b
ON a.formId = b.formId
AND a.responseId = b.responseId
WHERE a.formId = FORM_ID_VALUE
AND a.formField = 'user_id'
AND a.formValue = USER_ID_VALUE
AND b.formField = 'audio_file_id'
AND b.formValue = AUDIO_FILE_ID_VALUE
</code>```

Body:
Consider a table that contains a row for each field on a form that is submitted.

CREATE TABLE `FormResponses` (
  `responseID` char(35) COLLATE utf8_unicode_ci DEFAULT NULL,
  `formID` char(35) COLLATE utf8_unicode_ci DEFAULT NULL,
  `formField` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `formValue` longtext COLLATE utf8_unicode_ci
)

If a submitted form had 2 fields (user_id, and audio_file_id), there would be two rows, both having the same responseID and formId.

Now, I need to query the table to determine if a user_id has submitted the form for a particular audio_file_id (to prevent duplicate submissions for an audio file, while allowing submissions for other audio files using the same form).

The pseudoquery might look like:

SELECT responseId
FROM FormResponses
WHERE formId = FORM_ID_VALUE AND EXISTS

( SELECT responseID
  FROM FormResponses
  WHERE formField = "user_id" AND formValue = USER_ID_VALUE

AND

 SELECT responseID
 FROM FormResponses
 WHERE formField = "audio_file_id" AND formValue = AUDIO_FILE_ID_VALUE AND responseID = RESPONSE_ID_OF_USER_ID_QUERY_ABOVE

)

Basically, the plain English query would be "give me the response ID of the two rows where the formId = 123, and one of those two rows represents a user_id of 456 and the other of those two rows represents an audio_file_id of 789."

Of note:  If a user submits the same form for two different audio files, the responseID for those two submits will be different, but the formID will be the same.

I hope I am asking this clearly enough... hopefully it's just harder to explain than to do!

Body:
Whenever you have to combine data from two rows in the same table you do an auto join, i.e. you query the table twice and call them for instance a and b. Then you get the one row from table a and the other from table b. If all the criteria are met, you will get a resulting row:

SELECT a.responseId
FROM FormResponses a
JOIN FormResponses b
ON a.formId = b.formId
AND a.responseId = b.responseId
WHERE a.formId = FORM_ID_VALUE
AND a.formField = 'user_id'
AND a.formValue = USER_ID_VALUE
AND b.formField = 'audio_file_id'
AND b.formValue = AUDIO_FILE_ID_VALUE


问:
Can you have types that refer to each other in Julia?
I get ERROR: LoadError: UndefVarError: Expression not defined for the following code:

```<code>struct IntLiteral
    value::Int
end

struct Plus
    left::Expression
    right::Expression
end

struct Minus
    left::Expression
    right::Expression
end

const Expression = Union{IntLiteral, Plus, Minus}
</code>```

If I declare Expression ahead of Plus and Minus, I get a similar error. Wrapping the code in a module doesn't change anything, either.

Is there a way to reference a type ahead of its declaration in Julia? If not, what is the recommended solution for cases like this, where two types depend on each other? Just remove the type annotations?

In this particular case, I believe I could make Expression an abstract type, and have the others be subtypes of it. Is that recommended in this case? What about the general case?

答: Not currently, no.  See issue #269 for more details.</p>

Body:
I get ERROR: LoadError: UndefVarError: Expression not defined for the following code:

struct IntLiteral
    value::Int
end

struct Plus
    left::Expression
    right::Expression
end

struct Minus
    left::Expression
    right::Expression
end

const Expression = Union{IntLiteral, Plus, Minus}

If I declare Expression ahead of Plus and Minus, I get a similar error. Wrapping the code in a module doesn't change anything, either.

Is there a way to reference a type ahead of its declaration in Julia? If not, what is the recommended solution for cases like this, where two types depend on each other? Just remove the type annotations?

In this particular case, I believe I could make Expression an abstract type, and have the others be subtypes of it. Is that recommended in this case? What about the general case?


问:
How tell an other component of changement state of redux?
I have two components reactjs , I create an state redux to handle this state from two components .

```<code>  `appcomponent.js
import React, { Component } from 'react';
import { createStore } from 'redux';
import { connect } from 'react-redux';
//reducer
export function get_user(state=[], action) {
      switch (action.type) {
        case 'ADD_USER':
      return [
        {user:action.user}
      ];
      default:
      return state;
  }
     }
class appcomponent extends Component {
    constructor(props) {
        super(props);
        this.state = {Users:[]};
        //this.addUser=this.addUser.bind(this);
        this.onFormSubmit=this.onFormSubmit.bind(this);
        this.get=this.get.bind(this);
      }
get(){
    console.log(this.props.r);
}
onFormSubmit() {
  this.props.send('user');
}
  render() {
  return (
    <div>
   <br /><br /><br />
     <button onClick={this.onFormSubmit}>redux</button><br /><br /><br /><br />
     <button onClick={this.get}>REDUX</button>
    </div>
  )}
}
// action
export function addUser(user) {
  return {
    type: 'ADD_USER',
    user,
  };
}
function mapDispatchToProps (dispatch)  {
  return {
    send: user => dispatch(addUser(user))
  };
};
const mapStateToProps = (state, ownProps) => {
  return  { r:state};

};
export default connect(mapStateToProps,mapDispatchToProps)(appcomponent);
</code>```

In this component when I click "redux" button then onclick "REDUX" button I get the state changed.
In the other component I have this code :

```<code> class App extends Component {
constructor(props) {
    super(props);
    }
render() {
    return (
<div><h1>{this.props.user}</h1></div>
)
}}
const mapStateToProps = (state, ownProps) => {
  return  { user: state[0].user};//.user
};
function mapDispatchToProps (dispatch)  {
  return {
    get: user => dispatch(addUser('username'))
  };
};
export default connect(mapStateToProps,mapDispatchToProps)(App);
</code>```

In the last component always I get the initial state created in index.js

```<code>var store = createStore(get_user,[{user:'hhhh'}]);
ReactDOM.render( <Provider store={store}>
</code>```

Please who can help me ?

答:
You only need to call createStore() once, preferably near the top of your component tree not in each component.

Assuming you wrap your app in a Provider (from redux) you'll have access to redux's central State via the mapStateToProps function (where you can assign state elements to a particular components props):

```<code>import { Provider } from 'react-redux';
import {createStore, combineReducers } from 'redux';

const store = createStore(
  combineReducers({
    user: usersReducer,
    otherThings: otherThingsReducer
  })
)

const app = (
  <Provider store={store}>
    <MainAppComponentOrRouter/>
  </Provider>
);

ReactDOM.render(app, document.getElementById("app"));
</code>```

And then in a component:

```<code>const mapStateToProps = (state, props) => {
  return {
    user: state.user,
    otherThings: state.otherThings
  };
};

export default connect(mapStateToProps)(MyComponent);
</code>```

Body:
I have two components reactjs , I create an state redux to handle this state from two components .

  `appcomponent.js
import React, { Component } from 'react';
import { createStore } from 'redux';
import { connect } from 'react-redux';
//reducer
export function get_user(state=[], action) {
      switch (action.type) {
        case 'ADD_USER':
      return [
        {user:action.user}
      ];
      default:
      return state;
  }
     }
class appcomponent extends Component {
    constructor(props) {
        super(props);
        this.state = {Users:[]};
        //this.addUser=this.addUser.bind(this);
        this.onFormSubmit=this.onFormSubmit.bind(this);
        this.get=this.get.bind(this);
      }
get(){
    console.log(this.props.r);
}
onFormSubmit() {
  this.props.send('user');
}
  render() {
  return (

     <button onClick={this.onFormSubmit}>redux</button>

     <button onClick={this.get}>REDUX</button>

  )}
}
// action
export function addUser(user) {
  return {
    type: 'ADD_USER',
    user,
  };
}
function mapDispatchToProps (dispatch)  {
  return {
    send: user => dispatch(addUser(user))
  };
};
const mapStateToProps = (state, ownProps) => {
  return  { r:state};

};
export default connect(mapStateToProps,mapDispatchToProps)(appcomponent);

In this component when I click "redux" button then onclick "REDUX" button I get the state changed.
In the other component I have this code :

 class App extends Component {
constructor(props) {
    super(props);
    }
render() {
    return (

{this.props.user}

)
}}
const mapStateToProps = (state, ownProps) => {
  return  { user: state[0].user};//.user
};
function mapDispatchToProps (dispatch)  {
  return {
    get: user => dispatch(addUser('username'))
  };
};
export default connect(mapStateToProps,mapDispatchToProps)(App);

In the last component always I get the initial state created in index.js

var store = createStore(get_user,[{user:'hhhh'}]);
ReactDOM.render( <Provider store={store}>

Please who can help me ?

Body:
You only need to call createStore() once, preferably near the top of your component tree not in each component.

Assuming you wrap your app in a Provider (from redux) you'll have access to redux's central State via the mapStateToProps function (where you can assign state elements to a particular components props):

import { Provider } from 'react-redux';
import {createStore, combineReducers } from 'redux';

const store = createStore(
  combineReducers({
    user: usersReducer,
    otherThings: otherThingsReducer
  })
)

const app = (
  <Provider store={store}>
    <MainAppComponentOrRouter/>
  </Provider>
);

ReactDOM.render(app, document.getElementById("app"));

And then in a component:

const mapStateToProps = (state, props) => {
  return {
    user: state.user,
    otherThings: state.otherThings
  };
};

export default connect(mapStateToProps)(MyComponent);


问:
How do you toggle a checkbox on a Kendo UI PanelBar that can expand or collapse?
I am trying to make a panel bar with several expandable options with checkboxes at each level. The problem I am running into is that if you click on a checkbox that is part of an expandable panel, the checkbox does not toggle. Below is a simplified example that shows the problem. In the example below it is impossible to toggle the checkbox for Main 1

const panelBarTemplate = `

        #: item.text #
        <input type='checkbox'
            id=#: item.id #
            class='k-checkbox'
            # if (item.isVisible) { #checked='checked'# } # />
        # var ItemCheckboxLabelClass = "k-checkbox-label" #
        # if (item.items) { ItemCheckboxLabelClass = "k-checkbox-label expandable-item" } #

`;

var canExpandCollapse = true;

$('#side-bar-panel').kendoPanelBar({
  template: panelBarTemplate,
  dataSource: [{
    text: 'Main 1',
    id: 'Main1',
    isVisible: true,
    expanded: true,
    items: [{
      text: 'Sub 1',
      id: 'Sub1',
      isVisible: true
    }, {
      text: 'Sub 2',
      id: 'Sub2',
      isVisible: false
    }]
  }],
  dataBound: function() {
    $('.expandable-item').click(function() {
      canExpandCollapse = false;
    });
  },
  expand: cancelExpandCollapse,
  collapse: cancelExpandCollapse
});

function cancelExpandCollapse(e) {
  if (!canExpandCollapse) {
    e.preventDefault();
    canExpandCollapse = true;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.common.min.css" rel="stylesheet" />
<link href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.flat.min.css" rel="stylesheet" />
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/kendo.all.min.js"></script>
<ul id="side-bar-panel">
</ul></code>```

I found a solution for preventing expanding and collapsing when clicking on the checkbox here https://stackoverflow.com/a/31879672/4708150, but even though expanding and collapsing is disabled, the checkbox is still not being toggled.

答:
I was able to find a workaround by just not using a checkbox. Instead of checkboxes I used a Kendo mobile switch and was able to get the switch to toggle and the panel bar not expand or collapse.

Below is the modified snippet. Items that changed are the panelBarTemplate, the functions inside of the dataBound configuration, and the css files for Kendo mobile were added.

const panelBarTemplate = `

        #: item.text #
        <input type='checkbox'
            id=#: item.id #
            # var ItemCheckboxClass = "my-checkbox" #
            # if (item.items) { ItemCheckboxClass = "my-checkbox expandable-item" } #
            class="#= ItemCheckboxClass #"
            # if (item.isVisible) { #checked='checked'# } # />

`;

var canExpandCollapse = true;

$('#side-bar-panel').kendoPanelBar({
  template: panelBarTemplate,
  dataSource: [{
    text: 'Main 1',
    id: 'Main1',
    isVisible: true,
    expanded: true,
    items: [{
      text: 'Sub 1',
      id: 'Sub1',
      isVisible: true
    }, {
      text: 'Sub 2',
      id: 'Sub2',
      isVisible: false
    }]
  }],
  dataBound: function() {
    //initialize mobile switch if not already initialized.
    $('.my-checkbox').each(function(index, item) {
      let mobileSwitch = $(item);
      let mobileSwitchData = mobileSwitch.data('kendoMobileSwitch');
      if (!mobileSwitchData) {
        mobileSwitch.kendoMobileSwitch();
      }
    });

    //disable expanding and collapsing when clicking on a mobile switch
    //that is attached to an expandable panel.
    $('.expandable-item').siblings('.k-switch-container').click(function() {
      canExpandCollapse = false;
    });
  },
  expand: cancelExpandCollapse,
  collapse: cancelExpandCollapse
});

function cancelExpandCollapse(e) {
  if (!canExpandCollapse) {
    e.preventDefault();
    canExpandCollapse = true;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.common.min.css" rel="stylesheet" />
<link href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.mobile.all.min.css" rel="stylesheet" />
<link href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.flat.min.css" rel="stylesheet" />
<link href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.flat.mobile.min.css" rel="stylesheet" />
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/kendo.all.min.js"></script>
<ul id="side-bar-panel">
</ul></code>```

Body:
I am trying to make a panel bar with several expandable options with checkboxes at each level. The problem I am running into is that if you click on a checkbox that is part of an expandable panel, the checkbox does not toggle. Below is a simplified example that shows the problem. In the example below it is impossible to toggle the checkbox for Main 1

const panelBarTemplate = `

        #: item.text #
        <input type='checkbox'
            id=#: item.id #
            class='k-checkbox'
            # if (item.isVisible) { #checked='checked'# } # />
        # var ItemCheckboxLabelClass = "k-checkbox-label" #
        # if (item.items) { ItemCheckboxLabelClass = "k-checkbox-label expandable-item" } #

`;

var canExpandCollapse = true;

$('#side-bar-panel').kendoPanelBar({
  template: panelBarTemplate,
  dataSource: [{
    text: 'Main 1',
    id: 'Main1',
    isVisible: true,
    expanded: true,
    items: [{
      text: 'Sub 1',
      id: 'Sub1',
      isVisible: true
    }, {
      text: 'Sub 2',
      id: 'Sub2',
      isVisible: false
    }]
  }],
  dataBound: function() {
    $('.expandable-item').click(function() {
      canExpandCollapse = false;
    });
  },
  expand: cancelExpandCollapse,
  collapse: cancelExpandCollapse
});

function cancelExpandCollapse(e) {
  if (!canExpandCollapse) {
    e.preventDefault();
    canExpandCollapse = true;
  }
}

<link href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.common.min.css" rel="stylesheet" />
<link href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.flat.min.css" rel="stylesheet" />

I found a solution for preventing expanding and collapsing when clicking on the checkbox here https://stackoverflow.com/a/31879672/4708150, but even though expanding and collapsing is disabled, the checkbox is still not being toggled.

Body:
I was able to find a workaround by just not using a checkbox. Instead of checkboxes I used a Kendo mobile switch and was able to get the switch to toggle and the panel bar not expand or collapse.

Below is the modified snippet. Items that changed are the panelBarTemplate, the functions inside of the dataBound configuration, and the css files for Kendo mobile were added.

const panelBarTemplate = `
    <div>
        <span>#: item.text #</span>
        <input type='checkbox'
            id=#: item.id #
            # var ItemCheckboxClass = "my-checkbox" #
            # if (item.items) { ItemCheckboxClass = "my-checkbox expandable-item" } #
            class="#= ItemCheckboxClass #"
            # if (item.isVisible) { #checked='checked'# } # />
    </div>
`;

var canExpandCollapse = true;

$('#side-bar-panel').kendoPanelBar({
  template: panelBarTemplate,
  dataSource: [{
    text: 'Main 1',
    id: 'Main1',
    isVisible: true,
    expanded: true,
    items: [{
      text: 'Sub 1',
      id: 'Sub1',
      isVisible: true
    }, {
      text: 'Sub 2',
      id: 'Sub2',
      isVisible: false
    }]
  }],
  dataBound: function() {
    //initialize mobile switch if not already initialized.
    $('.my-checkbox').each(function(index, item) {
      let mobileSwitch = $(item);
      let mobileSwitchData = mobileSwitch.data('kendoMobileSwitch');
      if (!mobileSwitchData) {
        mobileSwitch.kendoMobileSwitch();
      }
    });

    //disable expanding and collapsing when clicking on a mobile switch
    //that is attached to an expandable panel.
    $('.expandable-item').siblings('.k-switch-container').click(function() {
      canExpandCollapse = false;
    });
  },
  expand: cancelExpandCollapse,
  collapse: cancelExpandCollapse
});

function cancelExpandCollapse(e) {
  if (!canExpandCollapse) {
    e.preventDefault();
    canExpandCollapse = true;
  }
}

<link href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.common.min.css" rel="stylesheet" />
<link href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.mobile.all.min.css" rel="stylesheet" />
<link href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.flat.min.css" rel="stylesheet" />
<link href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.flat.mobile.min.css" rel="stylesheet" />
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/kendo.all.min.js"></script>
<ul id="side-bar-panel">
</ul>


问:
AppWidgetProvider with dagger2
I try to use Dagger2 with AppWidgetProvider.
But my beans are never inject by dagger.

I start from sample: https://github.com/googlesamples/android-architecture-components/tree/master/GithubBrowserSample

My AppModule:

```<code>@Module
public class AppModule {

    @Provides
    @Singleton
    Context providesApplicationContext(Application application) {
        return application;
    }

    @Singleton @Provides
    MyDb provideDb(Application app) {
        return Room.databaseBuilder(app, MyDb.class,"my.db")
                .build();
    }

    @Provides
    @Singleton
    SharedPreferences providesSharedPreferences(Application application) {
        return PreferenceManager.getDefaultSharedPreferences(application);
    }
}
</code>```

My WeatherModule

```<code>@Module
public class WeatherModule {

    @Singleton @Provides
    public OpenWeatherMapService provideOpenWeatherMapService() {
        return new Retrofit.Builder()
                .baseUrl(BuildConfig.OPEN_WEATHER_MAP_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(new LiveDataCallAdapterFactory())
                .build()
                .create(OpenWeatherMapService.class);
    }

    @Singleton @Provides
    public WeatherDao provideWeatherDao(MyDb db) {
        return db.weatherDao();
    }
}
</code>```

My Widget Dagger component:

```<code>@Singleton
@Component(modules = {AppModule.class, WeatherModule.class})
public interface WeatherWidgetComponent {
    void inject(Context context);
}
</code>```

My application:

```<code>public class MyApplication extends Application implements HasActivityInjector {

    @Inject
    DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;

    private WeatherWidgetComponent weatherWidgetComponent;

    @Override
    public void onCreate() {
        super.onCreate();

        AppInjector.init(this);

        weatherWidgetComponent = DaggerWeatherWidgetComponent.builder()
                .build();
    }

    public WeatherWidgetComponent getWeatherWidgetComponent() {
        return weatherWidgetComponent;
    }

    @Override
    public DispatchingAndroidInjector<Activity> activityInjector() {
        return dispatchingAndroidInjector;
    }
}
</code>```

My AppWidgetProvider

```<code>public class WeatherAppWidgetProvider extends AppWidgetProvider {

    @Inject
    WeatherDao weatherDao;

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        inject(context);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        inject(context);

        for (int widgetId : appWidgetIds) {
            updateUI(appWidgetManager, context, widgetId);
        }
    }

    @Override
    public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
        super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
        inject(context);
        updateUI(appWidgetManager, context, appWidgetId);
    }

    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
        inject(context);
    }

    private void inject(Context context){
        Timber.d("inject");
        if(weatherDao ==null) {
            Timber.d("null so try to inject");
            ((MyApplication) context.getApplicationContext()).getWeatherWidgetComponent().inject(context);
        }
    }

    private void updateUI(AppWidgetManager appWidgetManager, Context context, int appWidgetId){
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.weather_widget);

        if(weatherDao ==null){
            Timber.d("weatherDao null");
        }
    }
}
</code>```

In logcat I always have:

11-14 18:41:43.494  3812  3812 D WeatherAppWidgetProvide: inject

11-14 18:41:43.495  3812  3812 D WeatherAppWidgetProvide: null so try to inject

11-14 18:41:43.198  3812  3812 D WeatherAppWidgetProvide: weatherDao null

答:
As Gabor pointed out in the comments, you have to specify a concrete class for field injection.

```<code>@Singleton
@Component(modules = {AppModule.class, WeatherModule.class})
public interface WeatherWidgetComponent {
    void inject(Context context);
}
</code>```

Injecting Context will not do anything, because Context does not have any @Inject annotated fields. The generated code will basically try to inject a context and do nothing.

If you were to replace the call to void inject(Context context) with void inject(WeatherAppWidgetProvider provider) Dagger will generate code to properly inject WeatherAppWidgetProvider and calling .inject(this) will actually do something.

Title: AppWidgetProvider with dagger2

Body:
I try to use Dagger2 with AppWidgetProvider.
But my beans are never inject by dagger.

I start from sample: https://github.com/googlesamples/android-architecture-components/tree/master/GithubBrowserSample

My AppModule:

@Module
public class AppModule {

    @Provides
    @Singleton
    Context providesApplicationContext(Application application) {
        return application;
    }

    @Singleton @Provides
    MyDb provideDb(Application app) {
        return Room.databaseBuilder(app, MyDb.class,"my.db")
                .build();
    }

    @Provides
    @Singleton
    SharedPreferences providesSharedPreferences(Application application) {
        return PreferenceManager.getDefaultSharedPreferences(application);
    }
}

My WeatherModule

@Module
public class WeatherModule {

    @Singleton @Provides
    public OpenWeatherMapService provideOpenWeatherMapService() {
        return new Retrofit.Builder()
                .baseUrl(BuildConfig.OPEN_WEATHER_MAP_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(new LiveDataCallAdapterFactory())
                .build()
                .create(OpenWeatherMapService.class);
    }

    @Singleton @Provides
    public WeatherDao provideWeatherDao(MyDb db) {
        return db.weatherDao();
    }
}

My Widget Dagger component:

@Singleton
@Component(modules = {AppModule.class, WeatherModule.class})
public interface WeatherWidgetComponent {
    void inject(Context context);
}

My application:

public class MyApplication extends Application implements HasActivityInjector {

    @Inject
    DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;

    private WeatherWidgetComponent weatherWidgetComponent;

    @Override
    public void onCreate() {
        super.onCreate();

        AppInjector.init(this);

        weatherWidgetComponent = DaggerWeatherWidgetComponent.builder()
                .build();
    }

    public WeatherWidgetComponent getWeatherWidgetComponent() {
        return weatherWidgetComponent;
    }

    @Override
    public DispatchingAndroidInjector<Activity> activityInjector() {
        return dispatchingAndroidInjector;
    }
}

My AppWidgetProvider

public class WeatherAppWidgetProvider extends AppWidgetProvider {

    @Inject
    WeatherDao weatherDao;

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        inject(context);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        inject(context);

        for (int widgetId : appWidgetIds) {
            updateUI(appWidgetManager, context, widgetId);
        }
    }

    @Override
    public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
        super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
        inject(context);
        updateUI(appWidgetManager, context, appWidgetId);
    }

    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
        inject(context);
    }

    private void inject(Context context){
        Timber.d("inject");
        if(weatherDao ==null) {
            Timber.d("null so try to inject");
            ((MyApplication) context.getApplicationContext()).getWeatherWidgetComponent().inject(context);
        }
    }

    private void updateUI(AppWidgetManager appWidgetManager, Context context, int appWidgetId){
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.weather_widget);

        if(weatherDao ==null){
            Timber.d("weatherDao null");
        }
    }
}

In logcat I always have:

11-14 18:41:43.494  3812  3812 D WeatherAppWidgetProvide: inject

11-14 18:41:43.495  3812  3812 D WeatherAppWidgetProvide: null so try to inject

11-14 18:41:43.198  3812  3812 D WeatherAppWidgetProvide: weatherDao null

Body:
As Gabor pointed out in the comments, you have to specify a concrete class for field injection.

@Singleton
@Component(modules = {AppModule.class, WeatherModule.class})
public interface WeatherWidgetComponent {
    void inject(Context context);
}

Injecting Context will not do anything, because Context does not have any @Inject annotated fields. The generated code will basically try to inject a context and do nothing.

If you were to replace the call to void inject(Context context) with void inject(WeatherAppWidgetProvider provider) Dagger will generate code to properly inject WeatherAppWidgetProvider and calling .inject(this) will actually do something.


问:
Ionic 3: How to delete an image from the PhotoLibrary?
In an Ionic 3 app I have a photo gallery which displays images from an album. It works fine, but I can't delete an image.

A LibraryItem, as retrieved by cordova.plugins.photoLibrary.getLibrary looks like this:

```<code>creationDate: Sat Nov 04 2017 21:21:33 GMT-0400 (EDT)
fileName: "2017-10-5-1.jpg"
height: 960
id: "1937;/storage/emulated/0/Pictures/Timelapser/2017-10-5-1.jpg"
latitude: 0
longitude: 0
photoURL: "cdvphotolibrary://photo?photoId=1937%3B%2Fstorage%2Femulated%2F0%2FPictures%2FTimelapser%2F2017-10-5-1.jpg"
thumbnailURL: "cdvphotolibrary://thumbnail?photoId=1937%3B%2Fstorage%2Femulated%2F0%2FPictures%2FTimelapser%2F2017-10-5-1.jpg&width=512&height=384&quality=0.8"
width: 1280
</code>```

I am trying to delete this (or any other) image file. However anything I try, Cordova throws an error and the file doesn't seem to exist. Ionic's manual is quite hazy at this point. This is all it says:

```<code>removeFile(path, fileName)
</code>```

The parameters are pretty obvious, except what are they supposed to be? I tried everything, extracted path and filename from the photoURL value, but nothing seems to help. Neither checkFile nor removeFile seems to find the file.

答:
You can not delete a file from the cdvphotolibrary:// url. If you want to delete a file,  you need to have file:/// native url.

check the Getting native file location open issue with the PhotoLibary plugin.

AndreasGassmann has a fork that returns the native url also. As per him you can get the native urls:

getNativeThumbnailUrl

getNativePhotoUrl

Body:
In an Ionic 3 app I have a photo gallery which displays images from an album. It works fine, but I can't delete an image.

A LibraryItem, as retrieved by cordova.plugins.photoLibrary.getLibrary looks like this:

creationDate: Sat Nov 04 2017 21:21:33 GMT-0400 (EDT)
fileName: "2017-10-5-1.jpg"
height: 960
id: "1937;/storage/emulated/0/Pictures/Timelapser/2017-10-5-1.jpg"
latitude: 0
longitude: 0
photoURL: "cdvphotolibrary://photo?photoId=1937%3B%2Fstorage%2Femulated%2F0%2FPictures%2FTimelapser%2F2017-10-5-1.jpg"
thumbnailURL: "cdvphotolibrary://thumbnail?photoId=1937%3B%2Fstorage%2Femulated%2F0%2FPictures%2FTimelapser%2F2017-10-5-1.jpg&width=512&height=384&quality=0.8"
width: 1280

I am trying to delete this (or any other) image file. However anything I try, Cordova throws an error and the file doesn't seem to exist. Ionic's manual is quite hazy at this point. This is all it says:

removeFile(path, fileName)

The parameters are pretty obvious, except what are they supposed to be? I tried everything, extracted path and filename from the photoURL value, but nothing seems to help. Neither checkFile nor removeFile seems to find the file.


问:
Extract face features from ARSCNFaceGeometry
I've been trying without success to extract face features, for instance the mouth, from ARSCNFaceGeometry in order to change their color or add a different material.
I understand I need to create an SCNGeometry for which I have the SCNGeometrySource but haven't been able to create the SCNGeometryElement.
Have tried creating it from ARFaceAnchor in update(from faceGeometry: ARFaceGeometry) but so far have been unable.
Would really appreciate someone help

答:
ARSCNFaceGeometry is a single mesh. If you want different areas of it to be different colors, your best bet is to apply a texture map (which you do in SceneKit by providing images for material property contents).

There’s no semantic information associated with the vertices in the mesh — that is, there’s nothing that says “this point is the tip of the nose, these points are the edge of the upper lip, etc”. But the mesh is topologically stable, so if you create a texture image that adds a bit of color around the lips or a lightning bolt over the eye or whatever, it’ll stay there as the face moves around.

If you need help getting started on painting a texture, there are a couple of things you could try:

Create a dummy texture first

Make a square image and fill it with a double gradient, such that the red and blue component for each pixel is based on the x and y coordinate of that pixel. Or some other distinctive pattern. Apply that texture to the model, and see how it looks — the landmarks in the texture will guide you where to paint.

Export the model

Create a dummy ARSCNFaceGeometry using the init(blendShapes:) initializer and an empty blendShapes dictionary (you don’t need an active ARFaceTracking session for this, but you do need an iPhone X). Use SceneKit’s scene export APIs (or Model I/O) to write that model out to a 3D file of some sort (.scn, which you can process further on the Mac, or something like .obj).

Import that file into your favorite 3D modeling tool (Blender, Maya, etc) and use that tool to paint a texture. Then use that texture in your app with real faces.

Actually, the above is sort of an oversimplification, even though it’s the simple answer for common cases. ARSCNFaceGeometry can actually contain up to four submeshes if you create it with the init(device:fillMesh:) initializer. But even then, those parts aren’t semantically labeled areas of the face — they’re the holes in the regular face model, flat fill-ins for the places where eyes and mouth show through.


问:
Multi-stage form in Laravel 5
I want to build a simple multi-stage registration process in Laravel 5.5, without having to resort to JavaScript, but I'm not sure if it's possible.

My routes are fairly simple:

```<code>Route::get('/stage1', 'UserController@showWelcome')->name('welcome');
Route::post('/stage1', 'UserController@validateWelcome');

Route::get('/stage2', 'UserController@create')->name('register');
Route::post('/stage2', 'UserController@store');
</code>```

In the UserController...

@showWelcome -> return view('stage1')

@validateWelcome -> validates input then return view('stage2', compact('request'))

@create -> return view('stage2')

@store -> validates the input, saves to DB then return view('stagesComplete')

The problem

Everything works perfectly except when there's a validation error during stage 2. The page is submitted but it shows the error messages on stage1.

I've ensured that the stage1 form POSTs to /stage1, and the same for /stage2 (it POSTs to /stage2).

I've tried redirecting to /stage2 with @validateWelcome, but of course you can't POST with a redirect.

Am I missing something, or is it just not possible?

答:
Normally, you should create:

```<code>GET step1 - show form
POST step1 - validate and redirect to step2
GET step2 - show form
POST step2 - validate and save data in database/whatever
</code>```

when POST step1 is fine, you can add data to session and redirect to step2, when you run POST step2 and data is invalid there won't be any problem because you wil have GET step2 action

Title: Multi-stage form in Laravel 5

Body:
I want to build a simple multi-stage registration process in Laravel 5.5, without having to resort to JavaScript, but I'm not sure if it's possible.

My routes are fairly simple:

Route::get('/stage1', 'UserController@showWelcome')->name('welcome');
Route::post('/stage1', 'UserController@validateWelcome');

Route::get('/stage2', 'UserController@create')->name('register');
Route::post('/stage2', 'UserController@store');

In the UserController...

@showWelcome -> return view('stage1')

@validateWelcome -> validates input then return view('stage2', compact('request'))

@create -> return view('stage2')

@store -> validates the input, saves to DB then return view('stagesComplete')

The problem

Everything works perfectly except when there's a validation error during stage 2. The page is submitted but it shows the error messages on stage1.

I've ensured that the stage1 form POSTs to /stage1, and the same for /stage2 (it POSTs to /stage2).

I've tried redirecting to /stage2 with @validateWelcome, but of course you can't POST with a redirect.

Am I missing something, or is it just not possible?

Body:
Normally, you should create:

GET step1 - show form
POST step1 - validate and redirect to step2
GET step2 - show form
POST step2 - validate and save data in database/whatever

when POST step1 is fine, you can add data to session and redirect to step2, when you run POST step2 and data is invalid there won't be any problem because you wil have GET step2 action


问:
Java PrintWriter big memory consume
I am trying to write a big file text from DB, around 2 millons of line.
I observed that while PrintWriter is printing (println()) the line, the file size is alway 0 byte. The file have size data after the stream closed.
It cause that all data first save in memory and free it when the stream close.
In my case after 1 millons of data +- 2.5GB of memory consumed. the app crash.
Is possible write data in real time and prevent memory consumition?

This is a a example:

```<code>    File file = new File("file.txt");

   PrintWriter out;

   out = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file)), "UTF-8"));

for (int i=0; i < 9999999; i++){
    out.println("some data here");
}
out.close();
</code>```

答:
You've created the PrintWriter without automatic line flushing, so the contents will be buffered until you call flush() or close(). Since you don't want to flush every line (it's slow), you can perform a flush every N lines with

```<code>for (int i=0; i < 9999999; i++){
    out.println("some data here");
    if(i % N == 0)
        out.flush();
}
</code>```

Try it out with different values of N to see how the performance changes.

Title: Java PrintWriter big memory consume

Body:
I am trying to write a big file text from DB, around 2 millons of line.
I observed that while PrintWriter is printing (println()) the line, the file size is alway 0 byte. The file have size data after the stream closed.
It cause that all data first save in memory and free it when the stream close.
In my case after 1 millons of data +- 2.5GB of memory consumed. the app crash.
Is possible write data in real time and prevent memory consumition?

This is a a example:

    File file = new File("file.txt");

   PrintWriter out;

   out = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file)), "UTF-8"));

for (int i=0; i < 9999999; i++){
    out.println("some data here");
}
out.close();

Body:
You've created the PrintWriter without automatic line flushing, so the contents will be buffered until you call flush() or close(). Since you don't want to flush every line (it's slow), you can perform a flush every N lines with

for (int i=0; i < 9999999; i++){
    out.println("some data here");
    if(i % N == 0)
        out.flush();
}

Try it out with different values of N to see how the performance changes.