问:
Android Facebook SDK v4 LikeView issue
I'm trying to implement the Facebook "Like Button" in my Android app. Before I was using the Facebook SDK v3 where you would set up the LikeView and then call likeView.handleOnActivityResult(context, requestCode, resultCode, data) inside of onActivityResult(); This would change the button so that after the page was "liked" it would show "Liked" and the number of people that also like the page.

Now, I'm using the Facebook SDK v4 because v3 is now deprecated. In this version, I do not see any documentation or anyway to have this same type of functionality for the "like" button. It no longer has the likeView.handlePnActivityResult method that v3 had. Now when the user hits the "like" button and likes the page, it doesn't change the state of the button.

Does anyone know how to solve this issue so that it will have the same functionality as the LikeView in the Facebook SDK v3?

Here is the code of what I'm doing:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Initialize FaceBook SDK
    FacebookSdk.sdkInitialize(this);

    setContentView(R.layout.activity_about);

    // Set up ActionBar
    actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);

    terms = (LinearLayout) findViewById(R.id.terms_holder);
    privacyPolicy = (LinearLayout) findViewById(R.id.privacy_policy_holder);
    share = (LinearLayout) findViewById(R.id.social_media_holder);
    environmentButton = (Button) findViewById(R.id.environment_change);
    likeView = (LikeView) findViewById(R.id.like_view);

    likeView.setObjectIdAndType("##############", LikeView.ObjectType.PAGE);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // In the old Facebook SDK this is where it would change the like button to "liked 2,038" but this code is deprecated now apparently
    // likeView.handleOnActivityResult(this, requestCode, resultCode, data);
}
</code>```

And here is my XML:

```<code><LinearLayout
android:id="@+id/social_media_holder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="10dp"
android:gravity="center_vertical"
android:clickable="true"
android:onClick="onClick" >

<com.facebook.share.widget.LikeView
    android:id="@+id/like_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="10dp" />

<TextView
    android:id="@+id/post_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="5dp"
    android:text="@string/post_about_us"
    android:textSize="20dp"
    android:textColor="@color/dark_grey" />
</code>```

答: Native Like Button: The Native Like Button, designed for mobile apps, will no longer be supported starting with Facebook SDK version 4.28 and above. Previous versions of the SDK can still use the Native Like Button, but starting 2/6, the Native Like Button will no longer be supported. After 2/6, the dialogs for Native Like will no longer appear and taps on any native like button will result in no action.</p>

Title: Android Facebook SDK v4 LikeView issue

Body:
I'm trying to implement the Facebook "Like Button" in my Android app. Before I was using the Facebook SDK v3 where you would set up the LikeView and then call likeView.handleOnActivityResult(context, requestCode, resultCode, data) inside of onActivityResult(); This would change the button so that after the page was "liked" it would show "Liked" and the number of people that also like the page.

Now, I'm using the Facebook SDK v4 because v3 is now deprecated. In this version, I do not see any documentation or anyway to have this same type of functionality for the "like" button. It no longer has the likeView.handlePnActivityResult method that v3 had. Now when the user hits the "like" button and likes the page, it doesn't change the state of the button.

Does anyone know how to solve this issue so that it will have the same functionality as the LikeView in the Facebook SDK v3?

Here is the code of what I'm doing:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Initialize FaceBook SDK
    FacebookSdk.sdkInitialize(this);

    setContentView(R.layout.activity_about);

    // Set up ActionBar
    actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);

    terms = (LinearLayout) findViewById(R.id.terms_holder);
    privacyPolicy = (LinearLayout) findViewById(R.id.privacy_policy_holder);
    share = (LinearLayout) findViewById(R.id.social_media_holder);
    environmentButton = (Button) findViewById(R.id.environment_change);
    likeView = (LikeView) findViewById(R.id.like_view);

    likeView.setObjectIdAndType("##############", LikeView.ObjectType.PAGE);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // In the old Facebook SDK this is where it would change the like button to "liked 2,038" but this code is deprecated now apparently
    // likeView.handleOnActivityResult(this, requestCode, resultCode, data);
}

And here is my XML:

<LinearLayout
android:id="@+id/social_media_holder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="10dp"
android:gravity="center_vertical"
android:clickable="true"
android:onClick="onClick" >

<com.facebook.share.widget.LikeView
    android:id="@+id/like_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="10dp" />

<TextView
    android:id="@+id/post_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="5dp"
    android:text="@string/post_about_us"
    android:textSize="20dp"
    android:textColor="@color/dark_grey" />


来源: stackexchange

问:
How to verify web service call is from android application or not
I have an android application with php web services. Web service urls are stored in application itself. I have a registration page in my application that post data to registration url.

My code for registration is :

```<code>           `String link = "http://xxxxxxx.registration.php";
            String data = URLEncoder.encode("name", "UTF-8") + "=" +
                    URLEncoder.encode(name, "UTF-8");
            data += "&" + URLEncoder.encode("phone", "UTF-8") + "=" +
                    URLEncoder.encode(phone, "UTF-8");
            data += "&" + URLEncoder.encode("password", "UTF-8") + "=" +
                    URLEncoder.encode(password, "UTF-8");

            URL url = new URL(link);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();`
</code>```

After i published the apk into playstore, someone reverse engineered the apk file and sending bulk requests with post data to my registration url.

I haven't used Proguard at the time of this attack.

```<code>minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro
</code>```

I tried securing the urls by keeping it on the gradle.properties file and call it by BuildConfig.Registration_Url. by referring this. But somehow they find the url again.

After some search I came to know that there is no method that hide urls 100% from attacker

I would like to know what is the correct method to secure code from an attacker.

How can i Verify the web service request is from application or not(It should redirect to an error page if the call is not from the application)

Can i keep all the web service url in server side?

I am a beginner in programming. Please Help !

答:
Use the user agent from $_SERVER['HTTP_USER_AGENT'],
and for simple detection you can use this SCRIPT:

```<code><?php

//Detect special conditions devices
$iPod    = stripos($_SERVER['HTTP_USER_AGENT'],"iPod");
$iPhone  = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$iPad    = stripos($_SERVER['HTTP_USER_AGENT'],"iPad");
$Android = stripos($_SERVER['HTTP_USER_AGENT'],"Android");
$webOS   = stripos($_SERVER['HTTP_USER_AGENT'],"webOS");

//do something with this information
if( $iPod || $iPhone ){
    //browser reported as an iPhone/iPod touch -- do something here
}else if($iPad){
    //browser reported as an iPad -- do something here
}else if($Android){
    //browser reported as an Android device -- do something here
}else if($webOS){
    //browser reported as a webOS device -- do something here
}

