问:
httpmodules(Classic Mode) Vs Modules (Integrated mode) not parsing request in the same way
I have an ASP.NET FW 4.5 application, normally it is running under Classic Mode , and we use a HttpModule that parse every request to webpages.
The Module checks in the DB if the user has access.
No problem with that.

When we switch to integrated mode we put a < webserver > < module > as recommended in the migration guide.
The problem is that the module is parsing every request to the application, also the css, jss and images.
In Classic mode this does not happen, only pages are parsed.
Is there a different behavior between classic and integrated?
The module implements methods like:

private void OnBeginRequest(object sender, EventArgs e)
private void OnAuthorization(object sender, EventArgs e)

答:
This question is a bit old but just in case somebody else finds it I'll provide the answer...

In integrated mode, any modules you provide in <system.webserver> are invoked for every IIS request (including non ASP.NET pages) unless you add a constraint via the preCondition attribute. e.g.

```<code><system.webserver>
    <modules>
        <add preCondition="managedHandler" name="..." type="..."/>
    </modules>
</system.webserver>
</code>```

Specifying managedHandler means the module will be invoked only for ASP.Net managed resources such as .aspx files, but not unmanaged resources such as html, images and javascript.

Note, however, this setting is overridden if you specify runAllManagedModulesForAllRequests="true" on the <modules> element, which causes all modules (and your Global.asax class if present) to be notified about all requests.

There's a useful write-up of the Life Cycle of an IIS 7.x request on MSDN, but this does not mention the preCondition attribute.  However you can read about it in the IIS Settings Schema documentation.

TL;DR

You might be wondering how it's possible that a module can be invoked for a non-managed resource when the event handlers defined in your Global.asax file are not invoked. After all, modules register their event handlers with the HttpApplication object that is passed to the IHttpModule.Init method like this:-

```<code>public void Init(System.Web.HttpApplication context)
{
    context.AuthenticateRequest += my_request_handler;
}
</code>```

The HttpApplication passed to Init is the same as that defined in Global.asax, so why aren't the Global application event handlers invoked?  The answer is simply that when a module registers its event handlers with the HttpApplication object, the HttpApplication is aware that it is in module initialization mode, and registers the event handlers separately, along with flags to indicate if the event handler should be called for non-managed resources.  You can investigate further by looking at the
HttpApplication reference source code.

Body:
This question is a bit old but just in case somebody else finds it I'll provide the answer...

In integrated mode, any modules you provide in <system.webserver> are invoked for every IIS request (including non ASP.NET pages) unless you add a constraint via the preCondition attribute. e.g.

<system.webserver>
    <modules>
        <add preCondition="managedHandler" name="..." type="..."/>
    </modules>
</system.webserver>

Specifying managedHandler means the module will be invoked only for ASP.Net managed resources such as .aspx files, but not unmanaged resources such as html, images and javascript.

Note, however, this setting is overridden if you specify runAllManagedModulesForAllRequests="true" on the <modules> element, which causes all modules (and your Global.asax class if present) to be notified about all requests.

There's a useful write-up of the Life Cycle of an IIS 7.x request on MSDN, but this does not mention the preCondition attribute.  However you can read about it in the IIS Settings Schema documentation.

TL;DR

You might be wondering how it's possible that a module can be invoked for a non-managed resource when the event handlers defined in your Global.asax file are not invoked. After all, modules register their event handlers with the HttpApplication object that is passed to the IHttpModule.Init method like this:-

public void Init(System.Web.HttpApplication context)
{
    context.AuthenticateRequest += my_request_handler;
}

The HttpApplication passed to Init is the same as that defined in Global.asax, so why aren't the Global application event handlers invoked?  The answer is simply that when a module registers its event handlers with the HttpApplication object, the HttpApplication is aware that it is in module initialization mode, and registers the event handlers separately, along with flags to indicate if the event handler should be called for non-managed resources.  You can investigate further by looking at the
HttpApplication reference source code.


来源: stackexchange

问:
PHP: Change only a portion of a URL string?
I’m working on a small hoppy project where I want to replace a specific page on a URL. Let me explain:

I’ve got the URL

http://www.example.com/article/paragraph/low/

I want to keep the URL but replace the last segment /low/ with /high/ so the new URL is:

http://www.example.com/article/paragraph/high/

I’ve tried different explode, split and splice but I just can’t seem to wrap my head around it and make it work. I can change the entire URL but not just the last segment and save it in a new variable.

I’m pretty confidence that it is a pretty straight forward case but I’ve never worked that much with arrays / string-manipulation in PHP so I’m pretty lost.

I guess that I have to first split the URL up in segments, using the "\" to separate it (I tried that but have problems by using explode("\", $string)) and then replace the last \low\ with \high\

Hope someone could help or point me in the right direction to what methods to use for doing this.

Sincere

Mestika

答:
This will probably be enough:

```<code>$url = "http://www.mydomain.com/article/paragraph/low/";
$newUrl = str_replace('/low/', '/high/', $url);
</code>```

or with regular expressions (it allows more flexibility)

```<code>$url = "http://www.mydomain.com/article/paragraph/low/";
$newUrl = preg_replace('/low(\/?)$/', 'high$1', $url);
</code>```

Note that the string approach will replace any low segment and only if it's followed by a /. The regex approach will replace low only if it's the last segment and it may not be followed by a /.

ContentLicense: CC BY-SA 4.0

Body:
This will probably be enough:

$url = "http://www.mydomain.com/article/paragraph/low/";
$newUrl = str_replace('/low/', '/high/', $url);

or with regular expressions (it allows more flexibility)

$url = "http://www.mydomain.com/article/paragraph/low/";
$newUrl = preg_replace('/low(\/?)$/', 'high$1', $url);

Note that the string approach will replace any low segment and only if it's followed by a /. The regex approach will replace low only if it's the last segment and it may not be followed by a /.

ContentLicense: CC BY-SA 2.5


问:
Android : Permission doesn't seems to work and icon doesn't want to display
I have an app that supposed to work on android TV, so befor posting it on App Store I wanted to test it on my own Android TV.

But when I install it I have 3 problemes :

1) I don't know why but my permissions doesn't seems to work

2) My app isn't dipslayed on the menu, you can only find it on settings-->app

3) The icon is the android default icon and not my own icon

Here's my manifest :

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.package">

<!-- read sd card -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- write sd card -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- location -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- internet -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- internet state -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- to disable recent app button -->
<uses-permission android:name="android.permission.REORDER_TASKS" />
<!-- AccountManager -->
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>
<!-- same -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- don't rember -->
<uses-permission android:name="android.permission.GET_TASKS"/>

<uses-feature
    android:name="android.hardware.touchscreen"
    android:required="false" />
<uses-feature
    android:name="android.software.leanback"
    android:required="true" />
<uses-feature
    android:name="android.hardware.location.gps"
    android:required="false" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar">
    <activity android:name=".MainActivity"
        android:banner="@drawable/my_logo_temp"
        android:icon="@drawable/my_logo_temp"
        android:label="@string/app_name"
        android:logo="@drawable/my_logo_temp"
        android:screenOrientation="landscape">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name=".account.AuthenticatorService"
        android:exported="true"
        android:process=":auth" >
        <intent-filter>
            <action android:name="android.accounts.AccountAuthenticator" />
        </intent-filter>

        <meta-data
            android:name="android.accounts.AccountAuthenticator"
            android:resource="@xml/auth" />
    </service>
</application>

</manifest>
</code>```

答:
Here is the answer hope this Help you.

Case 3 : Remove banner and icon from Mainactivity It should be always on Application tag so put it in the application tag.

Case 2 : Remove Existing Theme and Apply android:theme="@style/Theme.Leanback" on application tag.

I always Prefer to write this much of code when start developing TV application.

```<code><uses-feature
    android:name="android.hardware.touchscreen"
    android:required="false" />
<uses-feature
    android:name="android.software.leanback"
    android:required="true" />
<uses-feature
    android:name="android.hardware.faketouch"
    android:required="false" />
<uses-feature
    android:name="android.hardware.telephony"
    android:required="false" />
<uses-feature
    android:name="android.hardware.camera"
    android:required="false" />
<uses-feature
    android:name="android.hardware.nfc"
    android:required="false" />
<uses-feature
    android:name="android.hardware.location.gps"
    android:required="false" />
<uses-feature
    android:name="android.hardware.microphone"
    android:required="false" />
<uses-feature
    android:name="android.hardware.sensor"
    android:required="false" />

<supports-screens
    android:largeScreens="true"
    android:normalScreens="false"
    android:requiresSmallestWidthDp="720"
    android:smallScreens="false"
    android:xlargeScreens="true" />

    <-- Your Permission -->
    <-- You Application Tag -->