?>
</code>```

If you want to know more details of the user device I recommended to use one of the following solutions: http://51degrees.mobi or http://deviceatlas.com

ContentLicense: CC BY-SA 3.0

Body:
I have an android application with php web services. Web service urls are stored in application itself. I have a registration page in my application that post data to registration url.

My code for registration is :

           `String link = "http://xxxxxxx.registration.php";
            String data = URLEncoder.encode("name", "UTF-8") + "=" +
                    URLEncoder.encode(name, "UTF-8");
            data += "&" + URLEncoder.encode("phone", "UTF-8") + "=" +
                    URLEncoder.encode(phone, "UTF-8");
            data += "&" + URLEncoder.encode("password", "UTF-8") + "=" +
                    URLEncoder.encode(password, "UTF-8");

            URL url = new URL(link);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();`

After i published the apk into playstore, someone reverse engineered the apk file and sending bulk requests with post data to my registration url.

I haven't used Proguard at the time of this attack.

minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro

I tried securing the urls by keeping it on the gradle.properties file and call it by BuildConfig.Registration_Url. by referring this. But somehow they find the url again.

After some search I came to know that there is no method that hide urls 100% from attacker

I would like to know what is the correct method to secure code from an attacker.

How can i Verify the web service request is from application or not(It should redirect to an error page if the call is not from the application)

Can i keep all the web service url in server side?

I am a beginner in programming. Please Help !

Body:
Use the user agent from $_SERVER['HTTP_USER_AGENT'],
and for simple detection you can use this SCRIPT:

<?php

//Detect special conditions devices
$iPod    = stripos($_SERVER['HTTP_USER_AGENT'],"iPod");
$iPhone  = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$iPad    = stripos($_SERVER['HTTP_USER_AGENT'],"iPad");
$Android = stripos($_SERVER['HTTP_USER_AGENT'],"Android");
$webOS   = stripos($_SERVER['HTTP_USER_AGENT'],"webOS");

//do something with this information
if( $iPod || $iPhone ){
    //browser reported as an iPhone/iPod touch -- do something here
}else if($iPad){
    //browser reported as an iPad -- do something here
}else if($Android){
    //browser reported as an Android device -- do something here
}else if($webOS){
    //browser reported as a webOS device -- do something here
}

?>

If you want to know more details of the user device I recommended to use one of the following solutions: http://51degrees.mobi or http://deviceatlas.com


问:
Linux kernel memory management?
Will Linux Kernel free kmalloc'ed and not kfree'd in kernel module memory after module release just like it's work with user space apps?</p>

答: The kernel will not do any garbage collection for a module.  If the module kmallocs a chunk of memory and doesn't kfree it before the module is unloaded, that chunk will stay allocated and inaccessible until the next reboot.

ContentLicense: CC BY-SA 4.0

Title: Linux kernel memory management?

ContentLicense: CC BY-SA 2.5


问:
how to send mail on specified date and time using mysql and php
what I have is,

user specified date and time in the database.

a php script to send mail.

Required

trigger php script when specified date and time arrives.

I am using local apache server

Example: A wants to send mail to B in 5 days from now. A enters date and time in database and after 5 days it will automatically sent by running php mailer script.

Is there any way of scheduling this?

答:
you can use script for check diff date now by date in database for interval 1 min or 1 second or ever time run script check .for example by php :

```<code>public static function diff_time($date, $timezone = null,$now=null)
    {
        if($now == null)
        {
            $now =  date_create(date('Y-m-d H:i:s'));
            $now = new \DateTime(date('Y-m-d H:i:s'));
            $time_now = time();
        }
        if(is_int($date)){
            $time = $date;
            $date = date('Y-m-d H:i:s',$date);
        }
        else{
            $time = strtotime($date);
        }
        $date=new \DateTime($date);
        $diff=$date->diff($now);
        return $diff`;}
</code>```

you can use check diff time if near or zero time  send mail.
now you can add

```<code>crontab -e
</code>```

add

```<code>` * * * * * php ~/script.php`
</code>```

by in example run every time check and send mail

Body:
you can use script for check diff date now by date in database for interval 1 min or 1 second or ever time run script check .for example by php :

public static function diff_time($date, $timezone = null,$now=null)
    {
        if($now == null)
        {
            $now =  date_create(date('Y-m-d H:i:s'));
            $now = new \DateTime(date('Y-m-d H:i:s'));
            $time_now = time();
        }
        if(is_int($date)){
            $time = $date;
            $date = date('Y-m-d H:i:s',$date);
        }
        else{
            $time = strtotime($date);
        }
        $date=new \DateTime($date);
        $diff=$date->diff($now);
        return $diff`;}

you can use check diff time if near or zero time  send mail.
now you can add

crontab -e

add

` * * * * * php ~/script.php`

by in example run every time check and send mail


问:
How to change dynamically the path for saving a bunch of csv files
Every week, I use different path for saving a bunch of csv files by date of a week. E.g. We are running week N46 (Calendar company) and I will create one csv file for Monday, another for Tuesday and so on. I will save them using a path c:\weekN46\csvFiles AND, next week I will do similar operation but will be c:\weekN47\csvFiles and so. I wish to use VBA Excel code for saving all csv files in the regarding folder week.

答:
These two functions will help you to create a folder with current week it it does not exists, You can also use them to get the current week folder name.

Below function to return the current week folder name , You can also  use to get the folder name to save the file

```<code>Function SaveAddreess() As String

    Dim WeekNumber As String
    Dim WeekFolder  As String

    WeekNumber = CStr(Format(Now, "ww"))
    WeekFolder = "WeekN" & WeekNumber
    SaveAddreess = "c:\" & WeekFolder & Application.PathSeparator

End Function
</code>```

So if you want to save abc.csv to this week then you can generate the current week folder name and save it to that path.

Below Code is to check if this week folder exists or not if it does it will do nothing,if it does not, it will create one.

```<code>Function CreateThisWeekFolder()

    Dim fs As Object
    Dim fol As Object
    Dim thisweekFolder As String

    Set fs = CreateObject("Scripting.FileSystemObject")
    thisweekFolder = SaveAddreess

    If fs.FolderExists(thisweekFolder) Then
            'DO NOTHING
    Else
            fs.CreateFolder (thisweekFolder)
    End If

End Function
</code>```

Body:
These two functions will help you to create a folder with current week it it does not exists, You can also use them to get the current week folder name.

Below function to return the current week folder name , You can also  use to get the folder name to save the file

Function SaveAddreess() As String

    Dim WeekNumber As String
    Dim WeekFolder  As String

    WeekNumber = CStr(Format(Now, "ww"))
    WeekFolder = "WeekN" & WeekNumber
    SaveAddreess = "c:\" & WeekFolder & Application.PathSeparator

End Function

So if you want to save abc.csv to this week then you can generate the current week folder name and save it to that path.

Below Code is to check if this week folder exists or not if it does it will do nothing,if it does not, it will create one.

Function CreateThisWeekFolder()

    Dim fs As Object
    Dim fol As Object
    Dim thisweekFolder As String

    Set fs = CreateObject("Scripting.FileSystemObject")
    thisweekFolder = SaveAddreess

    If fs.FolderExists(thisweekFolder) Then
            'DO NOTHING
    Else
            fs.CreateFolder (thisweekFolder)
    End If

End Function


问:
How to query many to many relation tables in laravel?
i am trying to query many to many relation for my get api call. i have three table as shown here but i am not using pivot table.

This is my Projects model class and this the function

```<code>  public function projectRewd()
   {

     return $this
               ->belongsToMany('App\Rewards','rewards','project_id','reward_id');

   }
</code>```

And this is my Rewards model class and function

```<code>public function projectShip()
    {
        return $this->belongsToMany('App\Shipping_location','shipping_location','projects_id','rewards_id');

    }
</code>```

This is my api controller function

```<code>Route::get('projects/{id}', function($id) {
    $proj = Projects::whereHas('projectRewd', function($q)
    {
        $q->where('id', $id);
    });
    return $proj;

 });
</code>```

i am using this link for api call

```<code>http://localhost:8000/api/projects/1
</code>```

i want to extract rewards data and shipping_location data associate with project_id.

i am getting this error

```<code>"message": "Object of class Illuminate\\Database\\Eloquent\\Builder could not be converted to string"
</code>```

i check and tried all related error from different post.

i also search and tried many technique. Cant solve my problem.
Please suggest me how to do this??
can i do this type of query in larvel without using pivot table??

答:
Your closure-based controller returns your query-builder object. Not a project. You need to retrieve results from the query by fetching e.g. the first result (->first()) or all (->get()).

```<code>Route::get('projects/{id}', function($id) {
    $proj = Projects::whereHas('projectRewd', function($q)
    {
        $q->where('id', $id);
    })->first();
    return $proj;

 });
</code>```

Referencing $id:

The reason why $id is unknown, is that the closure doesn't know about it.
You can pass it to the closure using use(...).

```<code>Route::get('projects/{id}', function($id) {
    $proj = Projects::whereHas('projectRewd', function($q) use ($id)
    {
        ...
</code>```

Further:

Your whereHas query looks incorrect to me:

```<code>$q->where('id', $id);
</code>```

Apparently $id is the project id. But the 'id' column in projectRewd is the primary key of projectRewd (unless you have modified the defaults).

I assume you want to query all projects that have at least one projectRewd:

```<code>Route::get('projects/{id}', function($id) {
        $proj = Projects::has('projectRewd')->first();
        return $proj;

     });
</code>```

And if you want to eager load the joined tables:

```<code>Route::get('projects/{id}', function($id) {
        $proj = Projects::with('projectRewd. projectShips')->has('projectRewd')->first();
        return $proj;
    });
</code>```

Body:
i am trying to query many to many relation for my get api call. i have three table as shown here but i am not using pivot table.

This is my Projects model class and this the function

  public function projectRewd()
   {

     return $this
               ->belongsToMany('App\Rewards','rewards','project_id','reward_id');

   }

And this is my Rewards model class and function

public function projectShip()
    {
        return $this->belongsToMany('App\Shipping_location','shipping_location','projects_id','rewards_id');

    }

This is my api controller function

Route::get('projects/{id}', function($id) {
    $proj = Projects::whereHas('projectRewd', function($q)
    {
        $q->where('id', $id);
    });
    return $proj;

 });

i am using this link for api call

http://localhost:8000/api/projects/1

i want to extract rewards data and shipping_location data associate with project_id.

i am getting this error

"message": "Object of class Illuminate\\Database\\Eloquent\\Builder could not be converted to string"

i check and tried all related error from different post.

i also search and tried many technique. Cant solve my problem.
Please suggest me how to do this??
can i do this type of query in larvel without using pivot table??

Body:
Your closure-based controller returns your query-builder object. Not a project. You need to retrieve results from the query by fetching e.g. the first result (->first()) or all (->get()).

Route::get('projects/{id}', function($id) {
    $proj = Projects::whereHas('projectRewd', function($q)
    {
        $q->where('id', $id);
    })->first();
    return $proj;

 });

Referencing $id:

The reason why $id is unknown, is that the closure doesn't know about it.
You can pass it to the closure using use(...).

Route::get('projects/{id}', function($id) {
    $proj = Projects::whereHas('projectRewd', function($q) use ($id)
    {
        ...

Further:

Your whereHas query looks incorrect to me:

$q->where('id', $id);

Apparently $id is the project id. But the 'id' column in projectRewd is the primary key of projectRewd (unless you have modified the defaults).

I assume you want to query all projects that have at least one projectRewd:

Route::get('projects/{id}', function($id) {
        $proj = Projects::has('projectRewd')->first();
        return $proj;

     });

And if you want to eager load the joined tables:

Route::get('projects/{id}', function($id) {
        $proj = Projects::with('projectRewd. projectShips')->has('projectRewd')->first();
        return $proj;
    });


答:
With windows function, Spark will calcualte frames from unix epoch time 1970-01-01 00:00:00 UTC.
Because you set your the silde duration is 9 minutes, so the first frame contains value from your Time column is [2017-10-11 08:45:00.0,2017-10-11 09:05:00.0].

For clarity

```<code>$ date --date="2017-10-11 08:45:00" +"%s
1507686300
$ echo $[1507686300%180]
0
</code>```

Title: How to understand the result of the spark sql window function

Body:
I have the following code to try the spark sql window function:

test("spark sql time window 2") {
    val spark = SparkSession.builder().master("local").appName("SparkSQLWindowTest").getOrCreate()
    import spark.implicits._
    import org.apache.spark.sql.functions._
    val ds = Seq(
      SaleRecord("2017-10-11 09:01:12", 1),
      SaleRecord("2017-10-11 09:01:18", 6),
      SaleRecord("2017-10-11 10:11:12", 2),
      SaleRecord("2017-10-11 10:18:13", 5),
      SaleRecord("2017-10-11 10:22:13", 3),
      SaleRecord("2017-10-11 10:22:22", 6),
      SaleRecord("2017-10-11 10:34:56", 2),
      SaleRecord("2017-10-11 10:48:22", 6),
      SaleRecord("2017-10-11 11:52:23", 4),
      SaleRecord("2017-10-11 12:56:24", 2)).toDS

    val ds2 = ds.groupBy(window($"Time", "20 minutes", "9 minutes")).agg(sum("revenue")).orderBy("window.start")
    ds2.show(truncate = false)

    /*
+---------------------------------------------+------------+
|window                                       |sum(revenue)|
+---------------------------------------------+------------+
|[2017-10-11 08:45:00.0,2017-10-11 09:05:00.0]|7.0         |
|[2017-10-11 08:54:00.0,2017-10-11 09:14:00.0]|7.0         |
|[2017-10-11 09:57:00.0,2017-10-11 10:17:00.0]|2.0         |
|[2017-10-11 10:06:00.0,2017-10-11 10:26:00.0]|16.0        |
|[2017-10-11 10:15:00.0,2017-10-11 10:35:00.0]|16.0        |
|[2017-10-11 10:24:00.0,2017-10-11 10:44:00.0]|2.0         |
|[2017-10-11 10:33:00.0,2017-10-11 10:53:00.0]|8.0         |
|[2017-10-11 10:42:00.0,2017-10-11 11:02:00.0]|6.0         |
|[2017-10-11 11:36:00.0,2017-10-11 11:56:00.0]|4.0         |
|[2017-10-11 11:45:00.0,2017-10-11 12:05:00.0]|4.0         |
|[2017-10-11 12:39:00.0,2017-10-11 12:59:00.0]|2.0         |
|[2017-10-11 12:48:00.0,2017-10-11 13:08:00.0]|2.0         |
+---------------------------------------------+------------+

     */
  }

The definition of the SaleRecord is a simple case class:

case class SaleRecord(time: String, revenue: Double)

I could not understand how the first three rows is generated in the result?

Why the first window is
[2017-10-11 08:45:00.0,2017-10-11 09:05:00.0]

Body:
With windows function, Spark will calcualte frames from unix epoch time 1970-01-01 00:00:00 UTC.
Because you set your the silde duration is 9 minutes, so the first frame contains value from your Time column is [2017-10-11 08:45:00.0,2017-10-11 09:05:00.0].

For clarity

$ date --date="2017-10-11 08:45:00" +"%s
1507686300
$ echo $[1507686300%180]
0


问:
Django ReportLab PDF generation with SimpleDocTemplate
I am using SimpleDocTemplate to genetare and download pdf. My current code generating the PDF corectly but the pdf getting open in another tab of chrome browser with empty page and Its asking for 'Open' or 'Save' in FireFox browser. Where shoud i change my code to directly download the PDF without opening it in another Tab of Chrome. Thanks in advance.
This is the code..

```<code> def GenerateTc(request):

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename = "TC.pdf"'

    doc = SimpleDocTemplate(response,topMargin=20)
    doc.pagesize = landscape(A4)

    elements = []

    data= [

                 ['---OFFICE USE ONLY---'],
                 ['Date :','','ClassTeacher Signature: :',''],
                 ['Principal Signature :','','Accountant Signature :',''],
                 ['Student Name :'+' '+''],
                 ['Remark :','','',''],
          ]
    style =TableStyle([

                            ('SPAN',(2,15),(3,15)),
                            ('SPAN',(0,16),(1,16)),
                            ('SPAN',(2,16),(3,16)),
                            ('SPAN',(0,17),(3,17)),
                            ('SPAN',(0,18),(3,18)),
                    ])
    #Configure style and word wrap
    s = getSampleStyleSheet()
    s = s["BodyText"]
    s.wordWrap = 'CJK'
    ps = ParagraphStyle('title', fontSize=15, alignment=TA_CENTER,)
    data2 = [[Paragraph(cell, s) for cell in row] for row in data]
    t=Table(data2)
    t.setStyle(style)
    getSampleStyleSheet()
    elements.append(Paragraph("TRANSFER/DISCONTINUATION ACKNOWLEDGEMENT",ps))
    elements.append(Spacer(1,0.4*inch))
    elements.append(t)
    doc.build(elements)

    return response
</code>```

This is my URL:

```<code>url(r'^generate_tc/$',views.GenerateTc, name='generate_tc'),
</code>```

This is my HTML template form to call that function in view:

```<code><form action="{% url 'transfer_certificate:generate_tc' %}" id="form_sample_1" class="form-horizontal"
                  method="POST" enctype="multipart/form-data">
                {% csrf_token %}
                <input class="form-control" id="studentid" name="studentid" type="hidden" value="">
                <table class="table table-striped table-bordered table-hover table-checkable order-column"
                       id="sample_1">
                    <thead>
                    <tr>
                        <th style="display:none">student ID</th>
                        <th>Id</th>
                        <th>Name</th>
                        <th>Class</th>
                        <th>Section</th>

                        <th>Grant/Generate TC</th>
                    </tr>
                    </thead>
                    <tbody> {% for tc_detail in TCDetailsList %}
                        <tr style="cursor: pointer;">

                            <td style="display:none">{{ tc_detail.student.id }}</td>
                            <td>{{ forloop.counter }}</td>
                            <td>{{ tc_detail.student.first_name }}  {{ tc_detail.student.father_name }}
                                  {{ tc_detail.student.last_name }}</td>
                            <td>{{ tc_detail.student.academic_class_section.class_name }}</td>
                            <td>{{ tc_detail.student.academic_class_section.section_name }}</td>
                            <td><input type='submit' class="buttongenerate btn green btn-block" value='Generate TC'></td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </form>
</code>```

Thanks You.

答:
in your template you should have a link to the view like this

```<code> <a href="url">download</a>
</code>```

but you need to set the link as a download link like this

```<code><a href="url" download >download</a>
</code>```

Body:
I am using SimpleDocTemplate to genetare and download pdf. My current code generating the PDF corectly but the pdf getting open in another tab of chrome browser with empty page and Its asking for 'Open' or 'Save' in FireFox browser. Where shoud i change my code to directly download the PDF without opening it in another Tab of Chrome. Thanks in advance.
This is the code..

 def GenerateTc(request):

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename = "TC.pdf"'

    doc = SimpleDocTemplate(response,topMargin=20)
    doc.pagesize = landscape(A4)

    elements = []

    data= [

                 ['---OFFICE USE ONLY---'],
                 ['Date :','','ClassTeacher Signature: :',''],
                 ['Principal Signature :','','Accountant Signature :',''],
                 ['Student Name :'+' '+''],
                 ['Remark :','','',''],
          ]
    style =TableStyle([

                            ('SPAN',(2,15),(3,15)),
                            ('SPAN',(0,16),(1,16)),
                            ('SPAN',(2,16),(3,16)),
                            ('SPAN',(0,17),(3,17)),
                            ('SPAN',(0,18),(3,18)),
                    ])
    #Configure style and word wrap
    s = getSampleStyleSheet()
    s = s["BodyText"]
    s.wordWrap = 'CJK'
    ps = ParagraphStyle('title', fontSize=15, alignment=TA_CENTER,)
    data2 = [[Paragraph(cell, s) for cell in row] for row in data]
    t=Table(data2)
    t.setStyle(style)
    getSampleStyleSheet()
    elements.append(Paragraph("TRANSFER/DISCONTINUATION ACKNOWLEDGEMENT",ps))
    elements.append(Spacer(1,0.4*inch))
    elements.append(t)
    doc.build(elements)

    return response

This is my URL:

url(r'^generate_tc/$',views.GenerateTc, name='generate_tc'),

This is my HTML template form to call that function in view:

<form action="{% url 'transfer_certificate:generate_tc' %}" id="form_sample_1" class="form-horizontal"
                  method="POST" enctype="multipart/form-data">
                {% csrf_token %}
                <input class="form-control" id="studentid" name="studentid" type="hidden" value="">

                        student ID
                        Id
                        Name
                        Class
                        Section

                        Grant/Generate TC

 {% for tc_detail in TCDetailsList %}

                            {{ tc_detail.student.id }}
                            {{ forloop.counter }}
                            {{ tc_detail.student.first_name }}  {{ tc_detail.student.father_name }}
                                  {{ tc_detail.student.last_name }}
                            {{ tc_detail.student.academic_class_section.class_name }}
                            {{ tc_detail.student.academic_class_section.section_name }}
                            <input type='submit' class="buttongenerate btn green btn-block" value='Generate TC'>

                    {% endfor %}

            </form>

Thanks You.

Body:
in your template you should have a link to the view like this

 <a href="url">download</a>

but you need to set the link as a download link like this

<a href="url" download >download</a>


问:
Reference known property in (List<someClass>)someObject
have tried some searches. Probably my lack of knowledge that I'm not using the right search terms or perhaps just not understanding the answers.

I have a method that is being passed an object, which I want to output a particular value to a text file.
I already know the object will be a List< someClass > of a few different possible classes (customers/employees/items etc). But all of the classes contain the same string property (e.g.) string idNumber.

So something like this:

```<code>public static void OutputFile(object myInput)
{
  foreach (someGenericObject in (List<anyType>)myInput)
  {
    string textToOutput = someGenericObject.idNUmber;
    //output the text to somewhere else here
  }
}
</code>```

I feel like as long as I know that it will always contain a this "idNumber" property regardless of the type, that I should be able to reference it somehow. But I just can't seem to get my head around it?

The error I typically get is something like:

Cannot cast List< Employee > to List< object > etc.

Thanks in advance

答:
As I suggested in the comments, if you have the ability to modify these classes, you can have them all inherit from an interface IHasIdNumber with an idNumber property.

Your method would then become:

```<code>public static void OutputFile(IEnumerable<IHasIdNumber> myInput)
{
  foreach (var item in myInput)
  {
    string textToOutput = item.idNUmber;
    //output the text to somewhere else here
  }
}
</code>```

Body:
have tried some searches. Probably my lack of knowledge that I'm not using the right search terms or perhaps just not understanding the answers.

I have a method that is being passed an object, which I want to output a particular value to a text file.
I already know the object will be a List< someClass > of a few different possible classes (customers/employees/items etc). But all of the classes contain the same string property (e.g.) string idNumber.

So something like this:

public static void OutputFile(object myInput)
{
  foreach (someGenericObject in (List<anyType>)myInput)
  {
    string textToOutput = someGenericObject.idNUmber;
    //output the text to somewhere else here
  }
}

I feel like as long as I know that it will always contain a this "idNumber" property regardless of the type, that I should be able to reference it somehow. But I just can't seem to get my head around it?

The error I typically get is something like:

Cannot cast List< Employee > to List< object > etc.

Thanks in advance

Body:
As I suggested in the comments, if you have the ability to modify these classes, you can have them all inherit from an interface IHasIdNumber with an idNumber property.

Your method would then become:

public static void OutputFile(IEnumerable<IHasIdNumber> myInput)
{
  foreach (var item in myInput)
  {
    string textToOutput = item.idNUmber;
    //output the text to somewhere else here
  }
}


问:
How to check which type of data stored in a variable in python?
I am very new to Python.Is there any method through which i can find out which type of value is stored in a particular variable?

In below code how to find out type of stored value in a variable?

```<code>counter = 100
miles   = 1000.0
name    = "John"
name    =10

print counter
print miles
print name
</code>```

Body:
I am very new to Python.Is there any method through which i can find out which type of value is stored in a particular variable?

In below code how to find out type of stored value in a variable?

counter = 100
miles   = 1000.0
name    = "John"
name    =10

print counter
print miles
print name

Body:
>>> type('1')
<class 'str'>
>>> type(1)
<class 'int'>
>>> type(1.000)
<class 'float'>
>>> type({1:2})
<class 'dict'>
>>> type([1,2,3])
<class 'list'>


问:
Automatically transfer money from one bank account to another
Is there available any API which allow us to automatically transfer money to other bank account? I only found that I can't have it done with paypal API.

I have user money on one bank account and after some action in application I need to transfer this money to other user bank account.

So to summary it all, step by step:

User1 send money to application bank account.

After few hours User1 confirm some action on aplication by clicking button.

After User1 clicked button I want to transfer money to User2 bank account from application bank account automatically.

I already have in DB every information needed to do bank transfer.

I am looking for API which would allow me to do third step which is automatically transfering money from my (app) bank account to user bank account no matter which bank he is using.

答:
If you current bank doesn't support this feature (yet) there is no way to do this without switching to another bank.

I don't know if you are lucky enough to be located in The Netherlands. If you are, then you can use Bunq. They offer a nice APIs and SDKs that makes this possible.
Here are the details: https://www.bunq.com/nl/developer

I think there are plans to extend this to the rest of EU soon.


问:
How can I log a hyperlink click?
I have a hyperlink which I need to log when it's clicked.

I created a small prototype, and the problem is repeatable by creating a new MVC 2 Web app project.

Add

```<code><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</code>```

to the Site.Master file.

And

```<code>public ActionResult LogSomething()
{
    string doNothing = DateTime.Now.ToString();
    return new EmptyResult();
}
</code>```

to the HomeController.cs file

And

```<code><p>
    <a id="lnkTestPost" href="/home/about">Test Post</a>

    <script type="text/javascript">
        $("#lnkTestPost").click(function() {
            $.post("/home/LogSomething");
        });
    </script>
</p>
</code>```

in Home/Index.aspx

Put a break point in the LogSomething() action method in the HomeController.

But when I run it, sometimes the breakpoint is hit, other times it isn't.

I'm assuming it's not being hit due to the actual link sending the browser to another page, but shouldn't the post be made before the link is fired?

Is there anyway I can ensure the logging code is fired?

Please note; adding the logging functionality in the link target is not an option.

EDIT: The original hyperlink is actually to a custom protocol for an app installed on the user PC.  So the link is to something like "myapp:myArgs".  I didn't mention that in order to keep things simple, unfortunately, since none of the answers really apply to me, I now think it's necessary to mention.

答:
If I were doing it, I would probably do what, eg, Google does and setup a URL which logs then redirects. For example:

```<code><a href="/home/about">stuff</a>
<script>
    $("a:href").each(function(){
        this.attr("href", "/log?url=" + encodeURIComponent(this.attr("href")));
    });
</script>
</code>```

Then /log handler would do something like:

```<code>def log(request):
    target_url = request.GET["url"]
    log_link(target_url)
    return HttpRedirect(target_url)
</code>```

You'd need to put some thought into dealing with external links (eg, how you want to handle http://example.com/log?url=http://evil.com/)… But that's a solvable problem.

Also, for bonus points, you could swap the URL as the link is clicked (this is what Google does in their search results), so the mouse-over link-preview looks correct.

Title: How can I log a hyperlink click?

Body:
I have a hyperlink which I need to log when it's clicked.

I created a small prototype, and the problem is repeatable by creating a new MVC 2 Web app project.

Add

to the Site.Master file.

And

public ActionResult LogSomething()
{
    string doNothing = DateTime.Now.ToString();
    return new EmptyResult();
}

to the HomeController.cs file

And

    Test Post

in Home/Index.aspx

Put a break point in the LogSomething() action method in the HomeController.

But when I run it, sometimes the breakpoint is hit, other times it isn't.

I'm assuming it's not being hit due to the actual link sending the browser to another page, but shouldn't the post be made before the link is fired?

Is there anyway I can ensure the logging code is fired?

Please note; adding the logging functionality in the link target is not an option.

EDIT: The original hyperlink is actually to a custom protocol for an app installed on the user PC.  So the link is to something like "myapp:myArgs".  I didn't mention that in order to keep things simple, unfortunately, since none of the answers really apply to me, I now think it's necessary to mention.

Body:
If I were doing it, I would probably do what, eg, Google does and setup a URL which logs then redirects. For example:

<a href="/home/about">stuff</a>
<script>
    $("a:href").each(function(){
        this.attr("href", "/log?url=" + encodeURIComponent(this.attr("href")));
    });
</script>

Then /log handler would do something like:

def log(request):
    target_url = request.GET["url"]
    log_link(target_url)
    return HttpRedirect(target_url)

You'd need to put some thought into dealing with external links (eg, how you want to handle http://example.com/log?url=http://evil.com/)… But that's a solvable problem.

Also, for bonus points, you could swap the URL as the link is clicked (this is what Google does in their search results), so the mouse-over link-preview looks correct.


问:
How to install window service using installer in c#
I am having trouble in finalizing my window service.As my logic works fine in console application.But the problem is:

How to add installer and installutil.exe in the project?

答:
Go to Visual Studio Command prompt, and type installutil.exe <path to exe>

Alternatively, installutil.exe is located under C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe

Note: Depending on your framework version, path to installutil.exe will change

Refer to this SO thread which has already an answer
Install a Windows service using a Windows command prompt?

Are you having trouble while adding installer in your project? Any detailed information will help us in guiding you in the right direction


问:
how to check array index
I have following code in jquery

```<code>var newFeeds = [];
$(data.d).each(function () {
  newFeeds.push({
    content: this.Name,
    id: this.Id
  });
});
</code>```

I am able to access values from newFeeds[0].content, newFeeds[1].content, newFeeds[2].content but when I tried to
 access newFeeds[3].content its showing undefined error and checked typeof equals(===) undefined but its showing Uncaught TypeError: Cannot read property 'content' of undefined error. How can I avoid this error. I have only 3 elements in the array. Is there a way in Jquery to avoid this error or Can I set value not available in non existence index ?

答:
 i=0
 while(i <= newsFeed.length)
   if (newFeeds[i])
      //Your code goes here
   else
      i++```

Try by doing above.

Title: how to check array index

Body:
I have following code in jquery

var newFeeds = [];
$(data.d).each(function () {
  newFeeds.push({
    content: this.Name,
    id: this.Id
  });
});

I am able to access values from newFeeds[0].content, newFeeds[1].content, newFeeds[2].content but when I tried to
 access newFeeds[3].content its showing undefined error and checked typeof equals(===) undefined but its showing Uncaught TypeError: Cannot read property 'content' of undefined error. How can I avoid this error. I have only 3 elements in the array. Is there a way in Jquery to avoid this error or Can I set value not available in non existence index ?

Body:
 i=0
 while(i <= newsFeed.length)
   if (newFeeds[i])
      //Your code goes here
   else
      i++

Try by doing above.


问:
URL link not redirecting properly in Angularjs
I have a link in my announce.obj. But when I clicked it, it's giving me the wrong url (http://www./) in the browser.

html

```<code><p>
  <a ng-href="{{data.links}}" target="_blank">{{data.links}}</a>
</p>
</code>```

data.links value

```<code>www.google.com
</code>```

Should I add an https when saving my links in the db or something ?

答: Give the data.links a complete url value, copy it from the mobile browser including the https//: and all , this is a case of the url not beibg recognized.</p>

Body:
I have a link in my announce.obj. But when I clicked it, it's giving me the wrong url (http://www./) in the browser.

html

  {{data.links}}

data.links value

www.google.com

Should I add an https when saving my links in the db or something ?


问:
What are the problems with MySQL that cause it to get bad press?
I'm primarily a PostgreSQL user and I frequently hear about MySQL getting bad press (much like PHP). However, I don't actually know or understand why this happens. So I'm curious, what are the large problems with MySQL that cause developers to prefer other database solutions, and how real are the problems in the current releases?</p>

答:
I read something about this just yesterday in Phil Greenspun's blog:

Now that MySQL is 16 years old, I was surprised at the things that they’ve yet to accomplish. For example, the C in ACID is “Consistency”, i.e., being able to enforce rules in the SQL data model and using the RDBMS as a last line of defense against programmer mistakes. Yet MySQL silently fails to enforce any CHECK constraint. Similarly, when students would GROUP BY column_a and then SELECT column_b (where column_b had multiple values within each group), instead of raising an error as Oracle, Postgres, or SQL Server would, MySQL happily picks a column_b value at random and includes it. I don’t understand why people use it.

Also, the MySQL Gotchas page is a classic list.


问:
Angular 2 - Component Inheritance - base class variable not propagated to base template
Is there something special to do when using Component Inheritance ?

edit : this concerns INHERITANCE, not parent/child view/components communication

as I try to hide a div defined in the base class template, it does not work

in the page, the variable is not even updated even if it gets modified in the code

1st, I tried with [hidden] and *ngIf

then I tried using changeDetectorRef but it does not do anything

it seems the value is not propagated to the template

base class:

```<code>@Component({
    selector: 'my-content',
    templateUrl: './content.component.html',
    styleUrls: ['./content.component.css'],
})
export class ContentComponent implements OnInit {

    protected overlayVisible:boolean;

    constructor(....){...}

    ngOnInit() {
    }

    showOverlay()
    {
        this.overlayVisible=true; <<<<<<<<<<<<<< THESE GET CALLED
    }

    hideOverlay()
    {
        this.overlayVisible=false; <<<<<<<<<<<<<< THESE GET CALLED
    }
}
</code>```

base template (content.component.html):

```<code><div>
    <div class="contentMainDiv">
        <div class="contentBodyDiv"><ng-content select="[body]"></ng-content></div>
        <div [innerHTML]=" overlayVisible?'true':'false' "></div> /// DEBUG DIV
        <div [hidden]="!overlayVisible" class="contentOverlay" >
            <my-wait></my-wait>
        </div>

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

child component :

```<code>export class CustomersComponent extends ContentComponent implements OnInit {

    private customers: any;

    constructor(
        private customersService: CustomersService,
        injector:Injector
        ) { super(injector); }

    getCustomers() {
        this.showOverlay();

        this.customersService.getCustomers().subscribe((customers: any) => {
            this.customers = customers;
            this.hideOverlay();
        });
    }
</code>```

child template :

```<code><my-content>
    <div body>
        <div *ngIf="customers">
            some table ...
        </div>
    </div>
</my-content>
</code>```

what am I missing

is there something special to do when we use component inheritance ?

thanks

答:
the way I made it work is by removing the exportas

```<code><my-base-frame #baseFrame>
...
</my-base-frame>
</code>```

in the code

```<code>@ViewChildren('baseFrame') baseFrames; // finaly found how to get base class instance
</code>```

...

```<code>this.baseFrames.changes.subscribe( (_comps: QueryList <any>)
    {
        if(this.baseFrames.first && !this.baseFrame)
        {
            this.baseFrame=this.baseFrames.first;
            ...
        }
    })
</code>```

Body:
Is there something special to do when using Component Inheritance ?

edit : this concerns INHERITANCE, not parent/child view/components communication

as I try to hide a div defined in the base class template, it does not work

in the page, the variable is not even updated even if it gets modified in the code

1st, I tried with [hidden] and *ngIf

then I tried using changeDetectorRef but it does not do anything

it seems the value is not propagated to the template

base class:

@Component({
    selector: 'my-content',
    templateUrl: './content.component.html',
    styleUrls: ['./content.component.css'],
})
export class ContentComponent implements OnInit {

    protected overlayVisible:boolean;

    constructor(....){...}

    ngOnInit() {
    }

    showOverlay()
    {
        this.overlayVisible=true; <<<<<<<<<<<<<< THESE GET CALLED
    }

    hideOverlay()
    {
        this.overlayVisible=false; <<<<<<<<<<<<<< THESE GET CALLED
    }
}

base template (content.component.html):

<ng-content select="[body]"></ng-content>

 /// DEBUG DIV

            <my-wait></my-wait>

child component :

export class CustomersComponent extends ContentComponent implements OnInit {

    private customers: any;

    constructor(
        private customersService: CustomersService,
        injector:Injector
        ) { super(injector); }

    getCustomers() {
        this.showOverlay();

        this.customersService.getCustomers().subscribe((customers: any) => {
            this.customers = customers;
            this.hideOverlay();
        });
    }

child template :

<my-content>

            some table ...

</my-content>

what am I missing

is there something special to do when we use component inheritance ?

thanks

Body:
the way I made it work is by removing the exportas

<my-base-frame #baseFrame>
...
</my-base-frame>

in the code

@ViewChildren('baseFrame') baseFrames; // finaly found how to get base class instance

...

this.baseFrames.changes.subscribe( (_comps: QueryList <any>)
    {
        if(this.baseFrames.first && !this.baseFrame)
        {
            this.baseFrame=this.baseFrames.first;
            ...
        }
    })


问:
I need this for license check
is there a way to get from SQL Server a unique identifier?

I need this for license check. My application uses SQL Server and I give an activation key that is generated using that unique number. This means that the activation key will enable the user to launch the application only if he is connecting to the server he paid the license for.

It would be better and easier for me to directly call some SQL Query to retrieve some unique number that is generated once SQL Server is installed.

Is it possible?

Thanks!

答: NEWID() function will give you a GUID if that will work for you. If not you could write a function to generate a random number, store it in a table with a unique index, and return it if the insertion into the table is valid.

Title: I need this for license check


答:
you should have the value as,</p>

```<code>http://www.google.com
</code>```

Title: URL link not redirecting properly in Angularjs

Body:
you should have the value as,

http://www.google.com


问:
Bootstrap 4 - Child automatically aligns center (vertically) when parent height is longer than child
I was using bootstrap 4 when I found this behaviour unexpected:

https://jsfiddle.net/hzse8gfd/1/

In my fiddle, I have a sidebar which is stretched to screen's maximum height.I then have a 50px logo sitting on top of the sidebar, and a div that holds the rest of the sidebar content.

What I realised is that the content gets vertically pushed down/align center of the parent height, when I am expecting it stick to the top, just like the logo segment. Just curious why is the behavior as such.

I'm using bootstrap 4

HTML:

```<code><div id="sidebar" class="row">
    <div class="col-12 logo">
    </div>
    <div class="col-12 sidebar-content">
        <div class="row">
            <ul id="sidebar-results">
                <li>Result 1</li>
                <li>Result 2</li>
                <li>Result 3</li>
                <li>Result 4</li>
                <li>Result 5</li>
                <li>Result 6</li>
                <li>Result 7</li>
                <li>Result 8</li>
            </ul>
        </div>
    </div>
</div>
</code>```

CSS:

```<code>.logo{
  width:200px;
  height:50px;
  background-color:blue;
}

#sidebar{
  height:100vh;
}
</code>```

答:
I found out it's because you use .col-12 twice in a single .row, while total amount of columns should add up to 12 - your case: 24.

.logo{
  width:200px;
  height:50px;
  background-color:blue;
}

#sidebar{
  height:100vh;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div id="sidebar">
  <!-- LOGO ROW -->
  <div class="row">
      <div class="col-12 logo"></div>
  </div>
  <!-- RESULTS ROW -->
  <div class="row">
    <div class="col-12 sidebar-content">
        <ul id="sidebar-results">
          <li>Result 1</li>
          <li>Result 2</li>
          <li>Result 3</li>
          <li>Result 4</li>
          <li>Result 5</li>
          <li>Result 6</li>
          <li>Result 7</li>
          <li>Result 8</li>
        </ul>
    </div>
  </div>
</div></code>```

Body:
I was using bootstrap 4 when I found this behaviour unexpected:

https://jsfiddle.net/hzse8gfd/1/

In my fiddle, I have a sidebar which is stretched to screen's maximum height.I then have a 50px logo sitting on top of the sidebar, and a div that holds the rest of the sidebar content.

What I realised is that the content gets vertically pushed down/align center of the parent height, when I am expecting it stick to the top, just like the logo segment. Just curious why is the behavior as such.

I'm using bootstrap 4

HTML:

Result 1

Result 2

Result 3

Result 4

Result 5

Result 6

Result 7

Result 8

CSS:

.logo{
  width:200px;
  height:50px;
  background-color:blue;
}

#sidebar{
  height:100vh;
}

Body:
I found out it's because you use .col-12 twice in a single .row, while total amount of columns should add up to 12 - your case: 24.

.logo{
  width:200px;
  height:50px;
  background-color:blue;
}

#sidebar{
  height:100vh;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div id="sidebar">
  <!-- LOGO ROW -->
  <div class="row">
      <div class="col-12 logo"></div>
  </div>
  <!-- RESULTS ROW -->
  <div class="row">
    <div class="col-12 sidebar-content">
        <ul id="sidebar-results">
          <li>Result 1</li>
          <li>Result 2</li>
          <li>Result 3</li>
          <li>Result 4</li>
          <li>Result 5</li>
          <li>Result 6</li>
          <li>Result 7</li>
          <li>Result 8</li>
        </ul>
    </div>
  </div>
</div>


问:
Order by joined table through table
my mySQL (pun intended) is a bit rusty. I am trying to join a table through another table.

```<code>carparks has many clients
clients has many cars
</code>```

This is the query

```<code>select `carparks`.* from `carparks`

left join `clients` on `carparks`.`carpark_id` = `clients`.`carpark_id`

left join `cars` on `clients`.`client_id` = `cars`.`client_id`

where `carparks`.`carpark_id` in (1, 3, 8, 33, 34, 38, 39)

order by `cars`.`created_at` desc
</code>```

As you can see I am trying to order by the created_at column of cars, the above query though returns duplicated carparks for each of the cars within the carpark.

What I am looking at is to return only those carparks with the ids in the WHERE IN clause, simply ordered by the created_at column of the cars table.

Thanks

答:
You can use aggregation in your order  by clause on max created date from cars table</p>

```<code>SELECT cp.*
FROM `carparks` cp
LEFT JOIN `clients` cl ON cp.`carpark_id` = cl.`carpark_id`
LEFT JOIN `cars` c ON cl.`client_id` = c.`client_id`
WHERE cp.`carpark_id` IN (1, 3, 8, 33, 34, 38, 39)
GROUP BY cp.`carpark_id`
ORDER BY MAX(c.`created_at`) DESC
</code>```

Title: Order by joined table through table

Body:
my mySQL (pun intended) is a bit rusty. I am trying to join a table through another table.

carparks has many clients
clients has many cars

This is the query

select `carparks`.* from `carparks`

left join `clients` on `carparks`.`carpark_id` = `clients`.`carpark_id`

left join `cars` on `clients`.`client_id` = `cars`.`client_id`

where `carparks`.`carpark_id` in (1, 3, 8, 33, 34, 38, 39)

order by `cars`.`created_at` desc

As you can see I am trying to order by the created_at column of cars, the above query though returns duplicated carparks for each of the cars within the carpark.

What I am looking at is to return only those carparks with the ids in the WHERE IN clause, simply ordered by the created_at column of the cars table.

Thanks

Body:
You can use aggregation in your order  by clause on max created date from cars table

SELECT cp.*
FROM `carparks` cp
LEFT JOIN `clients` cl ON cp.`carpark_id` = cl.`carpark_id`
LEFT JOIN `cars` c ON cl.`client_id` = c.`client_id`
WHERE cp.`carpark_id` IN (1, 3, 8, 33, 34, 38, 39)
GROUP BY cp.`carpark_id`
ORDER BY MAX(c.`created_at`) DESC


答:
There are a few ways you can solve this.

Recommended way: Implement common interface:

```<code>public interface INumberable { // I'm sure you can come up with a better name...
    string IDNumber { get; set; }
}
</code>```

And then all the possible classes that can be passed into the method will implement INumberable. Your method can then look like this:

```<code>public static void OutputFile(List<INumerable> myInput)
{
  foreach (var someGenericObject in myInput)
  {
    string textToOutput = someGenericObject.idNUmber;
    //output the text to somewhere else here
  }
}
</code>```

Not-so-recommended way: Reflection:

```<code>Type t = someGenericObject.GetType();
var p = t.GetProperty("idNumber");
string theStringYouWant = (string)p.GetValue(someGenericObject);
</code>```

Note that this is not very safe.

Title: Reference known property in (List<someClass>)someObject

Body:
There are a few ways you can solve this.

Recommended way: Implement common interface:

public interface INumberable { // I'm sure you can come up with a better name...
    string IDNumber { get; set; }
}

And then all the possible classes that can be passed into the method will implement INumberable. Your method can then look like this:

public static void OutputFile(List<INumerable> myInput)
{
  foreach (var someGenericObject in myInput)
  {
    string textToOutput = someGenericObject.idNUmber;
    //output the text to somewhere else here
  }
}

Not-so-recommended way: Reflection:

Type t = someGenericObject.GetType();
var p = t.GetProperty("idNumber");
string theStringYouWant = (string)p.GetValue(someGenericObject);

Note that this is not very safe.


问:
creating xsl-fo with correct format
I need to create an xsl-fo document from an xml document which displays information of the the export ammount (profits) for each year and, within each year, for every region.

in order to produce a table which contains, for each year, the earnings for that year and how it compares to the previous year, in a three column table displaying such information.

this problem seems to have the whole class stumped and the teacher isn't currently available for consultation. Any help would be greatly appreciated. Thanks in advance.

答:
Another example that generates XSL-FO using round() function.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:fo="http://www.w3.org/1999/XSL/Format"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:output indent="yes"/>

    <xsl:template match="/">
        <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format"
            xmlns:axf="http://www.antennahouse.com/names/XSL/Extensions" xml:lang="en-US"
            id="id_document">
            <fo:layout-master-set>
                <fo:simple-page-master master-name="spm" page-width="6in" page-height="5in">
                    <fo:region-body margin-top="0.5in" margin-bottom="0.5in" margin-left="0.5in"
                        margin-right="0.5in" overflow="error-if-overflow"/>
                </fo:simple-page-master>
            </fo:layout-master-set>
            <fo:page-sequence master-reference="spm" reference-orientation="from-page-master-region()"
                writing-mode="from-page-master-region()">
                <fo:flow flow-name="xsl-region-body" font-family="Arial" font-size="11pt">
                    <xsl:apply-templates/>
                </fo:flow>
            </fo:page-sequence>
        </fo:root>
    </xsl:template>

    <xsl:template match="exports">
        <fo:table>
            <fo:table-column column-number="1" column-width="5em"/>
            <fo:table-column column-number="2" column-width="7em"/>
            <fo:table-column column-number="3" column-width="5em"/>
            <fo:table-body>
                <xsl:apply-templates/>
            </fo:table-body>
        </fo:table>
    </xsl:template>

    <xsl:template match="year">
        <xsl:variable name="currTotal" as="xs:decimal" select="xs:decimal(total)"/>
        <fo:table-row>
            <fo:table-cell>
                <fo:block>
                    <xsl:value-of select="./text()"/>
                </fo:block>
            </fo:table-cell>
            <fo:table-cell>
                <fo:block>
                    <xsl:value-of select="concat('$',round($currTotal * 10) div 10)"/>
                </fo:block>
            </fo:table-cell>
            <fo:table-cell>
                <fo:block>
                    <xsl:choose>
                        <xsl:when test="empty(preceding-sibling::*)">
                            <xsl:text>-</xsl:text>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:variable name="prevTotal" as="xs:decimal" select="xs:decimal(preceding-sibling::*[1]/total)"/>
                            <xsl:variable name="totalDiff" as="xs:decimal" select="$currTotal - $prevTotal"/>
                            <xsl:variable name="percentage" as="xs:decimal" select="round($totalDiff div $prevTotal * 10000) div 100"/>
                            <xsl:value-of select="concat($percentage,'%')"/>
                        </xsl:otherwise>
                    </xsl:choose>
                </fo:block>
            </fo:table-cell>
        </fo:table-row>
    </xsl:template>

</xsl:stylesheet>
</code>```

The main feature are

Generate fo:table from match="export" template.

Genrate each fo:table-row from match="year" template.

Use round() function to get each precision of values. (format-number() will be easier)

Use empty(preceding-sibling::*) to judge the first year element in exports.

The sample result:

Title: creating xsl-fo with correct format

Body:
Another example that generates XSL-FO using round() function.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:fo="http://www.w3.org/1999/XSL/Format"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:output indent="yes"/>

    <xsl:template match="/">
        <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format"
            xmlns:axf="http://www.antennahouse.com/names/XSL/Extensions" xml:lang="en-US"
            id="id_document">
            <fo:layout-master-set>
                <fo:simple-page-master master-name="spm" page-width="6in" page-height="5in">
                    <fo:region-body margin-top="0.5in" margin-bottom="0.5in" margin-left="0.5in"
                        margin-right="0.5in" overflow="error-if-overflow"/>
                </fo:simple-page-master>
            </fo:layout-master-set>
            <fo:page-sequence master-reference="spm" reference-orientation="from-page-master-region()"
                writing-mode="from-page-master-region()">
                <fo:flow flow-name="xsl-region-body" font-family="Arial" font-size="11pt">
                    <xsl:apply-templates/>
                </fo:flow>
            </fo:page-sequence>
        </fo:root>
    </xsl:template>

    <xsl:template match="exports">
        <fo:table>
            <fo:table-column column-number="1" column-width="5em"/>
            <fo:table-column column-number="2" column-width="7em"/>
            <fo:table-column column-number="3" column-width="5em"/>
            <fo:table-body>
                <xsl:apply-templates/>
            </fo:table-body>
        </fo:table>
    </xsl:template>

    <xsl:template match="year">
        <xsl:variable name="currTotal" as="xs:decimal" select="xs:decimal(total)"/>
        <fo:table-row>
            <fo:table-cell>
                <fo:block>
                    <xsl:value-of select="./text()"/>
                </fo:block>
            </fo:table-cell>
            <fo:table-cell>
                <fo:block>
                    <xsl:value-of select="concat('$',round($currTotal * 10) div 10)"/>
                </fo:block>
            </fo:table-cell>
            <fo:table-cell>
                <fo:block>
                    <xsl:choose>
                        <xsl:when test="empty(preceding-sibling::*)">
                            <xsl:text>-</xsl:text>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:variable name="prevTotal" as="xs:decimal" select="xs:decimal(preceding-sibling::*[1]/total)"/>
                            <xsl:variable name="totalDiff" as="xs:decimal" select="$currTotal - $prevTotal"/>
                            <xsl:variable name="percentage" as="xs:decimal" select="round($totalDiff div $prevTotal * 10000) div 100"/>
                            <xsl:value-of select="concat($percentage,'%')"/>
                        </xsl:otherwise>
                    </xsl:choose>
                </fo:block>
            </fo:table-cell>
        </fo:table-row>
    </xsl:template>

</xsl:stylesheet>

The main feature are

Generate fo:table from match="export" template.

Genrate each fo:table-row from match="year" template.

Use round() function to get each precision of values. (format-number() will be easier)

Use empty(preceding-sibling::*) to judge the first year element in exports.

The sample result:


问:
MongoDb shell scripting
Do you know if it is possible to get a list of databases(like 'show dbs' in console) from javascript. I want to drop all databases from mongo via javascript file (mongo admin.js), but i can't find a way to list all databases...

Thx

I'm trying to prepare simple script but i can't find out how i can change db from script.
Here is the sample javascript script. It always fails on command "use". I tried with db.eval and eval but it fails.

```<code>print(db.getMongo().getDBNames());
var environments = db.getMongo().getDBNames()
for(var environmentIndex in environments){
    print(environments[environmentIndex])
    eval("use staging");
    //db.dropDatabase();
}
</code>```

答:
Use db.adminCommand('listDatabases'). For other commands see http://www.mongodb.org/display/DOCS/List+of+Database+Commands

EDIT:

In util.js use dbname is defined as:

```<code>shellHelper.use = function( dbname ){
    db = db.getMongo().getDB( dbname );
    print( "switched to db " + db.getName() );
}
</code>```

Title: MongoDb shell scripting

Body:
Do you know if it is possible to get a list of databases(like 'show dbs' in console) from javascript. I want to drop all databases from mongo via javascript file (mongo admin.js), but i can't find a way to list all databases...

Thx

I'm trying to prepare simple script but i can't find out how i can change db from script.
Here is the sample javascript script. It always fails on command "use". I tried with db.eval and eval but it fails.

print(db.getMongo().getDBNames());
var environments = db.getMongo().getDBNames()
for(var environmentIndex in environments){
    print(environments[environmentIndex])
    eval("use staging");
    //db.dropDatabase();
}

Body:
Use db.adminCommand('listDatabases'). For other commands see http://www.mongodb.org/display/DOCS/List+of+Database+Commands

EDIT:

In util.js use dbname is defined as:

shellHelper.use = function( dbname ){
    db = db.getMongo().getDB( dbname );
    print( "switched to db " + db.getName() );
}


答:
I am able to access values from newFeeds[0].content,
  newFeeds[1].content, newFeeds[2].content but when I tried to access
  newFeeds[3].content its showing undefined error and checked typeof
  equals(===) undefined but its showing Uncaught TypeError: Cannot read
  property 'content' of undefined error. How can I avoid this error. I
  have only 3 elements in the array. Is there a way in Jquery to avoid
  this error or Can I set value not available in non existence index ?

Use (index_key in your_array) Here is example

Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined ?

```<code>"key" in your_object_or_array // true, regardless of the actual value
</code>```

var newfeeds = [{
  content: 'first'
}, {
  content: 'second'
}, {
  content: 'third'
}];

console.log(
   0 in newfeeds
);
console.log(
   2 in newfeeds
);
console.log(
   3 in newfeeds
);

/* So what you can use is */
var index_key = 1;
if(index_key in newfeeds){
    console.log(newfeeds[index_key].content);
}else{
   console.log(index_key + ' no such index');
}

var index_key = 3;
if(index_key in newfeeds){
    console.log(newfeeds[index_key].content);
}else{
   console.log(index_key + ' no such index');
}```

Title: how to check array index

Body:
I am able to access values from newFeeds[0].content,
  newFeeds[1].content, newFeeds[2].content but when I tried to access
  newFeeds[3].content its showing undefined error and checked typeof
  equals(===) undefined but its showing Uncaught TypeError: Cannot read
  property 'content' of undefined error. How can I avoid this error. I
  have only 3 elements in the array. Is there a way in Jquery to avoid
  this error or Can I set value not available in non existence index ?

Use (index_key in your_array) Here is example

Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined ?

"key" in your_object_or_array // true, regardless of the actual value

var newfeeds = [{
  content: 'first'
}, {
  content: 'second'
}, {
  content: 'third'
}];

console.log(
   0 in newfeeds
);
console.log(
   2 in newfeeds
);
console.log(
   3 in newfeeds
);

/* So what you can use is */
var index_key = 1;
if(index_key in newfeeds){
    console.log(newfeeds[index_key].content);
}else{
   console.log(index_key + ' no such index');
}

var index_key = 3;
if(index_key in newfeeds){
    console.log(newfeeds[index_key].content);
}else{
   console.log(index_key + ' no such index');
}


问:
pointers in C++ (need overview)
```<code>int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;    //line 1
*p2 = *p1;  //line 2
 p1 = p2;   //line 3
*p1 = 20;

cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
</code>```

My Analysis of this code:
p1 points to the first value and p2 points to the second value. Now, p1 points to value 10. My first question is :

Does this means that first value now stores 10. (line 1)

According to me, line 2 means that p2 and p1 point to the value stored at the address of the second value. AM I correct or wrong?

Lastly, I have no clue of line 3. So, need some help over there too.

答:
Forget syntax for a second and think about what those objects are.
A memory location has exactly two properties, location and content.

int firstvalue; reserves a memory location (its size does not matter here).
firstvalue = 5; stores a value there.

firstvalue is a label associated with the memory address, &firstvalue is that address.
A pointer is a variable containing an address, dereferencing with '*' gives you the content at that address.

So now

```<code>p1 = &firstvalue;  //address of firstvalue stored in pointer p1
p2 = &secondvalue; // same thing for p2 and secondvalue
*p1 = 10; //line 1: value 10 to variable pointed to by p1 i.e. firstvalue
*p2 = *p1;    //line  2: copy firstvalue to secondvalue
 p1 = p2;     //line 3:  now both point to secondvalue
</code>```

Ok?

Title: pointers in C++ (need overview)

Body:
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;    //line 1
*p2 = *p1;  //line 2
 p1 = p2;   //line 3
*p1 = 20;

cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;

My Analysis of this code:
p1 points to the first value and p2 points to the second value. Now, p1 points to value 10. My first question is :

Does this means that first value now stores 10. (line 1)

According to me, line 2 means that p2 and p1 point to the value stored at the address of the second value. AM I correct or wrong?

Lastly, I have no clue of line 3. So, need some help over there too.

Body:
Forget syntax for a second and think about what those objects are.
A memory location has exactly two properties, location and content.

int firstvalue; reserves a memory location (its size does not matter here).
firstvalue = 5; stores a value there.

firstvalue is a label associated with the memory address, &firstvalue is that address.
A pointer is a variable containing an address, dereferencing with '*' gives you the content at that address.

So now

p1 = &firstvalue;  //address of firstvalue stored in pointer p1
p2 = &secondvalue; // same thing for p2 and secondvalue
*p1 = 10; //line 1: value 10 to variable pointed to by p1 i.e. firstvalue
*p2 = *p1;    //line  2: copy firstvalue to secondvalue
 p1 = p2;     //line 3:  now both point to secondvalue

Ok?


问:
App crashes in viewForHeaderInSection:
I have have a tableview integrated in my app. The code is like this

```<code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [sortedDates count];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    EventHeaderView *headerView = (EventHeaderView *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"eventHeader"];
    if(headerView == nil) {
        headerView = [[EventHeaderView alloc] initWithReuseIdentifier:@"eventHeader"];
    }

    NSString *date = [sortedDates objectAtIndex:section]; **// app crashes here**
    NSString *formatHeaderStr = [NSDate stringFromDate:[NSDate dateFromString:date withFormat:@"yyyy-MM-dd"] withFormat:@"EE, MMMM dd yyyy"];
    [headerView.dateLbl setText:formatHeaderStr];
    [headerView.addEventBtn setTag:(section+1)*100];
    [headerView.addEventBtn addTarget:self action:@selector(addEventBtnClicked:) forControlEvents:UIControlEventTouchUpInside];

    [headerView layoutSubviews];
    return headerView;
}
</code>```

The number of sections return 'sortedDates' count but still viewForHeader crashes on [sortedDates objectAtIndex:section]. It happens at other places in my code as well.

I do not understand how to fix such issues. There is very small delay in these methods being getting called one after the other but still the array seems to be empty when it reaches the viewForHeader methods.

Kindly help.

答:
Use this for getting value from sortedDates.

```<code>NSString *date = [sortedDates objectAtIndex:section-1];
</code>```

Title: App crashes in viewForHeaderInSection:

Body:
I have have a tableview integrated in my app. The code is like this

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [sortedDates count];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    EventHeaderView *headerView = (EventHeaderView *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"eventHeader"];
    if(headerView == nil) {
        headerView = [[EventHeaderView alloc] initWithReuseIdentifier:@"eventHeader"];
    }

    NSString *date = [sortedDates objectAtIndex:section]; **// app crashes here**
    NSString *formatHeaderStr = [NSDate stringFromDate:[NSDate dateFromString:date withFormat:@"yyyy-MM-dd"] withFormat:@"EE, MMMM dd yyyy"];
    [headerView.dateLbl setText:formatHeaderStr];
    [headerView.addEventBtn setTag:(section+1)*100];
    [headerView.addEventBtn addTarget:self action:@selector(addEventBtnClicked:) forControlEvents:UIControlEventTouchUpInside];

    [headerView layoutSubviews];
    return headerView;
}

The number of sections return 'sortedDates' count but still viewForHeader crashes on [sortedDates objectAtIndex:section]. It happens at other places in my code as well.

I do not understand how to fix such issues. There is very small delay in these methods being getting called one after the other but still the array seems to be empty when it reaches the viewForHeader methods.

Kindly help.

Body:
Use this for getting value from sortedDates.

NSString *date = [sortedDates objectAtIndex:section-1];


问:
SSIS Main Package throwing Error : Package Failed Validation From Execute Package Task
i have a Main Package and 2 child packages(Load and Export). i have both child packages on the server in shared folder. when i execute Main Package its giving me the following Error for one of the Child package.

Error: Error 0xC0012050 while loading package file "\mhfile02\DIRFILEDEV\CHG77253\SSIS Packages\AaeAutoenrollee_Load.dtsx". Package failed validation from the ExecutePackage task. The package cannot run. .

Can anybody tell me what could be wrong?

Thanks

答:
From one day to another, I got this error in Visual Studio / SSDT too (VS 2013, with SSIS 2014). Note: I have project deployment model, not package deployment.
I have ProtectionLevel = EncryptSensitiveWithPassword.

In the master package, on all package execution tasks, I had to retype the password for the sub-packages again. After that, it worked again. I guess the master package had some corruption, no idea why.

Greetings,
Roli


问:
Current feature pack which is installed in WCS
Is there a way to find out the current installed feature pack and fix pack version in WCS?

The versionInfo.bat does not give me the sufficient information related to it!

答:
You can also see the versions of installed packages using

Start->All Programs-> IBM Installation Manager->View Installed Packages.

or

using this file

C:\ {IBM RAD Installed Path}\IBM\Installation Manager\installed.xml


问:
bootstrap 4 beta 2 back-to-top does not work
I have a back-to-top link in my navbar which work properly in bootstrap 3.3.7 but not in bootstrap 4 beta 2

back-to-top js file

```<code>$(document).ready(function(){
   var offset = 100;
   var duration = 800;

$(window).scroll(function () {
    if ($(this).scrollTop() > offset) {
        $('#back-to-top').fadeIn(duration);
    } else {
        $('#back-to-top').fadeOut(duration);
    }
});

// scroll body to 0px on click
$('#back-to-top').click(function (event) {
    event.preventDefault();
    $('#back-to-top').tooltip('hide');
    $('body,html').animate({
        scrollTop: 0
    }, duration);
    return false;
});

$('#back-to-top').tooltip('show');
});
</code>```

html code in the web application

```<code>  <body id="page-top" data-spy="scroll" data-target=".fixed-top">

        <div id="main-navbar" class="navbar fixed-top navbar-expand-md navbar-custom navbar-dark" role="navigation" >

                <div class="navbar-header">

                    <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbar-main-collapse">

                        <span class="sr-only">Toggle navigation</span>Menu
                        <i class="navbar-icon fa fa-bars icon"></i>
                         <!--<span class="navbar-toggler-icon"></span>-->

                    </button>

                    <a href="#" id="menu-toggler" class="navbar-brand"> <i class="fa fa-bars"></i></a>
                    <a href="#" class="navbar-brand page-scroll" id="back-to-top">Funeral Aftercare Service</a>

                </div>

                <div class="collapse navbar-collapse" id="navbar-main-collapse">
                    <ul class="nav navbar-nav">
                        <li class="d-none"><a href="#page-top"></a></li>
                        <li class="nav-item">
                            <a class="<?php echo $index; ?>" href="index.php">
                                <span class="fa fa-home"></span> Home <span class="sr-only">(current)</span>
                            </a>
                        </li>
                        <li class="nav-item"><a class="<?php echo $about; ?>" href="about_us.php">About Us</a></li>
                        <li class="nav-item"><a class="<?php echo $contact; ?>" href="contact_info.php">Contact Info</a></li>

                    </ul>...
</code>```

I notice that in the bootstrap 3, the jquery file (jquery-3.2.1.min.js) load more functions in for my back-to-top link while in bootstrap 4 less.

bootstrap 4 load only the first 2 in inspect view while bootstrap 3 load all of them

click -back-to-top.js (jQuery)

click - jquery-3.2.1.min.js (Bubbling DOM2)

focusin - jquery-3.2.1.min.js (jQuery)

focusout - jquery-3.2.1.min.js (jQuery)

mouseout - jquery-3.2.1.min.js (jQuery)

mouseout - jquery-3.2.1.min.js (Bubbling DOM2)

mouseover - jquery-3.2.1.min.js (jQuery)

mouseover - jquery-3.2.1.min.js (Bubbling DOM2)

答:
Based on bootstrap 4 documentation:

“If you’re using our compiled JavaScript, don’t forget to include CDN versions of jQuery and Popper.js before it.”

Your code seems correct, you need to load popper.js after jquery and before bootstrap 4.

Body:
I have a back-to-top link in my navbar which work properly in bootstrap 3.3.7 but not in bootstrap 4 beta 2

back-to-top js file

$(document).ready(function(){
   var offset = 100;
   var duration = 800;

$(window).scroll(function () {
    if ($(this).scrollTop() > offset) {
        $('#back-to-top').fadeIn(duration);
    } else {
        $('#back-to-top').fadeOut(duration);
    }
});

// scroll body to 0px on click
$('#back-to-top').click(function (event) {
    event.preventDefault();
    $('#back-to-top').tooltip('hide');
    $('body,html').animate({
        scrollTop: 0
    }, duration);
    return false;
});

$('#back-to-top').tooltip('show');
});

html code in the web application

                    <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbar-main-collapse">

                        Toggle navigationMenu

                    </button>

                    Funeral Aftercare Service

                            <a class="<?php echo $index; ?>" href="index.php">
                                 Home (current)

<a class="<?php echo $about; ?>" href="about_us.php">About Us

<a class="<?php echo $contact; ?>" href="contact_info.php">Contact Info

...

I notice that in the bootstrap 3, the jquery file (jquery-3.2.1.min.js) load more functions in for my back-to-top link while in bootstrap 4 less.

bootstrap 4 load only the first 2 in inspect view while bootstrap 3 load all of them

click -back-to-top.js (jQuery)

click - jquery-3.2.1.min.js (Bubbling DOM2)

focusin - jquery-3.2.1.min.js (jQuery)

focusout - jquery-3.2.1.min.js (jQuery)

mouseout - jquery-3.2.1.min.js (jQuery)

mouseout - jquery-3.2.1.min.js (Bubbling DOM2)

mouseover - jquery-3.2.1.min.js (jQuery)

mouseover - jquery-3.2.1.min.js (Bubbling DOM2)


问:
PHP SQL convert time to compare and display
I have a design of a page as the code below.
There are details passed from previous page to this page and at this page.
this is the page for user to pick a date and check for availability.
I'm stuck at the step to convert datetime to unixtime for comparison with database. And also after compare, isit possible to disable the slot button if its not available?

The requirement is to select time by hour, from 9-5, and store the selected datetime and the other information passed from previous page.

Thanks

<?PHP
 session_start();

 $userid = $_SESSION['userid'];
 $cname = $_POST['cname'];
 $cadd = $_POST['cadd'];
 $cphone = $_POST['cphone']

?>
<!DOCTYPE html>

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css" />

<title>Trial </title>

        Reservation Form

      <form method="post" action="datetime.php">

            Select Date

          <input type="datetime-local" step="3600" name="datetime" id="datetime" value=""/>

     Slot

        <input type="button" value="Slot 1" data-role="button" />
 <input type="button" value="Slot 2" data-role="button" />

<input type="submit" value="Check Availability" data-role="button" data-inline="true"/>

<input type="submit" value="Next" data-role="button" data-inline="true"/>

</form>

      Test

```

答:
Sorry, I am little confused with your requirement, but check below solution, use the solution as per your requirement.

MYSQL DATE field format is 'YYYY-MM-DD', ex. '2017-11-14',
In your form user will insert the date, and the form submit, in the PHP script where the form submit, get the date value and convert in the same

```<code>$date = '14.11.2017'; // Get the date from POST
$new_date = date('Y-m-d', strtotime($date));
//echo $new_date;
</code>```

Now check the $new_date in your database. Like "SELECT date_field FROM your_table WHERE date_field = '$new_date'"

Body:
Sorry, I am little confused with your requirement, but check below solution, use the solution as per your requirement.

MYSQL DATE field format is 'YYYY-MM-DD', ex. '2017-11-14',
In your form user will insert the date, and the form submit, in the PHP script where the form submit, get the date value and convert in the same

$date = '14.11.2017'; // Get the date from POST
$new_date = date('Y-m-d', strtotime($date));
//echo $new_date;

Now check the $new_date in your database. Like "SELECT date_field FROM your_table WHERE date_field = '$new_date'"


问:
Microsoft Bot Framework (MBF) - can't get video from Kik channel
I can't get my bot approved on Kik because of the following reason:

Your bot failed to respond to messages of the following types: start-chatting, video

I'll probably fix the start-chatting, but the video part is weird.

In other channels (e.g. Facebook Messenger) my bot intercept the video and can responds to it, but on Kik, it seems like I get no message at all when the user sends a video message.

Anyone familiar with that issue? Any help would be appreciated.
I'm using the Node.Js SDK.

答: I solved it. My bot service is running on Azure, and after 20 minutes of inactivity, the server is becoming idle and the response is delayed in about 15 seconds.</p>


问:
how to append and remove field using class in jquery
I created a form for product sale. admin can add fields for multiple product's click on add button using jquery and can remove fields by clicking on remove button.
I'm trying to append this using div id but this doesn't work. in this image, mark area will append by every clicking on add new row button.

```<code><div class="row" id="dsf">
                        <div class="col-md-2">
                            <select name="p_name" class="form-control" id="p_name">
                                <option value="">-Select Product-</option>
                                @foreach($products as $product)
                                <option value="{{$product->product_id}}">{{$product->name}}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-2">
                            <input type="text" name="p_code" id="p_code" class="form-control" readonly="">
                        </div>
                        <div class="col-md-2">
                            <input type="text" name="unit_pctn" id="unit_pctn" class="form-control" readonly="">
                        </div>
                        <div class="col-md-2">
                            <input type="text" name="u_price" id="u_price" class="form-control" readonly="">
                        </div>
                        <div class="col-md-1">
                            <input type="text" name="ctn" id="ctn" class="form-control">
                        </div>
                        <div class="col-md-1">
                            <input type="text" name="pcs" id ="pcs" class="form-control">
                        </div>
                        <div class="col-md-2">
                            <input type="text" name="t_amt" id="t_amt" class="form-control">
                        </div>
                        <div id="temp"></div>

                    </div>
</code>```

here is jquery part.

```<code><script type="text/javascript">
$(document).ready(function(){
    var elm=$(".dsf");
    $("#addrow").click(function(){
        $("#dsf").append();
    });
});
</code>```

答:
Hope this helps...

 function addRow(tableID) {

 var table = document.getElementById(tableID);

 var rowCount = table.rows.length;
 var row = table.insertRow(rowCount);

 var cell1 = row.insertCell(0);
 var element1 = document.createElement("input");
 element1.type = "checkbox";
 element1.name="chkbox[]";
 cell1.appendChild(element1);

 var cell2 = row.insertCell(1);
 cell2.innerHTML = rowCount + 1;

 var cell3 = row.insertCell(2);
 var element2 = document.createElement("input");
 element2.type = "text";
 element2.name = "txtbox[]";
 cell3.appendChild(element2);

}

function deleteRow(tableID) {
 try {
  var table = document.getElementById(tableID);
  var rowCount = table.rows.length;

  for(var i=0; i<rowCount; i++) {
   var row = table.rows[i];
   var chkbox = row.cells[0].childNodes[0];
   if(null != chkbox && true == chkbox.checked) {
    table.deleteRow(i);
    rowCount--;
    i--;
   }

  }
 }catch(e) {
  alert(e);
 }
}

   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

 <INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />

 <TABLE id="dataTable" width="350px">
  <TR>
   <TD><INPUT type="checkbox" name="chk"/></TD>
   <TD> 1 </TD>
   <TD> <INPUT type="text" /> </TD>
  </TR>
 </TABLE></code>```

Body:
I created a form for product sale. admin can add fields for multiple product's click on add button using jquery and can remove fields by clicking on remove button.
I'm trying to append this using div id but this doesn't work. in this image, mark area will append by every clicking on add new row button.

                            <select name="p_name" class="form-control" id="p_name">
                                <option value="">-Select Product-</option>
                                @foreach($products as $product)
                                <option value="{{$product->product_id}}">{{$product->name}}</option>
                                @endforeach
                            </select>

                            <input type="text" name="p_code" id="p_code" class="form-control" readonly="">

                            <input type="text" name="unit_pctn" id="unit_pctn" class="form-control" readonly="">

                            <input type="text" name="u_price" id="u_price" class="form-control" readonly="">

                            <input type="text" name="ctn" id="ctn" class="form-control">

                            <input type="text" name="pcs" id ="pcs" class="form-control">

                            <input type="text" name="t_amt" id="t_amt" class="form-control">

here is jquery part.

Body:
Hope this helps...

 function addRow(tableID) {

 var table = document.getElementById(tableID);

 var rowCount = table.rows.length;
 var row = table.insertRow(rowCount);

 var cell1 = row.insertCell(0);
 var element1 = document.createElement("input");
 element1.type = "checkbox";
 element1.name="chkbox[]";
 cell1.appendChild(element1);

 var cell2 = row.insertCell(1);
 cell2.innerHTML = rowCount + 1;

 var cell3 = row.insertCell(2);
 var element2 = document.createElement("input");
 element2.type = "text";
 element2.name = "txtbox[]";
 cell3.appendChild(element2);

}

function deleteRow(tableID) {
 try {
  var table = document.getElementById(tableID);
  var rowCount = table.rows.length;

  for(var i=0; i<rowCount; i++) {
   var row = table.rows[i];
   var chkbox = row.cells[0].childNodes[0];
   if(null != chkbox && true == chkbox.checked) {
    table.deleteRow(i);
    rowCount--;
    i--;
   }

  }
 }catch(e) {
  alert(e);
 }
}

<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

 <INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />

 <TABLE id="dataTable" width="350px">
  <TR>
   <TD><INPUT type="checkbox" name="chk"/></TD>
   <TD> 1 </TD>
   <TD> <INPUT type="text" /> </TD>
  </TR>
 </TABLE>


问:
Value types in object stored in heap as well?
I can imagine this question has been asked thousands of times, but I didn't have much luck in finding the answer, plus this is more out of curiosity than need.

Digging into the nuts and bolts of C#, I was wondering since objects are stored in the heap, are the value types within the objects stored in the heap as well or are they placed in the stack?

答: Yes, they're stored as part of the heap. However, it's all an implementation detail, as Eric Lippert has described on multiple occasions. I suggest you read his blog posts about it, this being the most recent one, and these two also being important.</p>