</code>```

Don't Forget to add compile 'com.android.support:leanback-v17:23.2.1' dependency in your build.gradle file. I was used this dependency when created the app you can change the version according to your project.

Try this one may be this help you.

For Case 1 : Permission issue it will be resolved if do all the above steps.

ContentLicense: CC BY-SA 3.0

Body:
I have an app that supposed to work on android TV, so befor posting it on App Store I wanted to test it on my own Android TV.

But when I install it I have 3 problemes :

1) I don't know why but my permissions doesn't seems to work

2) My app isn't dipslayed on the menu, you can only find it on settings-->app

3) The icon is the android default icon and not my own icon

Here's my manifest :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.package">

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

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

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

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

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

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

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

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

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

<uses-feature
    android:name="android.hardware.touchscreen"
    android:required="false" />
<uses-feature
    android:name="android.software.leanback"
    android:required="true" />
<uses-feature
    android:name="android.hardware.location.gps"
    android:required="false" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar">
    <activity android:name=".MainActivity"
        android:banner="@drawable/my_logo_temp"
        android:icon="@drawable/my_logo_temp"
        android:label="@string/app_name"
        android:logo="@drawable/my_logo_temp"
        android:screenOrientation="landscape">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name=".account.AuthenticatorService"
        android:exported="true"
        android:process=":auth" >
        <intent-filter>
            <action android:name="android.accounts.AccountAuthenticator" />
        </intent-filter>

        <meta-data
            android:name="android.accounts.AccountAuthenticator"
            android:resource="@xml/auth" />
    </service>
</application>

</manifest>

Body:
Here is the answer hope this Help you.

Case 3 : Remove banner and icon from Mainactivity It should be always on Application tag so put it in the application tag.

Case 2 : Remove Existing Theme and Apply android:theme="@style/Theme.Leanback" on application tag.

I always Prefer to write this much of code when start developing TV application.

<uses-feature
    android:name="android.hardware.touchscreen"
    android:required="false" />
<uses-feature
    android:name="android.software.leanback"
    android:required="true" />
<uses-feature
    android:name="android.hardware.faketouch"
    android:required="false" />
<uses-feature
    android:name="android.hardware.telephony"
    android:required="false" />
<uses-feature
    android:name="android.hardware.camera"
    android:required="false" />
<uses-feature
    android:name="android.hardware.nfc"
    android:required="false" />
<uses-feature
    android:name="android.hardware.location.gps"
    android:required="false" />
<uses-feature
    android:name="android.hardware.microphone"
    android:required="false" />
<uses-feature
    android:name="android.hardware.sensor"
    android:required="false" />

<supports-screens
    android:largeScreens="true"
    android:normalScreens="false"
    android:requiresSmallestWidthDp="720"
    android:smallScreens="false"
    android:xlargeScreens="true" />

    <-- Your Permission -->
    <-- You Application Tag -->

Don't Forget to add compile 'com.android.support:leanback-v17:23.2.1' dependency in your build.gradle file. I was used this dependency when created the app you can change the version according to your project.

Try this one may be this help you.

For Case 1 : Permission issue it will be resolved if do all the above steps.


问:
Own Set whih inherited from List<int>
Hi I want create class Set which inherited from List<int>

```<code>class Set : List<int>
{
  public void Add(tmp)
  public void Pop(tmp)
  public print()
}
</code>```

But I have problem how should look consturctor could someone give me example?
I know how should looks methods(I will write them myself).

答:
List<T> has a parameterless constructor, so you don't need to do anything within your constructor.

You can even omit it altogether if you don't plan on adding constructors with parameters, it'll automatically run the empty  constructor on the base class when you create a new Set():

```<code>class Set : List<int>
{
    public new void Add(int tmp)
    {
        // custom logic here
        base.Add(tmp);
    }
}

Set myset = new Set();
myset.Add(43);
</code>```

Note that you chose to inherit from List<int>, which means that all members defined by List<int> are also available on your Set class. An alternative solution is to wrap the list:

```<code>class Set : IEnumerable<int>
{
    private readonly List<int> wrappedCollection = new List<int>();

    public void Add(int value)
    {
        wrappedCollection.Add(value);
    }

    ...
}
</code>```

This way you can choose which interfaces you want to implement, and add additional functionality like your print() method.

Title: Own Set whih inherited from List<int>

Body:
Hi I want create class Set which inherited from List<int>

class Set : List<int>
{
  public void Add(tmp)
  public void Pop(tmp)
  public print()
}

But I have problem how should look consturctor could someone give me example?
I know how should looks methods(I will write them myself).

Body:
List<T> has a parameterless constructor, so you don't need to do anything within your constructor.

You can even omit it altogether if you don't plan on adding constructors with parameters, it'll automatically run the empty  constructor on the base class when you create a new Set():

class Set : List<int>
{
    public new void Add(int tmp)
    {
        // custom logic here
        base.Add(tmp);
    }
}

Set myset = new Set();
myset.Add(43);

Note that you chose to inherit from List<int>, which means that all members defined by List<int> are also available on your Set class. An alternative solution is to wrap the list:

class Set : IEnumerable<int>
{
    private readonly List<int> wrappedCollection = new List<int>();

    public void Add(int value)
    {
        wrappedCollection.Add(value);
    }

    ...
}

This way you can choose which interfaces you want to implement, and add additional functionality like your print() method.


问:
How to joint two set of retrieved data using LinQ To Entities
I am using dbcontext Code first to get a query base on this condition for the Classes (tables) below:

Creator != null && ArticleAttached != null && !IsCancelled

Problem :

How to get data from the classes (tables) and show

Article Title, No. of Likes, No. Of Comments,  Total Assigned, TotalResponded

```<code>A) I use dbcontext as follows:

  var ListArticles = dbcontext.LearningActivites
   .Where(la => la.Creator != null && la.ArticleAttached != null && !la.IsCancelled)
   .Select(la =>
      new
      {
        Id = la.Id,
        Title = la.ArticleAttached.ArticleTitle,
        CreatedWhen = la.ArticleAttached.CreatedAt,
        TTLComment = la.ArticleAttached.Comments.Count,
        TTLOfLikes = la.ArticleAttached.StudentsLiked.Count + la.ArticleAttached.TeachersLiked.Count

      });

This will get :

 Article Title, Total of Likes, total Comment
</code>```

B) How to get : Total Assigned  and Total Responded base on the classes below?

```<code> var TotalAssigned = dbcontext.LearningActivites
 .Where(la => la.Creator != null && la.ArticleAttached != null && !la.IsCancelled)
 .Sum(la => la.ClassesAssigned.SelectMany(a => a.LearningActivitiesAssigned.LongCount));
</code>```

C) How to joint the result from A + B ?

to show

Article Title, No. of Likes, No. Of Comments, Total Assigned, TotalResponded

Classes:

```<code> public class LearningActivity
 {
   public virtual ArticleCreator Creator { get; set; }
   public virtual ArticleCreator EditedBy { get; set; }
   public virtual Teacher CreatedByTeacher { get; set; }
   public virtual Article ArticleAttached { get; set; }
   public virtual Article ArticleAttachedByOther { get; set; }

   public virtual IList<Class> ClassesAssigned { get; set; }
   public virtual IList<Group> GroupsAssigned { get; set; }

   public bool IsCancelled { get; set; }
 }

 public class Article
 {
   public string ArticleTitle {get;set;}
   public virtual IList<Teacher> TeachersLiked { get; set; }
   public virtual IList<Student> StudentsLiked { get; set; }
   public virtual IList<ArticleComment> Comments { get; set; }
 }

 public class Student
 {
   public virtual IList<ArticleCommentStudent> Comments { get; set; }
 }

 public class Class
 {
   public virtual School School { get; set; }
   public virtual IList<Student> Students { get; set; }
   public virtual IList<LearningActivity> LearningActivitiesAssigned { get; set; }

 }

 public class Group
 {
  public virtual School School { get; set; }
  public virtual IList<Student> Students { get; set; }
  public virtual ApplicationUser Creator { get; set; }

}
</code>```

Thanks

答:
Can you use this to sum of Assigned

TotalAssigned = la.ClassesAssigned.Sum(x => x.LearningActivitiesAssigned.LongCount)

and .GroupBy(la => la.ArticleAttached.ArticleTitle)

```<code>var ListArticles = dbcontext.LearningActivites
   .GroupBy(la => la.ArticleAttached.ArticleTitle)
   .Where(la => la.Creator != null && la.ArticleAttached != null && !la.IsCancelled)
   .Select(la =>
      new
      {
        Id = la.Id,
        Title = la.ArticleAttached.ArticleTitle,
        CreatedWhen = la.ArticleAttached.CreatedAt,
        TTLComment = la.ArticleAttached.Comments.Count,
        TTLOfLikes = la.ArticleAttached.StudentsLiked.Count + la.ArticleAttached.TeachersLiked.Count
        TotalAssigned = la.ClassesAssigned.Sum(x => x.LearningActivitiesAssigned.LongCount)
      });
</code>```

Body:
I am using dbcontext Code first to get a query base on this condition for the Classes (tables) below:

Creator != null && ArticleAttached != null && !IsCancelled

Problem :

How to get data from the classes (tables) and show

Article Title, No. of Likes, No. Of Comments,  Total Assigned, TotalResponded

A) I use dbcontext as follows:

  var ListArticles = dbcontext.LearningActivites
   .Where(la => la.Creator != null && la.ArticleAttached != null && !la.IsCancelled)
   .Select(la =>
      new
      {
        Id = la.Id,
        Title = la.ArticleAttached.ArticleTitle,
        CreatedWhen = la.ArticleAttached.CreatedAt,
        TTLComment = la.ArticleAttached.Comments.Count,
        TTLOfLikes = la.ArticleAttached.StudentsLiked.Count + la.ArticleAttached.TeachersLiked.Count

      });

This will get :

 Article Title, Total of Likes, total Comment

B) How to get : Total Assigned  and Total Responded base on the classes below?

 var TotalAssigned = dbcontext.LearningActivites
 .Where(la => la.Creator != null && la.ArticleAttached != null && !la.IsCancelled)
 .Sum(la => la.ClassesAssigned.SelectMany(a => a.LearningActivitiesAssigned.LongCount));

C) How to joint the result from A + B ?

to show

Article Title, No. of Likes, No. Of Comments, Total Assigned, TotalResponded

Classes:

 public class LearningActivity
 {
   public virtual ArticleCreator Creator { get; set; }
   public virtual ArticleCreator EditedBy { get; set; }
   public virtual Teacher CreatedByTeacher { get; set; }
   public virtual Article ArticleAttached { get; set; }
   public virtual Article ArticleAttachedByOther { get; set; }

   public virtual IList<Class> ClassesAssigned { get; set; }
   public virtual IList<Group> GroupsAssigned { get; set; }

   public bool IsCancelled { get; set; }
 }

 public class Article
 {
   public string ArticleTitle {get;set;}
   public virtual IList<Teacher> TeachersLiked { get; set; }
   public virtual IList<Student> StudentsLiked { get; set; }
   public virtual IList<ArticleComment> Comments { get; set; }
 }

 public class Student
 {
   public virtual IList<ArticleCommentStudent> Comments { get; set; }
 }

 public class Class
 {
   public virtual School School { get; set; }
   public virtual IList<Student> Students { get; set; }
   public virtual IList<LearningActivity> LearningActivitiesAssigned { get; set; }

 }

 public class Group
 {
  public virtual School School { get; set; }
  public virtual IList<Student> Students { get; set; }
  public virtual ApplicationUser Creator { get; set; }

}

Thanks

Body:
Can you use this to sum of Assigned

TotalAssigned = la.ClassesAssigned.Sum(x => x.LearningActivitiesAssigned.LongCount)

and .GroupBy(la => la.ArticleAttached.ArticleTitle)

var ListArticles = dbcontext.LearningActivites
   .GroupBy(la => la.ArticleAttached.ArticleTitle)
   .Where(la => la.Creator != null && la.ArticleAttached != null && !la.IsCancelled)
   .Select(la =>
      new
      {
        Id = la.Id,
        Title = la.ArticleAttached.ArticleTitle,
        CreatedWhen = la.ArticleAttached.CreatedAt,
        TTLComment = la.ArticleAttached.Comments.Count,
        TTLOfLikes = la.ArticleAttached.StudentsLiked.Count + la.ArticleAttached.TeachersLiked.Count
        TotalAssigned = la.ClassesAssigned.Sum(x => x.LearningActivitiesAssigned.LongCount)
      });


问:
How to Learn MS SQL Server 2005?
I would like to start learning SQL Server 2005 on my own.  Can anyone recommend good books or websites that will be a good start for me?</p>

答:
For heavier TSQL questions, I found this blog useful :

http://www.sommarskog.se/

OwnerDisplayName: Craig G

Title: How to Learn MS SQL Server 2005?

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: Ash Machine


问:
LINQ Query to check for a predicate in all columns in a table
I have a table with 30 columns,
and it contains 1000 rows.
I want a single LINQ query,  which checks for a particular value in all columns and converts the result into a list.

For example:

```<code>table.where(allcolumnvalue.contains(searchvalue)).Tolist()
</code>```

How to accomplish the above using one LINQ query. Any help is much appreciated.

答:
For your request all of fields should have same type, at least in the static typed C#.

The method Queriable.Where gets the Expression<Func<T, bool>> predicate as parameter. So you need build the predicate o.p1 == val || o.p2 == val || o.p3 = val ... as Expression value. Here o is a parameter of Expression<Func<T, bool>>:

```<code>public Expression BuildExpression<TObj, TVal>(TObj obj, TVal val)
{
    Expression<Func<TObj, bool>> predicate = (o) => o.p1 == val || ... || o.pN == val;
    return predicate;
}
</code>```

but we need build predicate dynamically for all properties of TObj that have type TVal.

To simplify the code we will build equal expression false || o.p1 == val || ... || o.pN == val.

```<code>public Expression<Func<TObj, bool>> BuildExpression<TObj, TVal>(TVal val)
{
    var parameter = Expression.Parameter(typeof(TObj), "o");
    var valExpression = Expression.Constant(val, typeof(TVal));
    var body = Expression.Constant(false, typeof(bool));

    var properties = typeof(TObj).GetProperties()
                                 .Where(p => p.PropertyType == typeof(TVal));
    foreach (var property in properties)
    {
        var propertyExpression = Expression.Property(parameter, property);
        var equalExpression = Expression.Equal(propertyExpression, valExpression);
        body = Expression.Or(body, equalExpression);
    }

    return Expression.Lambda<Func<TObj, bool>>(body, parameter);
}

. . .

using (var dbContext = new DbContext())
{
    var whereExpression = BuildExpression<User, string>("foo");
    var contaningsFoo = dbContext.Users.Where(whereExpression);
}
</code>```

Body:
I have a table with 30 columns,
and it contains 1000 rows.
I want a single LINQ query,  which checks for a particular value in all columns and converts the result into a list.

For example:

table.where(allcolumnvalue.contains(searchvalue)).Tolist()

How to accomplish the above using one LINQ query. Any help is much appreciated.

Body:
For your request all of fields should have same type, at least in the static typed C#.

The method Queriable.Where gets the Expression<Func<T, bool>> predicate as parameter. So you need build the predicate o.p1 == val || o.p2 == val || o.p3 = val ... as Expression value. Here o is a parameter of Expression<Func<T, bool>>:

public Expression BuildExpression<TObj, TVal>(TObj obj, TVal val)
{
    Expression<Func<TObj, bool>> predicate = (o) => o.p1 == val || ... || o.pN == val;
    return predicate;
}

but we need build predicate dynamically for all properties of TObj that have type TVal.

To simplify the code we will build equal expression false || o.p1 == val || ... || o.pN == val.

public Expression<Func<TObj, bool>> BuildExpression<TObj, TVal>(TVal val)
{
    var parameter = Expression.Parameter(typeof(TObj), "o");
    var valExpression = Expression.Constant(val, typeof(TVal));
    var body = Expression.Constant(false, typeof(bool));

    var properties = typeof(TObj).GetProperties()
                                 .Where(p => p.PropertyType == typeof(TVal));
    foreach (var property in properties)
    {
        var propertyExpression = Expression.Property(parameter, property);
        var equalExpression = Expression.Equal(propertyExpression, valExpression);
        body = Expression.Or(body, equalExpression);
    }

    return Expression.Lambda<Func<TObj, bool>>(body, parameter);
}

. . .

using (var dbContext = new DbContext())
{
    var whereExpression = BuildExpression<User, string>("foo");
    var contaningsFoo = dbContext.Users.Where(whereExpression);
}


问:
given current datetime how do i determine the the nearest time before and after from a given dateime array
Given a list of times, how do I get the nearest times in the past and the nearest time in the future in java: for example current is 2017-06-06T12:04:00 and the list  2017-06-06T11:00:00, 2017-06-06T11:30:00, 2017-06-06T12:00:00, 2017-06-06T12:30:00. In this case i am expecting the to get 2017-06-06T12:00:00 and 2017-06-06T12:30:00.</p>

答:
Parse the strings as date objects, for example a LocalDateTime, which needs to be Comparable.

put them in an TreeSet

use TreeSet::floor and TreeSet:ceiling to get the closest time


问:
populate json data into html table using ajax call
i am trying to populate json data produced by rest web services into html table. this is my html code

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee List</title>
</head>
<body>
    <h1>Employee List</h1>
    <form>
        <table  id= "content">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Age</th>
                <th>Salary</th>
                <th>Address</th>
            </tr>
        </thead>
        <tbody id = "emp">
        </tbody>
        </table>
    </form>
    <script>

    $(document).ready(function(){
        alert("1");
        var data = $("#employee").val();
        alert("2");
        $.ajax({

            url: '/rest/restemployees',
            type: 'GET',
            dataType: 'JSON',
            success: function(data){
                alert("3");
                $.each(data, function(i,value){
                    $("#content tbody").append("<tr>" + "<td>" + value.id + "</td>" +
                            "<td>" + value.name + "</td>" +
                            "<td>" + value.age + "</td>" +
                            "<td>" + value.salary + "</td>" +
                            "<td>" + value.address + "</td>" + "</tr>")
                });

            },
            error: function(data){
                alert("4");
            }

        });
    });

    </script>
</body>
</html>
</code>```

please help me

note: alerts are used just to know the flow

Content is the table id. i don't know where the mistake is. can anyone help me to solve this

答:
I would do something like

```<code>success: function(data){
                alert("3");
              $(data).each(function(){
                    $('#tbody').append('<tr><td>' + this.id + '</td><td>' + this.name + '</td><td>' + this.age + '</td><td>' + this.salary + '</td><td>' + this.address + '</td></tr>')
                });
</code>```

and instead of giving table id just put an id to table body where you want to append

Body:
i am trying to populate json data produced by rest web services into html table. this is my html code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee List</title>

Employee List

    <form>

                Id
                Name
                Age
                Salary
                Address

    </form>

please help me

note: alerts are used just to know the flow

Content is the table id. i don't know where the mistake is. can anyone help me to solve this

Body:
I would do something like

success: function(data){
                alert("3");
              $(data).each(function(){
                    $('#tbody').append('<tr><td>' + this.id + '</td><td>' + this.name + '</td><td>' + this.age + '</td><td>' + this.salary + '</td><td>' + this.address + '</td></tr>')
                });

and instead of giving table id just put an id to table body where you want to append


问:
New Array's key should be another Array's value
I want to create new array.

Value of element in array should be blank.

Key of array should another array's value.

```<code>$Oldarr =  Array
(
    [0] => Webseite,
    [1] => Bestellung,
    [2] => Verkäufer,
    [3] => Käufer,
    [4] => Warenwert,
    [5] => Lieferkosten,
    [6] => Produktname,
    [7] => Article Nr,
    [8] => Anzahl
);
</code>```

And New array shoud be

```<code>$Newarr =  Array
(
    ['Bestellung'] => '',
    ['Verkäufer'] => '',
    ['Käufer'] => '',
    ['Warenwert'] => '',
    ['Lieferkosten'] => '',
    ['Produktname'] => '',
    ['Article Nr'] => '',
    ['Anzahl'] => ''
);
</code>```

答:
You can use following code:</p>

```<code>$new = array_flip($Oldarr);
$new = array_fill_keys($Oldarr,'');
</code>```

Body:
I want to create new array.

Value of element in array should be blank.

Key of array should another array's value.

$Oldarr =  Array
(
    [0] => Webseite,
    [1] => Bestellung,
    [2] => Verkäufer,
    [3] => Käufer,
    [4] => Warenwert,
    [5] => Lieferkosten,
    [6] => Produktname,
    [7] => Article Nr,
    [8] => Anzahl
);

And New array shoud be

$Newarr =  Array
(
    ['Bestellung'] => '',
    ['Verkäufer'] => '',
    ['Käufer'] => '',
    ['Warenwert'] => '',
    ['Lieferkosten'] => '',
    ['Produktname'] => '',
    ['Article Nr'] => '',
    ['Anzahl'] => ''
);

Body:
You can use following code:

$new = array_flip($Oldarr);
$new = array_fill_keys($Oldarr,'');


问:
How to rollback transaction in Spring JDBC?
I want to do several inserts in my method, and want to rollback all the inserts if anything goes wrong.
Here's my jdbc bean definition

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>
</code>```

And here's my method

```<code>@Transactional
public void save(Map<String, String> properties, Long moduleId,
                 String language, String propertyFileName, String filePath) {

    KeyHolder keyHolder = new GeneratedKeyHolder();

    final String propertyFileQuery = "INSERT INTO property_file " +
            "(moduleId, languageId, propertyFileName,hash,path) " +
            "VALUES (?,?,?,?,?)";

    jdbcTemplate.update(connection -> {
        PreparedStatement ps =
                connection.prepareStatement(propertyFileQuery, new String[]{"id"});
        ps.setLong(1, moduleId);
        ps.setString(2, language);
        ps.setString(3, propertyFileName);
        ps.setString(4, "hash goes here");
        ps.setString(5, filePath);

        return ps;
    }, keyHolder);

    int x = 0 / 0;

    final String propertiesQuery = "INSERT INTO property_value " +
            "(propertyFileId, propKey, propValue) " +
            "VALUES (?,?,?)";

    properties.forEach((key, value) -> jdbcTemplate.update(
            propertiesQuery, keyHolder.getKey(), key, value
    ));

}
</code>```

I want it to rollback the first insert, after it meets the runtime exception 0/0

But the data goes into the database, and doesn't get rolled back.

What am i doing wrong?

答:
Found out the reason. The transaction management was ok, the reason I couldn't do my job in a transaction was because of my MySQL Engine. It was set to MyISAM.
As cited in MySQL web site

MyISAM does not support transactions and probably never will.

Just changed the tables from MyISAM to InnoDb, and got it working.

Body:
I want to do several inserts in my method, and want to rollback all the inserts if anything goes wrong.
Here's my jdbc bean definition

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

And here's my method

@Transactional
public void save(Map<String, String> properties, Long moduleId,
                 String language, String propertyFileName, String filePath) {

    KeyHolder keyHolder = new GeneratedKeyHolder();

    final String propertyFileQuery = "INSERT INTO property_file " +
            "(moduleId, languageId, propertyFileName,hash,path) " +
            "VALUES (?,?,?,?,?)";

    jdbcTemplate.update(connection -> {
        PreparedStatement ps =
                connection.prepareStatement(propertyFileQuery, new String[]{"id"});
        ps.setLong(1, moduleId);
        ps.setString(2, language);
        ps.setString(3, propertyFileName);
        ps.setString(4, "hash goes here");
        ps.setString(5, filePath);

        return ps;
    }, keyHolder);

    int x = 0 / 0;

    final String propertiesQuery = "INSERT INTO property_value " +
            "(propertyFileId, propKey, propValue) " +
            "VALUES (?,?,?)";

    properties.forEach((key, value) -> jdbcTemplate.update(
            propertiesQuery, keyHolder.getKey(), key, value
    ));

}

I want it to rollback the first insert, after it meets the runtime exception 0/0

But the data goes into the database, and doesn't get rolled back.

What am i doing wrong?


问:
WSO2 DSS - Odata
When configuring a WSO2 DSS datasource, I have checked the 'Enable ODATA' option. I have verified that, ODATA endpoints are available for Oracle tables, but not Oracle views.

Does WSO2 DSS support for creating ODATA endpoints for Oracle views?

答: Currently, it is not supported for Oracle views. You can use this jira ticket to track this improvement.</p>

Title: WSO2 DSS - Odata


问:
How to design a method that contains lots of IF's or Switch statements
How can i make the design of this class more dynamic so i can add new extensions and types as required.

```<code>public class Processor
{
    public Processor(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        if(extension == "jpg" || extension == "gif" || extension == "png")
        {
            //Process Image file type
        }
        else if(extension == "xls" || extension == "xlsx")
        {
            //Process spreadsheet type
        }
        else if(extension == "doc" || extension == "docx")
        {
            //Process document file type
        }
        //and so forth ...
    }
}
</code>```

We may need to process .tiff files in future or we may need to process video files, which means a new if branch

```<code>else if(extension == "avi" || extension == "mp4")
{
    //Process video file type
}
</code>```

As you can see this can get very long.

The valid files types and groups are stored in a DB...

Can anyone recommend any patterns or clever ideas to solve this problem?
Cheers

答:
Use a dictionary.

```<code>Dictionary<string, IFileHandler> fileHandlers = new Dictionary<string, IFileHandler>
{
    { "jpg", imageHander },
    { "gif", imageHander },
    { "xls", spreadsheetHander },
    // ...
};
</code>```

Then use it as follows:

```<code>public void Process(string fileName)
{
    string extension = Path.GetExtension(fileName);

    // TODO: What should happen if the filetype is unknown?
    fileHandlers[extension].Process(fileName);
}
</code>```

The valid files types and groups are stored in a DB...

Then you probably want to query the database to get the correct group from the extension and use the group as the dictionary key rather than the extension.

Body:
How can i make the design of this class more dynamic so i can add new extensions and types as required.

public class Processor
{
    public Processor(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        if(extension == "jpg" || extension == "gif" || extension == "png")
        {
            //Process Image file type
        }
        else if(extension == "xls" || extension == "xlsx")
        {
            //Process spreadsheet type
        }
        else if(extension == "doc" || extension == "docx")
        {
            //Process document file type
        }
        //and so forth ...
    }
}

We may need to process .tiff files in future or we may need to process video files, which means a new if branch

else if(extension == "avi" || extension == "mp4")
{
    //Process video file type
}

As you can see this can get very long.

The valid files types and groups are stored in a DB...

Can anyone recommend any patterns or clever ideas to solve this problem?
Cheers

Body:
Use a dictionary.

Dictionary<string, IFileHandler> fileHandlers = new Dictionary<string, IFileHandler>
{
    { "jpg", imageHander },
    { "gif", imageHander },
    { "xls", spreadsheetHander },
    // ...
};

Then use it as follows:

public void Process(string fileName)
{
    string extension = Path.GetExtension(fileName);

    // TODO: What should happen if the filetype is unknown?
    fileHandlers[extension].Process(fileName);
}

The valid files types and groups are stored in a DB...

Then you probably want to query the database to get the correct group from the extension and use the group as the dictionary key rather than the extension.


问:
How to avoid axis line disappearing when using ggarrange?
I'd like to arrange two facet plots using ggarrange (in order to get x axes aligned).

```<code>library(egg)
library(ggplot2)

p1 <- ggplot(warpbreaks) +
  geom_bar(aes(x = wool)) +
  facet_wrap(~tension, ncol = 2, scales = "free_x") +
  theme_bw() +
  theme(axis.line = element_line(colour = "black", size = .1),
        panel.border = element_blank(),
        strip.background = element_blank())

p2 <- ggplot(warpbreaks) +
  geom_bar(aes(x = tension)) +
  facet_wrap(~wool) +
  theme_bw() +
  theme(axis.line = element_line(colour = "black", size = .1),
        panel.border = element_blank(),
        strip.background = element_blank())

ggarrange(p1, p2, ncol = 2)
</code>```

Works great, but unfortunately the vertical axis lines disappeared. This does not happen when using grid.arrange, but at least for my real data there the x axes are not aligned, hence my wish to use ggarrange. Is there a way to keep the axis lines?

答:
tl;dr: setting panel.background = element_blank() should restore the axes.

I think it's a combination of a clipping issue in ggplot2 (the y axis line can be clipped by the plot panel, cutting its width in half), and egg::gtable_frame placing the axis below the plot panel.

```<code>library(egg)
library(ggplot2)

p1 <- ggplot(warpbreaks) +
  geom_bar(aes(x = wool)) +
  facet_wrap(~tension, ncol = 2, scales = "free_x") +
  theme_bw() +
  theme(axis.line = element_line(colour = alpha("red", 0.5), size = 5),
        panel.border = element_blank(),
        panel.background = element_rect(fill = alpha("white", 0.5),
                                        linetype = 2, colour = "black"),
        strip.background = element_blank())

p1
</code>```

```<code>g1 <- ggplotGrob(p1)
gg <- gtable_frame(g1)
grid.newpage()
grid.draw(gg)
</code>```

Body:
I'd like to arrange two facet plots using ggarrange (in order to get x axes aligned).

library(egg)
library(ggplot2)

p1 <- ggplot(warpbreaks) +
  geom_bar(aes(x = wool)) +
  facet_wrap(~tension, ncol = 2, scales = "free_x") +
  theme_bw() +
  theme(axis.line = element_line(colour = "black", size = .1),
        panel.border = element_blank(),
        strip.background = element_blank())

p2 <- ggplot(warpbreaks) +
  geom_bar(aes(x = tension)) +
  facet_wrap(~wool) +
  theme_bw() +
  theme(axis.line = element_line(colour = "black", size = .1),
        panel.border = element_blank(),
        strip.background = element_blank())

ggarrange(p1, p2, ncol = 2)

Works great, but unfortunately the vertical axis lines disappeared. This does not happen when using grid.arrange, but at least for my real data there the x axes are not aligned, hence my wish to use ggarrange. Is there a way to keep the axis lines?

Body:
tl;dr: setting panel.background = element_blank() should restore the axes.

I think it's a combination of a clipping issue in ggplot2 (the y axis line can be clipped by the plot panel, cutting its width in half), and egg::gtable_frame placing the axis below the plot panel.

library(egg)
library(ggplot2)

p1 <- ggplot(warpbreaks) +
  geom_bar(aes(x = wool)) +
  facet_wrap(~tension, ncol = 2, scales = "free_x") +
  theme_bw() +
  theme(axis.line = element_line(colour = alpha("red", 0.5), size = 5),
        panel.border = element_blank(),
        panel.background = element_rect(fill = alpha("white", 0.5),
                                        linetype = 2, colour = "black"),
        strip.background = element_blank())

p1

g1 <- ggplotGrob(p1)
gg <- gtable_frame(g1)
grid.newpage()
grid.draw(gg)


问:
Change color of bootstrap navbar on hover link?
I want to know how to change the color of the links when you hover over them in the nav bar, as currently they are an ugly color.

Thanks for any suggestions?

HTML:

```<code><div class="container">
    <div class="navbar">
        <div class="navbar-inner">
            <ul class="nav">
                <li class="active"><a href="#">Home</a></li>
                <li><a href="#">Link One</a></li>
                <li><a href="#">Link Two</a></li>
                <li><a href="#">Link Three</a></li>
            </ul>
        </div>
    </div>
</div>
</code>```

答:
Sorry for late reply. You can only use:</p>

```<code>   nav a:hover{

                   background-color:color name !important;

                 }
</code>```

Body:
I want to know how to change the color of the links when you hover over them in the nav bar, as currently they are an ugly color.

Thanks for any suggestions?

HTML:

Home

Link One

Link Two

Link Three

Body:
Sorry for late reply. You can only use:

   nav a:hover{

                   background-color:color name !important;

                 }


问:
GNU Parallel: Argument list too long when calling function
I created a script to verify a (big) number of items and it was doing the verification in a serial way (one after the other) with the end result of the script taking about 9 hours to complete. Looking around about how to improve this, I found GNU parallel but I'm having problems making it work.

The list of items is in a text file so I was doing the following:

```<code>readarray items < ${ALL_ITEMS}
export -f process_item
parallel process_item ::: "${items[@]}"
</code>```

Problem is, I receive an error:

```<code>GNU parallel: Argument list too long
</code>```

I understand by looking at similar posts 1, 2, 3 that this is more a Linux limitation than a GNU parallel one. From the answers to those posts I also tried to extrapolate a workaround by piping the items to head but the result is that only a few items (the parameter passed to head) are processed.

I have been able to make it work using xargs:

```<code>cat "${ALL_ITEMS}" | xargs -n 1 -P ${THREADS} -I {} bash -c 'process_item "$@"' _ {}
</code>```

but I've seen GNU parallel has other nice features I'd like to use.

Any idea how to make this work with GNU parallel? By the way, the number of items is about 2.5 million and growing every day (the script run as a cron job).

Thanks

答:
From man parallel:

```<code>parallel [options] [command [arguments]] < list_of_arguments
</code>```

So:

```<code>export -f process_item
parallel process_item < ${ALL_ITEMS}
</code>```

probably does what you want.

Body:
I created a script to verify a (big) number of items and it was doing the verification in a serial way (one after the other) with the end result of the script taking about 9 hours to complete. Looking around about how to improve this, I found GNU parallel but I'm having problems making it work.

The list of items is in a text file so I was doing the following:

readarray items < ${ALL_ITEMS}
export -f process_item
parallel process_item ::: "${items[@]}"

Problem is, I receive an error:

GNU parallel: Argument list too long

I understand by looking at similar posts 1, 2, 3 that this is more a Linux limitation than a GNU parallel one. From the answers to those posts I also tried to extrapolate a workaround by piping the items to head but the result is that only a few items (the parameter passed to head) are processed.

I have been able to make it work using xargs:

cat "${ALL_ITEMS}" | xargs -n 1 -P ${THREADS} -I {} bash -c 'process_item "$@"' _ {}

but I've seen GNU parallel has other nice features I'd like to use.

Any idea how to make this work with GNU parallel? By the way, the number of items is about 2.5 million and growing every day (the script run as a cron job).

Thanks

Body:
From man parallel:

parallel [options] [command [arguments]] < list_of_arguments

So:

export -f process_item
parallel process_item < ${ALL_ITEMS}

probably does what you want.


问:
org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'templates/email/test.vm'
My code as follow.

```<code>VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
        ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        ve.init();
        Template tempalte = ve.getTemplate("templates/email/test.vm");
</code>```

I am getting following error.

org.apache.velocity.exception.ResourceNotFoundException: Unable to
  find resource 'templates/email/test.vm'   at
  org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:452)
    at
  org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:335)
    at
  org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1102).....

"template" folder is in my src folder.

If I directly put the velocity template file into src folder and
  update as "Template tempalte = ve.getTemplate("test.vm");" it works.

I am using Mac OS, Java 1.8, Eclipse Neon.

Please help me to solve this.

Thanks and Regards,
IsuruJ

答:
Thanks for your time.
This is an ANT project. Mistakenly I couldn't write script to copy templates folder to WEB-INF/classes folder. That was the issue. Both @user7294900 and @soorapadman are correct. The code works now.

Really sorry for the inconvenience.

Best Regards,
IsuruJ

Body:
My code as follow.

VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
        ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        ve.init();
        Template tempalte = ve.getTemplate("templates/email/test.vm");

I am getting following error.

org.apache.velocity.exception.ResourceNotFoundException: Unable to
  find resource 'templates/email/test.vm'   at
  org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:452)
    at
  org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:335)
    at
  org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1102).....

"template" folder is in my src folder.

If I directly put the velocity template file into src folder and
  update as "Template tempalte = ve.getTemplate("test.vm");" it works.

I am using Mac OS, Java 1.8, Eclipse Neon.

Please help me to solve this.

Thanks and Regards,
IsuruJ


答:
You can pipe the file to parallel, or just use the -a (--arg-file) option. The following are equvalent:

```<code>cat "${ALL_ITEMS}" | parallel process_item
parallel process_item < "${ALL_ITEMS}"
parallel -a "${ALL_ITEMS}" process_item
parallel --arg-file "${ALL_ITEMS}" process_item
parallel process_item :::: "${ALL_ITEMS}"
</code>```

Title: GNU Parallel: Argument list too long when calling function

Body:
You can pipe the file to parallel, or just use the -a (--arg-file) option. The following are equvalent:

cat "${ALL_ITEMS}" | parallel process_item
parallel process_item < "${ALL_ITEMS}"
parallel -a "${ALL_ITEMS}" process_item
parallel --arg-file "${ALL_ITEMS}" process_item
parallel process_item :::: "${ALL_ITEMS}"


问:
SQL Server refactor a column from varchar(50) to uniqueidentifier and surrounding issues
I have a table message in a database that has almost a million rows. It has a externalId column which is varchar(50). The values stored in it are guid but I want to update this column to be uniqueidentifier.

So I think I am going to add a new column which is uniqueidentifier. Copy all the values across to this column and then drop the original column. Then I will rename this column to externalId.

My problem is there are hundreds of stored procs etc and I need to make sure that I don't break anything. I also have to grep through all the code and make changes so that we expect a Guid and not a string. (I am using C#)

Does anyone have some tips or recommendations?

Would I be better do just duplicate this column and not touch the existing column and make any code that does a select on it use the guid column instead of the string (currently it sometimes times-out!). I would also have to update any code then that inserts into this table to also insert a guid...)

I love legacy crap .......................

答:
One very quick and safe way to check if you break anything on your dev system is to rename your table the message_legacy and make a view called message which casts externalid to uniqueidentifier.  That shouldn't mess with the underlying data but will give you a workable interface to see how your stored procs and other code will behave.  Remember to grant the same permissions to this view as you have on the table or you might get errors which are permission related instead of type related, which is what you really want to test.

If you get an acceptable result, then go ahead and change the column definition.  Personally, I'd rename the table, create a new table with the column type changed, insert into new_table select * from old_table, then drop the old table.

Good luck!


问:
Can’t find my artifacts with GitLab CI
I'm using a shared runner, on gitlab.com. The guide here shows a section for job artifacts. But when I run my job and look at my job page, I just see this:

There's no section for job artifacts.

What should I try?

Here's my .gitlab-ci.yml:

```<code>image: node:7.9

stages:
  - lint
  - test

cache:
  paths:
    - node_modules/

before_script:
  - npm install
  - npm install -g grunt-cli

lint:
  stage: lint
  script:
    - grunt lint

test:
  stage: test
  script:
    - grunt
    - grunt test
    - grunt coveralls
  artifacts:
    paths:
      - dist/project*.min.js*
</code>```

答:
There can be several reasons for this not happening. Most likely the file was never generated and as such was not available as an artifact. You can find the cause of this in the output itself.

Artifact upload is always logged in the output as well, for instance this is some debug in a build of mine:

```<code>Uploading artifacts...
storage/logs/lumen.log: found 1 matching files
Uploading artifacts to coordinator... ok            id=1444 responseStatus=201 Created token=MHYPxxWu
</code>```

If you don't see anything like that, most likely the reason why is also logged.

Title: Can’t find my artifacts with GitLab CI

Body:
I'm using a shared runner, on gitlab.com. The guide here shows a section for job artifacts. But when I run my job and look at my job page, I just see this:

There's no section for job artifacts.

What should I try?

Here's my .gitlab-ci.yml:

image: node:7.9

stages:
  - lint
  - test

cache:
  paths:
    - node_modules/

before_script:
  - npm install
  - npm install -g grunt-cli

lint:
  stage: lint
  script:
    - grunt lint

test:
  stage: test
  script:
    - grunt
    - grunt test
    - grunt coveralls
  artifacts:
    paths:
      - dist/project*.min.js*

Body:
There can be several reasons for this not happening. Most likely the file was never generated and as such was not available as an artifact. You can find the cause of this in the output itself.

Artifact upload is always logged in the output as well, for instance this is some debug in a build of mine:

Uploading artifacts...
storage/logs/lumen.log: found 1 matching files
Uploading artifacts to coordinator... ok            id=1444 responseStatus=201 Created token=MHYPxxWu

If you don't see anything like that, most likely the reason why is also logged.


问:
Android Studio - Unable to find valid certification path to requested target
I'm getting this error

Gradle 'project_name' project refresh failed: Unable to find valid certification path to requested target

when I create a new project on Android Studio 0.8.14 Mac OSX

Build.gradle file seems to become empty

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.13.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    } }

allprojects {
    repositories {
        jcenter()
    } }
</code>```

And I can't run the project, seems that I have to configure everything manually.

Here is the idea.log http://pastebin.com/kyhfrBp9

答:
If you are working in a restricted workplaces you probably will encounter this problem

A combination of a few things worked for me
Basically change https to http

From https:

```<code>repositories {
   jcenter()
}
</code>```

To :

```<code>repositories {
        maven { url "http://jcenter.bintray.com" }
   }
</code>```

and in gradle-wrapper.properties ..

From :

```<code>    distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
</code>```

To :

```<code>   distributionUrl=http\://services.gradle.org/distributions/gradle-3.3-all.zip
</code>```

And then

```<code>- (optional)  File -> Invalidate Caches / Restart`
- Give a clean build.
</code>```

To verify :  Check your Gradle console. It should start downloading libs from jcenter via HTTP.

Body:
I'm getting this error

Gradle 'project_name' project refresh failed: Unable to find valid certification path to requested target

when I create a new project on Android Studio 0.8.14 Mac OSX

Build.gradle file seems to become empty

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.13.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    } }

allprojects {
    repositories {
        jcenter()
    } }

And I can't run the project, seems that I have to configure everything manually.

Here is the idea.log http://pastebin.com/kyhfrBp9

Body:
If you are working in a restricted workplaces you probably will encounter this problem

A combination of a few things worked for me
Basically change https to http

From https:

repositories {
   jcenter()
}

To :

repositories {
        maven { url "http://jcenter.bintray.com" }
   }

and in gradle-wrapper.properties ..

From :

    distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip

To :

   distributionUrl=http\://services.gradle.org/distributions/gradle-3.3-all.zip

And then

- (optional)  File -> Invalidate Caches / Restart`
- Give a clean build.

To verify :  Check your Gradle console. It should start downloading libs from jcenter via HTTP.


问:
Same Ajax Response after Page Reload
I am building a website where I am loading the content through an Ajax request. So when the user clicks on a link I prevent a page reload and load the content with Ajax in the main area. Now I have the problem that if the user clicks on the refresh button they will be thrown away to the very first page. Is there a way to somehow store where the user is in the page in the moment and to recall that value at a reload so that I can call the same Ajax Request the user had last?

Let me know if you need any specific code.

Thanks a lot!

David

答: It's common for Single Page Applications to use hash parameters in the URL to keep a track of the page state.</p>

Title: Same Ajax Response after Page Reload


问:
Creating a New Array in a Particular Order
Once a particular promise is resolved, i wish to loop through each of the items in the response and push them into an array in a specific order.

status-start

status-in-progress

status-completed

How can I go about doing this? Here is my code so far:

```<code>dashService.getBatches(refresh)
.then(function (response) {
  if (response.error) {
    console.log("No data received");
  } else {
    angular.forEach(response.items, function (item) {
      if (item.status === 'start') {
        currentBatches.push(job);
      }
    });
  }
});
</code>```

答:
I would create a map of available options and their corresponding order, then sort your values to insert based on that map. Then once sorted iterate the array pushing them into your destination array. That or you could concat them once sorted to produce a new array.

```<code>const orderMap = {
  'status-start': 0,
  'status-in-progress': 1,
  'status-completed': 2
};

newData.sort((a, b) => {
  return orderMap[a] - orderMap[b];
}).forEach(d => {
  originalData.push(d);
});
</code>```

Heres a fiddle

Obviously you will need to change object structures etc, this is just a proof of concept. Also this is written in ES6, so no IE but it can be easily written in ES5.

EDIT: I see your sort is based on a sub property status updated the demo to reflect that.

https://jsfiddle.net/k0m2s1yt/2/

Body:
Once a particular promise is resolved, i wish to loop through each of the items in the response and push them into an array in a specific order.

status-start

status-in-progress

status-completed

How can I go about doing this? Here is my code so far:

dashService.getBatches(refresh)
.then(function (response) {
  if (response.error) {
    console.log("No data received");
  } else {
    angular.forEach(response.items, function (item) {
      if (item.status === 'start') {
        currentBatches.push(job);
      }
    });
  }
});

Body:
I would create a map of available options and their corresponding order, then sort your values to insert based on that map. Then once sorted iterate the array pushing them into your destination array. That or you could concat them once sorted to produce a new array.

const orderMap = {
  'status-start': 0,
  'status-in-progress': 1,
  'status-completed': 2
};

newData.sort((a, b) => {
  return orderMap[a] - orderMap[b];
}).forEach(d => {
  originalData.push(d);
});

Heres a fiddle

Obviously you will need to change object structures etc, this is just a proof of concept. Also this is written in ES6, so no IE but it can be easily written in ES5.

EDIT: I see your sort is based on a sub property status updated the demo to reflect that.

https://jsfiddle.net/k0m2s1yt/2/


问:
Own Set whih inherited from List<int>
Hi I want create class Set which inherited from List<int>

```<code>class Set : List<int>
{
  public void Add(tmp)
  public void Pop(tmp)
  public print()
}
</code>```

But I have problem how should look consturctor could someone give me example?
I know how should looks methods(I will write them myself).

答:
Within the class type ctor then hit tab twice, this will create the default constructor:

```<code>        public Set()
        {

        }
</code>```

Using Set as a class name could be confusing though as the 'set' keyword is used in properties

Title: Own Set whih inherited from List<int>

Body:
Hi I want create class Set which inherited from List<int>

class Set : List<int>
{
  public void Add(tmp)
  public void Pop(tmp)
  public print()
}

But I have problem how should look consturctor could someone give me example?
I know how should looks methods(I will write them myself).

Body:
Within the class type ctor then hit tab twice, this will create the default constructor:

        public Set()
        {

        }

Using Set as a class name could be confusing though as the 'set' keyword is used in properties


问:
"The imported project microsoft.dotnet.props was not found" when using AWS Lambda function
I have installed the .NET Core SDK as well as .NET Core Visual Studio 2015 Tooling Preview 2 along with AWS Visual Studio Toolkit as shown in the image below:

But even after installation, I am getting an error when trying to use the sample AWS Lambda function as shown in the image below:

How can I resolve this issue?

答: Used Offline Installation of .NET Core SDK as well as .NET Core Visual Studio 2015 Tooling Preview 2.</p>


Title: Format date string using gawk?

Body:
I have an issue that when running this code:

gawk 'BEGIN{FS=";";RS="\r\n"}
        {
            for (i = 1; i <= NF; i++) {
                if(match($i, /([0-9]{4})-([0-9]{2})-([0-9]{2})-([0-9]{2})\.([0-9]{2})\.([0-9]{2})\.([0-9]{6})/, m)){
                    $i =  m[1]"-"m[2]"-"m[3]" " m[4]":"m[5]":"m[6]
                    printf $0 "\n"
                }

            }
        }' contact20.txt > cleaned.txt

with input:

3;0952;2001-03-22-11.56.13.514119;2;2014-09-21-10.25.58.918626;J;2015-12-27-14.17.45.593190;N;0;0001-01-01-00.00.00.000000;N;2014-09-21-10.25.58.918626;2012-11-03-21.52.55.270989;N;0001-01-01-00.00.00.000000

I get:

3 0952 2001-03-22 11:56:13 2 2014-09-21-10.25.58.918626 J 2015-12-27-14.17.45.593190 N 0 0001-01-01-00.00.00.000000 N 2014-09-21-10.25.58.918626 2012-11-03-21.52.55.270989 N 0001-01-01-00.00.00.000000

But the result should look like this:

3;0952;2001-03-22 11:56:13;2;2014-09-21 10:25:58;J;2015-12-27 14:17:45;N;0;0001-01-01 00:00:00;N;2014-09-21 10:25:58;2012-11-03 21:52:55;N;0001-01-01 00:00:00

I can't figure out why is removing the ; from the string and also is ignoring date strings like 0001-01-01-00.00.00.000000 and the match is only matching the first one?

What do I need to change to make work property?

Body:
Your current approach will output/repeat the same line for each field in loop.
To get the desired result as a line with transformed "date" values use the following:

awk 'BEGIN{ FS=OFS=";" }
     {  for (i = 1; i <= NF; i++) {
            if(match($i, /([0-9]{4})-([0-9]{2})-([0-9]{2})-([0-9]{2})\.([0-9]{2})\.([0-9]{2})\.([0-9]{6})/, m)){
                $i =  m[1]"-"m[2]"-"m[3]" " m[4]":"m[5]":"m[6]
            }
        }
     }1' contact20.txt > cleaned.txt

cat cleaned.txt
3;0952;2001-03-22 11:56:13;2;2014-09-21 10:25:58;J;2015-12-27 14:17:45;N;0;0001-01-01 00:00:00;N;2014-09-21 10:25:58;2012-11-03 21:52:55;N;0001-01-01 00:00:00


问:
get serializearray() elements with ajax and node js
I would like to get input elements from my form to node js:

Client Side

```<code>var ss =( $('#addform').serializeArray() );
var url= 'http://localhost:8181/add';
    $.ajax({
        url:url,
        type: 'POST',
        dataType: "json",
        data:{ss:ss},
        success: function(json){
            alert("done");
    },
    error: function(jqXHR, textStatus, err) {
        alert('text status '+textStatus+', err '+err)
    }
});
</code>```

[Object, Object, Object, Object, Object, Object, Object]

Server Side:

```<code>router.route('/adduser')
.post(function(req, res) {
  res.header("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      console.log(req.body);
      console.log(req.body.name);
}
</code>```

Result:

```<code>{ ss:
   [ { name: 'name', value: 'a' },
     { name: 'lastname', value: 'a' },
     { name: 'email', value: 'a' },
     { name: 'password', value: 'a' },
     { name: 'password2', value: 'a' },
     { name: 'country', value: 'a' },
     { name: 'phone', value: 'a' } ] }
</code>```

console.log(req.body.name); returns undefined

How can I get elements of these objects in server side ?

答:
```<code>req.body.name
</code>```

This is not surprising.

Look at req.body (you're already logging it and you quoted it in the question!).

The only property the object has is ss, the value of which is an array. It doesn't have a name property.

Don't do this:

```<code>var ss =( $('#addform').serializeArray() );
</code>```

It doesn't give you the data in the format you want.

Use serialize instead.

```<code>var ss = $('#addform').serialize();
</code>```

That will give you a URL encoded string. So pass that directly to data instead of passing an object:

```<code>data: ss,
</code>```

Body:
I would like to get input elements from my form to node js:

Client Side

var ss =( $('#addform').serializeArray() );
var url= 'http://localhost:8181/add';
    $.ajax({
        url:url,
        type: 'POST',
        dataType: "json",
        data:{ss:ss},
        success: function(json){
            alert("done");
    },
    error: function(jqXHR, textStatus, err) {
        alert('text status '+textStatus+', err '+err)
    }
});

[Object, Object, Object, Object, Object, Object, Object]

Server Side:

router.route('/adduser')
.post(function(req, res) {
  res.header("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      console.log(req.body);
      console.log(req.body.name);
}

Result:

{ ss:
   [ { name: 'name', value: 'a' },
     { name: 'lastname', value: 'a' },
     { name: 'email', value: 'a' },
     { name: 'password', value: 'a' },
     { name: 'password2', value: 'a' },
     { name: 'country', value: 'a' },
     { name: 'phone', value: 'a' } ] }

console.log(req.body.name); returns undefined

How can I get elements of these objects in server side ?

Body:
req.body.name

This is not surprising.

Look at req.body (you're already logging it and you quoted it in the question!).

The only property the object has is ss, the value of which is an array. It doesn't have a name property.

Don't do this:

var ss =( $('#addform').serializeArray() );

It doesn't give you the data in the format you want.

Use serialize instead.

var ss = $('#addform').serialize();

That will give you a URL encoded string. So pass that directly to data instead of passing an object:

data: ss,


问:
Why does my box2d.js/canvas script run faster with firebug open?
Seems truly bizarre, and I can't seem to find any cause.

I'm running a little simulation with box2d.js, just a few boxes with joints to make a 'rope'.

Using firefox (version 3.6.13) it runs quite sluggishly, until I open up firebug(version 1.6.0), and then there is a vast speed increace (at a guess I'd say at least 2x).

If I completely disable the firebug addon and restart the browser it remains slow.

What could be causing this, and how can I get it to run that fast normally?

EDIT

As proof, here is a zip file: https://docs.google.com/leaf?id=0B5twGxOv6WCsOTU5NzVjZTEtNGY0ZS00ZjFiLTkwNDUtYTE3YjlmNmU2Zjhh&sort=name&layout=list&num=50

Got a friend with an older version of firebug and he couldn't reproduce.

EDIT 2

If I change my implementation to using raphael instead of canvas it no longer occurs, so I think this must be to do with canvas.

答: That is bizarre! Do you have any console.log calls in your code? Without Firebug those will fail, perhaps causing the slow-down.


问:
ListView Not Updating After Filtering
I have a ListView (with setTextFilterEnabled(true)) and a custom adapter (extends ArrayAdapter) which I update from the main UI thread whenever a new item is added/inserted. Everything works fine at first--new items show up in the list immediately. However this stops the moment I try to filter the list.

Filtering works, but I do it once and all of my succeeding attempts to modify the contents of the list (add, remove) don't display anymore. I used the Log to see if the adapter's list data gets updated properly, and it does, but it's no longer in sync with the ListView shown.

Any ideas what's causing this and how best to address the issue?

答:
First of all I would like to mention, that @jhie's answer is very good. However those facts did not really solve my problem. But with the help of knowledge of how the internally used mechanism worked, I could write it my own filtering function:

```<code>public ArrayList<String> listArray = new ArrayList<>();
public ArrayList<String> tempListArray = new ArrayList<>();
public ArrayAdapter<String> tempAdapter;
public String currentFilter;
</code>```

in onCreate:

```<code>// Fill my ORIGINAL listArray;
listArray.add("Cookies are delicious.");

// After adding everything to listArray, I add everything to tempListArray
for (String element : listArray){
    tempListArray.add(element);
}

// Setting up the Adapter...
tempAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, tempListArray);
myListView.setAdapter(tempAdapter);
</code>```

Filtering:

```<code>// Defining filter functions
public void customFilterList(String filter){
        tempListArray.clear();
        for (String item : listArray){
            if (item.toLowerCase().contains(filter.toLowerCase())){
                tempListArray.add(item);
            }
        }
        currentFilter = filter;
        tempAdapter.notifyDataSetChanged();
    }
    public void updateList(){
        customFilterList(currentFilter);
    }
</code>```

I used it for implementing a search function into my list.

The big advantage: You  have much more filtering power: at customFilterList() you can easily implement the usage of Regular Expressions or use it as a case
sensitive filter.

Instead of notifyDataSetChanged you would call updateList() .

Instead of myListView.getFilter().filter('filter text') you would call customFilterList('filter text')

At the moment this is only working with one ListView. Maybe - with a bit of work - you could implement this as a Custom Array Adapter.

Title: ListView Not Updating After Filtering

Body:
First of all I would like to mention, that @jhie's answer is very good. However those facts did not really solve my problem. But with the help of knowledge of how the internally used mechanism worked, I could write it my own filtering function:

public ArrayList<String> listArray = new ArrayList<>();
public ArrayList<String> tempListArray = new ArrayList<>();
public ArrayAdapter<String> tempAdapter;
public String currentFilter;

in onCreate:

// Fill my ORIGINAL listArray;
listArray.add("Cookies are delicious.");

// After adding everything to listArray, I add everything to tempListArray
for (String element : listArray){
    tempListArray.add(element);
}

// Setting up the Adapter...
tempAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, tempListArray);
myListView.setAdapter(tempAdapter);

Filtering:

// Defining filter functions
public void customFilterList(String filter){
        tempListArray.clear();
        for (String item : listArray){
            if (item.toLowerCase().contains(filter.toLowerCase())){
                tempListArray.add(item);
            }
        }
        currentFilter = filter;
        tempAdapter.notifyDataSetChanged();
    }
    public void updateList(){
        customFilterList(currentFilter);
    }

I used it for implementing a search function into my list.

The big advantage: You  have much more filtering power: at customFilterList() you can easily implement the usage of Regular Expressions or use it as a case
sensitive filter.

Instead of notifyDataSetChanged you would call updateList() .

Instead of myListView.getFilter().filter('filter text') you would call customFilterList('filter text')

At the moment this is only working with one ListView. Maybe - with a bit of work - you could implement this as a Custom Array Adapter.


问:
How to embed a facebook page in an iframe?
For my application I need to embed Facebook page in an iframe, here is the html code:

```<code><html>
<head></head>
<body>
<iframe src="http://www.facebook.com" style="width:100%;height:100%">
</body>
</html>
</code>```

But it does not work, any idea why and how to circumvent ?

答:
Now it is working. Example code below:

faceframe.html

ff1.html

<meta http-equiv="refresh" content="0; url=https://facebook.com/" />

Open faceframe.html...

Now this done. try it it's working...

Body:
For my application I need to embed Facebook page in an iframe, here is the html code:

But it does not work, any idea why and how to circumvent ?

Body:
Now it is working. Example code below:

faceframe.html

<iframe src="file:///C:/Users/Zishan Ahamed/Desktop/ff1.html" width="100%" height="350px" border="0" scrolling="auto" /></iframe>

ff1.html

<meta http-equiv="refresh" content="0; url=https://facebook.com/" />

Open faceframe.html...

Now this done. try it it's working...


问:
POST connect ECONNREFUSED on Bot Framework Channel Emulator
I am encountering a weird errror on Bot Framework. It always says:

```<code>POST connect ECONNREFUSED 127.0.0.1:3978
</code>```

This is the details on the Bot Framework Channel Operator:

```<code>{
"type": "conversationUpdate",
"membersAdded": [
{
  "id": "default-bot",
  "name": "Bot"
}
],
"id": "1dhnjafnclhfeml51c",
"channelId": "emulator",
"timestamp": "2017-04-22T03:56:06.215Z",
"localTimestamp": "2017-04-22T11:56:06+08:00",
"recipient": {
"id": "default-bot",
"name": "Bot"
},
"conversation": {
"id": "a1376jghbggg6a5hjc"
},
"from": {
"id": "default-user",
"name": "User"
},
"serviceUrl": "http://localhost:51293"
}
</code>```

I am using Visual Studio 2017 using Bot Application Template and connecting the API through Bot Framework Channel Emulator. I've tried refreshing the Emulator to start a new message, tried restarting the website project, rebuild it, but its still the same. I didn't change the code on Bot Application template. The localhost URL is correct. I am not sure why I am encountering the error or did I missed something.

答: Use http:// not https://, if you run on localhost and check the right port. It is 3979 in my version, while the emulator uses 3978 on default.

Body:
I am encountering a weird errror on Bot Framework. It always says:

POST connect ECONNREFUSED 127.0.0.1:3978

This is the details on the Bot Framework Channel Operator:

{
"type": "conversationUpdate",
"membersAdded": [
{
  "id": "default-bot",
  "name": "Bot"
}
],
"id": "1dhnjafnclhfeml51c",
"channelId": "emulator",
"timestamp": "2017-04-22T03:56:06.215Z",
"localTimestamp": "2017-04-22T11:56:06+08:00",
"recipient": {
"id": "default-bot",
"name": "Bot"
},
"conversation": {
"id": "a1376jghbggg6a5hjc"
},
"from": {
"id": "default-user",
"name": "User"
},
"serviceUrl": "http://localhost:51293"
}

I am using Visual Studio 2017 using Bot Application Template and connecting the API through Bot Framework Channel Emulator. I've tried refreshing the Emulator to start a new message, tried restarting the website project, rebuild it, but its still the same. I didn't change the code on Bot Application template. The localhost URL is correct. I am not sure why I am encountering the error or did I missed something.


问:
How to shorten thread name in logback logs?
You can shorten the name of the logger using %logger{x} syntax where x controls shortening procedure. Is there any way to shorten the name of the thread the same way?</p>

答:
What about this at your thread's beginings?

```<code>if (Thread.currentThread().getName().split("-").length > 1) {
    String threadName = Thread.currentThread().getName();
    threadName = "thread" + threadName.split("-")[3];
    Thread.currentThread().setName(threadName);
}
</code>```

Then in your logback.xml:

```<code>[%-8thread] %msg%n
</code>```

... and you'll get something like this:

```<code>[main    ] Process started
[thread1 ] Thread started
[thread2 ] Thread started
[thread1 ] Thread ended
[thread1 ] Thread started
[thread2 ] Thread ended
[thread2 ] Thread started
[thread1 ] Thread ended
[thread2 ] Thread ended
[thread3 ] Thread ended
[thread4 ] Thread ended
[thread5 ] Thread ended
[main    ] Process ended
</code>```

Body:
What about this at your thread's beginings?

if (Thread.currentThread().getName().split("-").length > 1) {
    String threadName = Thread.currentThread().getName();
    threadName = "thread" + threadName.split("-")[3];
    Thread.currentThread().setName(threadName);
}

Then in your logback.xml:

[%-8thread] %msg%n

... and you'll get something like this:

[main    ] Process started
[thread1 ] Thread started
[thread2 ] Thread started
[thread1 ] Thread ended
[thread1 ] Thread started
[thread2 ] Thread ended
[thread2 ] Thread started
[thread1 ] Thread ended
[thread2 ] Thread ended
[thread3 ] Thread ended
[thread4 ] Thread ended
[thread5 ] Thread ended
[main    ] Process ended


问:
accessing FormControl in Angular 2
What is the difference between template variable spy and name in following two statements? What does spy represent and what does name represent. The code is from following tutorial on Angular.

https://angular.io/docs/ts/latest/guide/forms.html

```<code><input type="text" class="form-control" id="name"
  required
  [(ngModel)]="model.name" name="name"
  #spy>
<br>TODO: remove this: {{spy.className}}
spy is assigned value of control which represents the input.

<input type="text" class="form-control" id="name"
               required
               [(ngModel)]="model.name" name="name"
               #name="ngModel">
</code>```

I thought that spy represents the FormControl within NgForm to represent the input element. Using spy, I can access properties of the FormControl (eg spyu.className). But I couldn't understand if name is also a FormControl and how assigning it a value of "ngModel" makes it different from spy

答:
What does spy represent

When you specify template reference by itself like this #some-name, it by default references ElementRef in a component/directive class and native DOM element in the template. ElementRef is a wrapper around native DOM element and you can read more about it here. className is a standard DOM API that is a string of all classes attached to the element.

If it's used by itself on the child component, it by default references component instance.

what does name represent

When you specify template reference in the form #some-name="other-name", it references a directive by the name other-name. So in your case:

```<code>#name="ngModel"
</code>```

it references NgModel directive instance on this input control.

I thought that spy represents the FormControl within NgForm to
  represent the input element.

No, as I explained earlier, it represents ElementRef. To get access to the form control through template reference, you would have to use FormControlDirective and use template reference like this:

```<code><input #spy="ngForm" [formControl]="control">
</code>```

As this directive is defined like this:

```<code>@Directive({selector: '[formControl]', providers: [formControlBinding], exportAs: 'ngForm'})

                                      ---------------------------------------- ^^^^^^^^^

export class FormControlDirective extends NgControl implements OnChanges {
</code>```

But that wouldn't make much sense as you would already have access to the form control in your component control value.

Title: accessing FormControl in Angular 2

Body:
What is the difference between template variable spy and name in following two statements? What does spy represent and what does name represent. The code is from following tutorial on Angular.

https://angular.io/docs/ts/latest/guide/forms.html

<input type="text" class="form-control" id="name"
  required
  [(ngModel)]="model.name" name="name"
  #spy>

TODO: remove this: {{spy.className}}
spy is assigned value of control which represents the input.

<input type="text" class="form-control" id="name"
               required
               [(ngModel)]="model.name" name="name"
               #name="ngModel">

I thought that spy represents the FormControl within NgForm to represent the input element. Using spy, I can access properties of the FormControl (eg spyu.className). But I couldn't understand if name is also a FormControl and how assigning it a value of "ngModel" makes it different from spy

Body:
What does spy represent

When you specify template reference by itself like this #some-name, it by default references ElementRef in a component/directive class and native DOM element in the template. ElementRef is a wrapper around native DOM element and you can read more about it here. className is a standard DOM API that is a string of all classes attached to the element.

If it's used by itself on the child component, it by default references component instance.

what does name represent

When you specify template reference in the form #some-name="other-name", it references a directive by the name other-name. So in your case:

#name="ngModel"

it references NgModel directive instance on this input control.

I thought that spy represents the FormControl within NgForm to
  represent the input element.

No, as I explained earlier, it represents ElementRef. To get access to the form control through template reference, you would have to use FormControlDirective and use template reference like this:

<input #spy="ngForm" [formControl]="control">

As this directive is defined like this:

@Directive({selector: '[formControl]', providers: [formControlBinding], exportAs: 'ngForm'})

                                      ---------------------------------------- ^^^^^^^^^

export class FormControlDirective extends NgControl implements OnChanges {

But that wouldn't make much sense as you would already have access to the form control in your component control value.


问:
How to store time in protobuf 3
I have this struct in golang

```<code>struct File {
  name string
  creatation_time time.Time
}
</code>```

How do I write it in protobuf3 ?

答:
Create example.proto;

```<code>syntax = "proto3";

import google_protobuf "github.com/golang/protobuf/ptypes/timestamp"

message File {
    string name = 1;
    google.protobuf.Timestamp creatation_time = 2;
}
</code>```

After compilation check the example.pb.go for the structure definition that has been created.

Title: How to store time in protobuf 3

Body:
I have this struct in golang

struct File {
  name string
  creatation_time time.Time
}

How do I write it in protobuf3 ?

Body:
Create example.proto;

syntax = "proto3";

import google_protobuf "github.com/golang/protobuf/ptypes/timestamp"

message File {
    string name = 1;
    google.protobuf.Timestamp creatation_time = 2;
}

After compilation check the example.pb.go for the structure definition that has been created.


问:
Email validation, using if else statements wont allow it to continue checking if there was an error with the first if?
I have:

```<code>if(isset($_POST['submit'])) {
    if (empty($name)) {
        echo'<span class="error">ERROR: Missing Name </span><br/>';
    } else if(empty($phone) || empty($email)) {
        echo'<span class="error">ERROR: You must insert a phone number or email</span><br/>';
    } else if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        echo'<span class="error">ERROR: Please Insert a valid Email</span><br/>';
    }  else {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
            "Name: $name
            Email: $email
            Phone Number: $phone
            Comment: $comment", "From: $email" );
        echo'<span id="valid">Message has been sent</span><br/>';
    }
}
</code>```

How else could I check for all of those issues without using else if?
When I use else if, it checks through the first if statement, if there is an issue with it it will not continue going through the other if statements following that one.

Any ideas? Thank you

答:
You could collect all errors in an array like this:

```<code>if (isset($_POST['submit'])) {
    $errors = array();
    if (empty($name)) {
        $errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
    }
    if (empty($phone) || empty($email)) {
        $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
    }
    if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        $errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
    }
    if ($errors) {
        echo 'There were some errors: ';
        echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
    } else {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
            "Name: $name\n".
            "Email: $email\n".
            "Phone Number: $phone\n".
            "Comment: $comment", "From: $email");
        echo'<span id="valid">Message has been sent</span><br/>';
    }
}
</code>```

With this you can check all requirements and report all errors and not just the first one.

Body:
I have:

if(isset($_POST['submit'])) {
    if (empty($name)) {
        echo'ERROR: Missing Name
';
    } else if(empty($phone) || empty($email)) {
        echo'ERROR: You must insert a phone number or email
';
    } else if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        echo'ERROR: Please Insert a valid Email
';
    }  else {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
            "Name: $name
            Email: $email
            Phone Number: $phone
            Comment: $comment", "From: $email" );
        echo'Message has been sent
';
    }
}

How else could I check for all of those issues without using else if?
When I use else if, it checks through the first if statement, if there is an issue with it it will not continue going through the other if statements following that one.

Any ideas? Thank you

Body:
You could collect all errors in an array like this:

if (isset($_POST['submit'])) {
    $errors = array();
    if (empty($name)) {
        $errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
    }
    if (empty($phone) || empty($email)) {
        $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
    }
    if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        $errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
    }
    if ($errors) {
        echo 'There were some errors: ';
        echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
    } else {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
            "Name: $name\n".
            "Email: $email\n".
            "Phone Number: $phone\n".
            "Comment: $comment", "From: $email");
        echo'<span id="valid">Message has been sent</span><br/>';
    }
}

With this you can check all requirements and report all errors and not just the first one.