问:
Change description of an SSRS report subscription through PowerShell
I have a PowerShell script and I would like to update descriptions of couple of my SSRS report subscriptions that meets some criteria. I am aware of below method.

```<code>$proxy.ChangeSubscriptionOwner()
</code>```

Likewise do we have any mechanisms to update descriptions as well? Please suggest.

答:
I know this doesn't yet get to your answer but maybe it'll get you partially there. </p>

<p>Here is how you can get all the reports with subscriptions. </p>

```<code>function Get-DataDrivenSubscriptionProperties
{
  param([string] $Subscriptionid,
   [object]$ssrsproxy)
   $ddextensionSettings = $ddDataRetrievalPlan = $ddDescription = $ddactive = $ddstatus = $ddeventtype = $ddmatchdata = $ddparameters = $Null
    $ddOwner = $ssrsproxy.GetDataDrivenSubscriptionProperties($subscriptionid,[ref]$ddextensionSettings,[ref]$ddDataRetrievalPlan,[ref]$ddDescription,[ref]$ddactive,[ref]$ddstatus,[ref]$ddeventtype,[ref]$ddmatchdata,[ref]$ddparameters)
    [PSCustomObject]@{
        'Owner' = $ddOwner
        'extensionSettings' = $ddextensionSettings
        'DataRetrievalPlan' = $ddDataRetrievalPlan
        'Description' = $ddDescription
        'active' = $ddactive
        'status' =$ddstatus
        'eventtype' =$ddeventtype
        'matchdata' = $ddmatchdata
        'parameters' = $ddparameters
      }
}
function Get-SubscriptionProperties
{
  param([string]$Subscriptionid,
  [object]$ssrsproxy)
  $subextensionSettings = $subDataRetrievalPlan = $subDescription = $subactive = $substatus = $subeventtype = $submatchdata = $subparameters = $Null

  $subOwner = $ssrsproxy.GetSubscriptionProperties($subscriptionid,[ref]$subextensionSettings,[ref]$subDescription,[ref]$subactive,[ref]$substatus,[ref]$subeventtype,[ref]$submatchdata,[ref]$subparameters)
      [PSCustomObject]@{
        'Owner' = $subOwner
        'extensionSettings' = $subextensionSettings
        'Description' = $subDescription
        'active' = $subactive
        'status' =$substatus
        'eventtype' =$subeventtype
        'matchdata' = $submatchdata
        'parameters' = $subparameters
      }

}
function Get-Subscriptions
{
  #Returns a nested object with each
  param([object]$ssrsproxy, [string]$site)
  #write-verbose 'Path to where the reports are must be specified to get the subscriptions you want.. Root (/) does not seem to get everything'
  $items = $ssrsproxy.ListChildren($site,$true) | Where-Object{$_.typename -eq 'report'}
  $subscriptions = @()
  foreach($item in $items)
  {
    $subs = $ssrsproxy.ListSubscriptions($item.path)
    $count = $subs.count
    write-verbose "found $($subs.count) subscriptions for $($item.Name)"
    $subprops = @()
    if($subs)
    {
      $s = @()
      foreach($sub in $subs)
      {

        if($sub.isdatadriven -eq 'true')
        {
          $subprops += Get-DataDrivenSubscriptionProperties -subscriptionid $sub.SubscriptionID -ssrsproxy $ssrsproxy
          $sub | add-member -MemberType NoteProperty -Name Properties -value $subprops -TypeName [PSCustomObject]
        }
        else
        {
          $subprops +=   Get-SubscriptionProperties -subscriptionid $sub.SubscriptionID -ssrsproxy $ssrsproxy
          $sub | add-member -MemberType NoteProperty -Name Properties -value $subprops -TypeName [PSCustomObject]
        }

      }

      $item | add-member -MemberType NoteProperty -Name Subscriptions -Value $subs -TypeName [PSCustomObject]
      $item | Add-Member -MemberType NoteProperty -Name 'SubscriptionCount' -Value $count
    }
    else
    {
      $count = 0
    }
  if($count -ne 0)
    {
      $subscriptions += $item
    }
  }
  $subscriptions
}
function New-SubscriptionFile
{
    [CmdletBinding()]
    [Alias()]
    param([psobject]$subscriptionObject, [string]$path)
    if(test-path $path -PathType Leaf)
    {$path = split-path $path}
    foreach($sub in $subscriptionObject)
    {
      $reportName = (($sub.name).split('.'))[0]
      $filename = "$path\$reportName.xml"
      $sub | Export-Clixml -Path $filename -Depth 100
    }
}
</code>```

Body:
I have a PowerShell script and I would like to update descriptions of couple of my SSRS report subscriptions that meets some criteria. I am aware of below method.

$proxy.ChangeSubscriptionOwner()

Likewise do we have any mechanisms to update descriptions as well? Please suggest.

Body:
I know this doesn't yet get to your answer but maybe it'll get you partially there.

Here is how you can get all the reports with subscriptions.

function Get-DataDrivenSubscriptionProperties
{
  param([string] $Subscriptionid,
   [object]$ssrsproxy)
   $ddextensionSettings = $ddDataRetrievalPlan = $ddDescription = $ddactive = $ddstatus = $ddeventtype = $ddmatchdata = $ddparameters = $Null
    $ddOwner = $ssrsproxy.GetDataDrivenSubscriptionProperties($subscriptionid,[ref]$ddextensionSettings,[ref]$ddDataRetrievalPlan,[ref]$ddDescription,[ref]$ddactive,[ref]$ddstatus,[ref]$ddeventtype,[ref]$ddmatchdata,[ref]$ddparameters)
    [PSCustomObject]@{
        'Owner' = $ddOwner
        'extensionSettings' = $ddextensionSettings
        'DataRetrievalPlan' = $ddDataRetrievalPlan
        'Description' = $ddDescription
        'active' = $ddactive
        'status' =$ddstatus
        'eventtype' =$ddeventtype
        'matchdata' = $ddmatchdata
        'parameters' = $ddparameters
      }
}
function Get-SubscriptionProperties
{
  param([string]$Subscriptionid,
  [object]$ssrsproxy)
  $subextensionSettings = $subDataRetrievalPlan = $subDescription = $subactive = $substatus = $subeventtype = $submatchdata = $subparameters = $Null

  $subOwner = $ssrsproxy.GetSubscriptionProperties($subscriptionid,[ref]$subextensionSettings,[ref]$subDescription,[ref]$subactive,[ref]$substatus,[ref]$subeventtype,[ref]$submatchdata,[ref]$subparameters)
      [PSCustomObject]@{
        'Owner' = $subOwner
        'extensionSettings' = $subextensionSettings
        'Description' = $subDescription
        'active' = $subactive
        'status' =$substatus
        'eventtype' =$subeventtype
        'matchdata' = $submatchdata
        'parameters' = $subparameters
      }

}
function Get-Subscriptions
{
  #Returns a nested object with each
  param([object]$ssrsproxy, [string]$site)
  #write-verbose 'Path to where the reports are must be specified to get the subscriptions you want.. Root (/) does not seem to get everything'
  $items = $ssrsproxy.ListChildren($site,$true) | Where-Object{$_.typename -eq 'report'}
  $subscriptions = @()
  foreach($item in $items)
  {
    $subs = $ssrsproxy.ListSubscriptions($item.path)
    $count = $subs.count
    write-verbose "found $($subs.count) subscriptions for $($item.Name)"
    $subprops = @()
    if($subs)
    {
      $s = @()
      foreach($sub in $subs)
      {

        if($sub.isdatadriven -eq 'true')
        {
          $subprops += Get-DataDrivenSubscriptionProperties -subscriptionid $sub.SubscriptionID -ssrsproxy $ssrsproxy
          $sub | add-member -MemberType NoteProperty -Name Properties -value $subprops -TypeName [PSCustomObject]
        }
        else
        {
          $subprops +=   Get-SubscriptionProperties -subscriptionid $sub.SubscriptionID -ssrsproxy $ssrsproxy
          $sub | add-member -MemberType NoteProperty -Name Properties -value $subprops -TypeName [PSCustomObject]
        }

      }

      $item | add-member -MemberType NoteProperty -Name Subscriptions -Value $subs -TypeName [PSCustomObject]
      $item | Add-Member -MemberType NoteProperty -Name 'SubscriptionCount' -Value $count
    }
    else
    {
      $count = 0
    }
  if($count -ne 0)
    {
      $subscriptions += $item
    }
  }
  $subscriptions
}
function New-SubscriptionFile
{
    [CmdletBinding()]
    [Alias()]
    param([psobject]$subscriptionObject, [string]$path)
    if(test-path $path -PathType Leaf)
    {$path = split-path $path}
    foreach($sub in $subscriptionObject)
    {
      $reportName = (($sub.name).split('.'))[0]
      $filename = "$path\$reportName.xml"
      $sub | Export-Clixml -Path $filename -Depth 100
    }
}


来源: stackexchange

问:
Callrail API HTTP GET request with headers
I can throw this into a linux terminal and get results.

```<code>curl -H "Authorization: Token token={api_token}" \
 -X GET \
 "https://api.callrail.com/v2/a/{account_id}/calls.json?company_id={companyId}"
</code>```

Here is what I have:

```<code>var myToken = "fakeToken1234";

$.ajax
    ({
        type: "GET",
        url: "https://api.callrail.com/v2/a/{accountId}/calls.json?company_id={companyId}",
        dataType: 'json',
        beforeSend: function (xhr) { xhr.setRequestHeader('Authorization:', + myToken ); }
    });
</code>```

Per CallRail Documentation I'm supposed to pass the api_token into HTTP Authorization header. I get a 401 Unauthorized message.

I think my syntax is off but can't pin it down. Any help?

答:
My problem was I didn't understand the syntax that CallRail wanted in the header.

This solved it: headers: { "Authorization": 'Token token=' + myToken },

```<code>var myToken = "token1234";
var accountId = "Id1234";
var companyId = "Id1234";

$.ajax
    ({
        type: "GET",
        url: "https://api.callrail.com/v2/a/" + accountId + "/calls/timeseries.json?company_id=" + companyId + "",
        dataType: 'json',
        headers: { "Authorization": 'Token token=' + myToken },
            success: function (result) {
                console.log(result);
            },
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I can throw this into a linux terminal and get results.

curl -H "Authorization: Token token={api_token}" \
 -X GET \
 "https://api.callrail.com/v2/a/{account_id}/calls.json?company_id={companyId}"

Here is what I have:

var myToken = "fakeToken1234";

$.ajax
    ({
        type: "GET",
        url: "https://api.callrail.com/v2/a/{accountId}/calls.json?company_id={companyId}",
        dataType: 'json',
        beforeSend: function (xhr) { xhr.setRequestHeader('Authorization:', + myToken ); }
    });

Per CallRail Documentation I'm supposed to pass the api_token into HTTP Authorization header. I get a 401 Unauthorized message.

I think my syntax is off but can't pin it down. Any help?

Body:
My problem was I didn't understand the syntax that CallRail wanted in the header.

This solved it: headers: { "Authorization": 'Token token=' + myToken },

var myToken = "token1234";
var accountId = "Id1234";
var companyId = "Id1234";

$.ajax
    ({
        type: "GET",
        url: "https://api.callrail.com/v2/a/" + accountId + "/calls/timeseries.json?company_id=" + companyId + "",
        dataType: 'json',
        headers: { "Authorization": 'Token token=' + myToken },
            success: function (result) {
                console.log(result);
            },
    });


问:
Why doesn't this code for a navigation drawer work?
Following is some code to create a navigation drawer. The problem is that the drawer doesn't appear properly. The drawer is visible from the start of the activity but only partially, and it doesn't slide in and out from the side. It's just stationary in one place. What's wrong here?

NOTE: I've removed the Action Bar by writing NoActionBar in styles.xml

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<
android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.nirvan.navigationexample3.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"></LinearLayout>

   <
   android.support.design.widget.NavigationView
   android:layout_width="wrap_content"
   android:layout_height="match_parent"
   android:id="@+id/nv"
   >

   <ListView
       android:layout_width="200dp"
       android:layout_height="match_parent"
       android:id="@+id/listView"></ListView>

   </android.support.design.widget.NavigationView>
</code>```

mainActivity.java

```<code>package com.example.nirvan.navigationexample3;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity
{

@Override
protected void onCreate(Bundle savedInstanceState)
   {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ListView ls=(ListView)findViewById(R.id.listView);
    String[] values=
    {"one","two","three","four","five","six","seven","eight"};

    ArrayAdapter<String> adapter=new ArrayAdapter(this,
    R.layout.item,values);
    ls.setAdapter(adapter);
   }
 }
</code>```

item.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

</TextView>
</code>```

答:
Edit your layout file like this:</p>

```<code>    <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="false">

         <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

      <include layout="@layout/nav_header_main"
                    android:id="@+id/my"/>
                <ListView

                    android:layout_weight="7"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:id="@+id/list_view_inside_nav"></ListView>
            </LinearLayout>
        </android.support.design.widget.NavigationView>

    </android.support.v4.widget.DrawerLayout>
</code>```

Body:
Following is some code to create a navigation drawer. The problem is that the drawer doesn't appear properly. The drawer is visible from the start of the activity but only partially, and it doesn't slide in and out from the side. It's just stationary in one place. What's wrong here?

NOTE: I've removed the Action Bar by writing NoActionBar in styles.xml

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<
android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.nirvan.navigationexample3.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"></LinearLayout>

   <
   android.support.design.widget.NavigationView
   android:layout_width="wrap_content"
   android:layout_height="match_parent"
   android:id="@+id/nv"
   >

   <ListView
       android:layout_width="200dp"
       android:layout_height="match_parent"
       android:id="@+id/listView"></ListView>

   </android.support.design.widget.NavigationView>

mainActivity.java

package com.example.nirvan.navigationexample3;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity
{

@Override
protected void onCreate(Bundle savedInstanceState)
   {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ListView ls=(ListView)findViewById(R.id.listView);
    String[] values=
    {"one","two","three","four","five","six","seven","eight"};

    ArrayAdapter<String> adapter=new ArrayAdapter(this,
    R.layout.item,values);
    ls.setAdapter(adapter);
   }
 }

item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

</TextView>

Body:
Edit your layout file like this:

    <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="false">

         <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

      <include layout="@layout/nav_header_main"
                    android:id="@+id/my"/>
                <ListView

                    android:layout_weight="7"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:id="@+id/list_view_inside_nav"></ListView>
            </LinearLayout>
        </android.support.design.widget.NavigationView>

    </android.support.v4.widget.DrawerLayout>


问:
JSP form input maxlength not working on number type
I'm using jsp <form:input> tag for input the data on jsp form. The requirement is to limit length of input field and be able to input only numbers.

The following tag works for limiting length of the input string, however I'm able to input any symbols here:

```<code><form:input path="somePath" code="someCode" maxlength="3"/>
</code>```

And when I use type number, maxlength attribute doesn't work and there is no limit on input field, however I'm limited to number only:

<form:input path="somePath" code="someCode" maxlength="3" type="number"/>

Is there a way to have input field limited in maximum length and to numbers only? Can't figure out why the line above doesn't work.

答:
Thanks to the answer here for HTML5, I was able to solve this on JSP page in the following way:

```<code><form:input maxlength="3" type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
</code>```

As of the type number - it is supported by <form:input> tag, however there is no way to limit it in length.

Body:
I'm using jsp <form:input> tag for input the data on jsp form. The requirement is to limit length of input field and be able to input only numbers.

The following tag works for limiting length of the input string, however I'm able to input any symbols here:

<form:input path="somePath" code="someCode" maxlength="3"/>

And when I use type number, maxlength attribute doesn't work and there is no limit on input field, however I'm limited to number only:

<form:input path="somePath" code="someCode" maxlength="3" type="number"/>

Is there a way to have input field limited in maximum length and to numbers only? Can't figure out why the line above doesn't work.

Body:
Thanks to the answer here for HTML5, I was able to solve this on JSP page in the following way:

<form:input maxlength="3" type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>

As of the type number - it is supported by <form:input> tag, however there is no way to limit it in length.


问:
Storing 2 same id of post table with different language into database
I'm building a multi language website. In this case just 2 languages, it's Indonesian and English using Laravel.
I have posts table, it will store id of each post and post_translations table is to store local, title, and description of post.
I got the problem when storing data into database. I don't have any idea how to store post without inc the id except I've added 2 same post with Indonesian and English.

This is the result (wrong)

posts table

```<code>id
1
2
</code>```

post_translations table

```<code>id  post_id  locale   title
1     1      en       fisrt post
2     2      id       post yang pertama
</code>```

Expexted result

posts table

```<code>id
1
</code>```

post_translations table

```<code>id  post_id  locale   title
1     1      en       fisrt post
2     1      id       post yang pertama
</code>```

PostController

```<code>  public function store(Request $request) {
    $this->validate($request, [
        'title' => 'required',
        'slug' => 'required',
        'content' => 'required'
    ]);

    $post = new Post;

    $post->title = $request->title;
    $post->slug = $request->slug;
    $post->content = $request->content;

    $post->save();
    return redirect()->route('post.index');
}
</code>```

答:
I think you should change your tables  strucuture:

posts : id, slug.

post_translations : id, post_id, locale, title, content

Also add relation to your Post model:

```<code>public function translations()
{
    return $this->hasMany(PostTranslation::class, 'post_id');
}
</code>```

And update your controller:

```<code>$post = new Post;

$post->slug = $request->slug;
$post->save();

$post->translations()->create([
    'locale' => 'en', //or grab it from $request
    'title' => $request->title,
    'content' => $request->content
])
</code>```

It will create your post and add translation to it

Body:
I'm building a multi language website. In this case just 2 languages, it's Indonesian and English using Laravel.
I have posts table, it will store id of each post and post_translations table is to store local, title, and description of post.
I got the problem when storing data into database. I don't have any idea how to store post without inc the id except I've added 2 same post with Indonesian and English.

This is the result (wrong)

posts table

id
1
2

post_translations table

id  post_id  locale   title
1     1      en       fisrt post
2     2      id       post yang pertama

Expexted result

posts table

id
1

post_translations table

id  post_id  locale   title
1     1      en       fisrt post
2     1      id       post yang pertama

PostController

  public function store(Request $request) {
    $this->validate($request, [
        'title' => 'required',
        'slug' => 'required',
        'content' => 'required'
    ]);

    $post = new Post;

    $post->title = $request->title;
    $post->slug = $request->slug;
    $post->content = $request->content;

    $post->save();
    return redirect()->route('post.index');
}

Body:
I think you should change your tables  strucuture:

posts : id, slug.

post_translations : id, post_id, locale, title, content

Also add relation to your Post model:

public function translations()
{
    return $this->hasMany(PostTranslation::class, 'post_id');
}

And update your controller:

$post = new Post;

$post->slug = $request->slug;
$post->save();

$post->translations()->create([
    'locale' => 'en', //or grab it from $request
    'title' => $request->title,
    'content' => $request->content
])

It will create your post and add translation to it


问:
Store Min, Max,Avg values in "single" variable
I have many variable like:

```<code>int signalX_Max;
int signalX_Min;
int signalX_Avg;
int signalY_Max;
int signalY_Min;
int signalY_Avg;
int signalZ_Min;
int signalZ_Max;
int signalZ_Avg;
</code>```

How can I store/declare this variables to to use it in code like signal.yMin, signal.yMax, signal.yAvg, signal.xMin, signal.xMax, signal.xAvg etc. or signal['xMin'], signal['xMax'],signal['xAvg'] etc

答:
You could create a class and then have the above as properties. Then create an instance of it. You could access with the dot operator

```<code> public class Signal
        {
            int signalX_Max  { get; set; }
            int signalX_Min { get; set; }
            int signalX_Avg { get; set; }
            int signalY_Max { get; set; }
            int signalY_Min { get; set; }
            int signalY_Avg { get; set; }
            int signalZ_Min { get; set; }
            int signalZ_Max { get; set; }
            int signalZ_Avg { get; set; }

        }
</code>```

Then you could do ,

```<code>   Signal signal = new Signal();
   signal.signalX_Avg = ....
</code>```

Body:
I have many variable like:

int signalX_Max;
int signalX_Min;
int signalX_Avg;
int signalY_Max;
int signalY_Min;
int signalY_Avg;
int signalZ_Min;
int signalZ_Max;
int signalZ_Avg;

How can I store/declare this variables to to use it in code like signal.yMin, signal.yMax, signal.yAvg, signal.xMin, signal.xMax, signal.xAvg etc. or signal['xMin'], signal['xMax'],signal['xAvg'] etc

Body:
You could create a class and then have the above as properties. Then create an instance of it. You could access with the dot operator

 public class Signal
        {
            int signalX_Max  { get; set; }
            int signalX_Min { get; set; }
            int signalX_Avg { get; set; }
            int signalY_Max { get; set; }
            int signalY_Min { get; set; }
            int signalY_Avg { get; set; }
            int signalZ_Min { get; set; }
            int signalZ_Max { get; set; }
            int signalZ_Avg { get; set; }

        }

Then you could do ,

   Signal signal = new Signal();
   signal.signalX_Avg = ....


问:
Protocol conforming to Sequence protocol while eliminating generic constraint issue
Attempting to create a protocol that is used to create different nodes within a tree. A simplified version is:

```<code>protocol NodeElement {
    var children: [NodeElement] { get }
}
</code>```

This protocol can be used to create structs that can be used to create nodes into a tree.

```<code>struct TextNode: NodeElement {
    var text: String
    var children: [NodeElement]
}

struct NumberNode: NodeElement {
    var number: Int
    var children: [NodeElement]
}
</code>```

and with these structs, a Tree can be created containing varying types.

let root = TextNode(text: "Hello", children: [NumberNode(...), ...])

I would like NodeElement to conform to the Sequence Protocol to allow for pre-order tree traversal within a for...in loop.

This can be done through

```<code>protocol NodeElement: Sequence { ... }

extension NodeElement {
    func makeIterator() -> AnyIterator<NodeElement> {
        var stack: [NodeElement] = [self]

        return AnyIterator {
            if let next = stack.first {
                stack.remove(at: 0)
                stack.insert(contentsOf: next.content, at: 0)
                return next
            }
            return nil
        }
    }
}
</code>```

If this is done, the following ERROR occurs:

```<code>error: protocol 'NodeElement' can only be used as a generic constraint
because it has Self or associated type requirements

var content: [NodeElement] { get }
              ^
</code>```

This occurs even when I believe I am fully conforming to the Sequence protocol.

Without making a NodeElement a struct and having all nodes inherit from it, is there any way to make this work?

答:
NodeElement has a reference to itself so it cannot be used to define a concrete type.  You will not be able to make it a Sequence because of this.

You could however achieve something similar by simply adding a computed variable to the protocol instead of making it a sequence per se.

for Example:

```<code>extension NodeElement
{
    var treeNodes : AnyIterator<NodeElement>
    {
        var stack: [NodeElement] = [self]

        return AnyIterator {
            if let next = stack.first {
                stack.remove(at: 0)
                stack.insert(contentsOf: next.children, at: 0)
                return next
            }
            return nil
        }
    }
}
</code>```

You will then be able to use your protocol in a for ... in loop using that variable:

```<code>for node in root.treeNodes
{
   ...
}
</code>```

Body:
Attempting to create a protocol that is used to create different nodes within a tree. A simplified version is:

protocol NodeElement {
    var children: [NodeElement] { get }
}

This protocol can be used to create structs that can be used to create nodes into a tree.

struct TextNode: NodeElement {
    var text: String
    var children: [NodeElement]
}

struct NumberNode: NodeElement {
    var number: Int
    var children: [NodeElement]
}

and with these structs, a Tree can be created containing varying types.

let root = TextNode(text: "Hello", children: [NumberNode(...), ...])

I would like NodeElement to conform to the Sequence Protocol to allow for pre-order tree traversal within a for...in loop.

This can be done through

protocol NodeElement: Sequence { ... }

extension NodeElement {
    func makeIterator() -> AnyIterator<NodeElement> {
        var stack: [NodeElement] = [self]

        return AnyIterator {
            if let next = stack.first {
                stack.remove(at: 0)
                stack.insert(contentsOf: next.content, at: 0)
                return next
            }
            return nil
        }
    }
}

If this is done, the following ERROR occurs:

error: protocol 'NodeElement' can only be used as a generic constraint
because it has Self or associated type requirements

var content: [NodeElement] { get }
              ^

This occurs even when I believe I am fully conforming to the Sequence protocol.

Without making a NodeElement a struct and having all nodes inherit from it, is there any way to make this work?

Body:
NodeElement has a reference to itself so it cannot be used to define a concrete type.  You will not be able to make it a Sequence because of this.

You could however achieve something similar by simply adding a computed variable to the protocol instead of making it a sequence per se.

for Example:

extension NodeElement
{
    var treeNodes : AnyIterator<NodeElement>
    {
        var stack: [NodeElement] = [self]

        return AnyIterator {
            if let next = stack.first {
                stack.remove(at: 0)
                stack.insert(contentsOf: next.children, at: 0)
                return next
            }
            return nil
        }
    }
}

You will then be able to use your protocol in a for ... in loop using that variable:

for node in root.treeNodes
{
   ...
}


问:
IE11 on Win7, console seems broken
I upgraded my Win7 test box to use IE11, the released version.

When using the developer tools (F12), I switch to the console.

At the bottom is the text box where you can enter commands and have the console execute the javascript command....

Except it doesn't.  All that happens is the console window prints the command, as if it was a piece of text.

Did I switch to a different console mode on accident?

答:
I was having this problem also, and found that updating IE fixed it as this post describes:
Debugger not working in IE 11 F12 developer tools</p>

Title: IE11 on Win7, console seems broken


问:
How to Request Specific Object From JSON URL with C# WebClient
Following code returns entire JSON objects but I need to Filter to some specific Object, for example I need to get only the "layers" or tiltle can you please let me know how to do this is C#?

Do I have to create an HttpWebRequestobject for this? if so where should I pass the requested data?

```<code>using (WebClient wc = new WebClient())
   {
    var json = wc.DownloadString("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson");
    Console.WriteLine(json);
   }
</code>```

I already tried this but it is also returning everything

```<code>class Program
{
    private const string URL = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson";
    private const string DATA = @"{{""layers"":""Layers""}}";
    static void Main(string[] args)
    {

       CreateObject();

    }
    private static void CreateObject()
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = DATA.Length;
        using (Stream webStream = request.GetRequestStream())
        using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
        {
            requestWriter.Write(DATA);
        }

        try
        {
            WebResponse webResponse = request.GetResponse();
            using (Stream webStream = webResponse.GetResponseStream())
            {
                if (webStream != null)
                {
                    using (StreamReader responseReader = new StreamReader(webStream))
                    {
                        string response = responseReader.ReadToEnd();
                        Console.WriteLine(response);
                        Console.ReadLine();
                    }
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("-----------------");
            Console.WriteLine(e.Message);
            Console.ReadLine();
        }

    }

}
</code>```

答:
If you need the info related to the layers array object then you can use following code

```<code> using (var wc = new WebClient())
 {
     string json = wc.DownloadString("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson");
     dynamic data = Json.Decode(json);
     Console.WriteLine(data.layers[0].id);
     Console.WriteLine(data.layers[0].name);
     Console.WriteLine(data.documentInfo.Title);
 }
</code>```

Body:
Following code returns entire JSON objects but I need to Filter to some specific Object, for example I need to get only the "layers" or tiltle can you please let me know how to do this is C#?

Do I have to create an HttpWebRequestobject for this? if so where should I pass the requested data?

using (WebClient wc = new WebClient())
   {
    var json = wc.DownloadString("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson");
    Console.WriteLine(json);
   }

I already tried this but it is also returning everything

class Program
{
    private const string URL = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson";
    private const string DATA = @"{{""layers"":""Layers""}}";
    static void Main(string[] args)
    {

       CreateObject();

    }
    private static void CreateObject()
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = DATA.Length;
        using (Stream webStream = request.GetRequestStream())
        using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
        {
            requestWriter.Write(DATA);
        }

        try
        {
            WebResponse webResponse = request.GetResponse();
            using (Stream webStream = webResponse.GetResponseStream())
            {
                if (webStream != null)
                {
                    using (StreamReader responseReader = new StreamReader(webStream))
                    {
                        string response = responseReader.ReadToEnd();
                        Console.WriteLine(response);
                        Console.ReadLine();
                    }
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("-----------------");
            Console.WriteLine(e.Message);
            Console.ReadLine();
        }

    }

}

Body:
If you need the info related to the layers array object then you can use following code

 using (var wc = new WebClient())
 {
     string json = wc.DownloadString("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson");
     dynamic data = Json.Decode(json);
     Console.WriteLine(data.layers[0].id);
     Console.WriteLine(data.layers[0].name);
     Console.WriteLine(data.documentInfo.Title);
 }


问:
How to map value from one observable to pair with depending observable value?
Suppose I have two observables:

Observable<MainInfo> mainInfoObs and

Observable<AdditionalInfo> additionalInfoObs(MainInfo mainInfo) function.

I want somehow to combine these observables to receive Pair<MainInfo, AdditionalInfo>

I can't just use zip, because additionalInfoObs depends on mainInfo.

So I want to do something like

```<code>mainInfoObs
    .map(mainInfo->new Pair(mainInfo,
                    getAdditionalInfo(mainInfo).toBlocking().last()
                    )
        )
</code>```

But that blocks and hangs.

Please help me - how to combine observables as I want?

答:
It turned out, that flatMap has a variant with 2 arguments, which is what I need.
Here is my solution with flatmap:</p>

```<code>mainInfoObs.flatMap(mainInfo->getAdditionalInfo(mainInfo), Pair::new)
</code>```

Body:
Suppose I have two observables:

Observable<MainInfo> mainInfoObs and

Observable<AdditionalInfo> additionalInfoObs(MainInfo mainInfo) function.

I want somehow to combine these observables to receive Pair<MainInfo, AdditionalInfo>

I can't just use zip, because additionalInfoObs depends on mainInfo.

So I want to do something like

mainInfoObs
    .map(mainInfo->new Pair(mainInfo,
                    getAdditionalInfo(mainInfo).toBlocking().last()
                    )
        )

But that blocks and hangs.

Please help me - how to combine observables as I want?

Body:
It turned out, that flatMap has a variant with 2 arguments, which is what I need.
Here is my solution with flatmap:

mainInfoObs.flatMap(mainInfo->getAdditionalInfo(mainInfo), Pair::new)


问:
JPA The state field path cannot be resolved to a valid type
I need assistance in troubleshooting a relationship / query with EclipseLink 2.5.x provider.

The relationship from ThreePhaseMotorInput to ValidationMessage  is supposed to be a uni-directional OneToMany, i.e. each motor can have 0..n messages and in Java object graph ValidationMessage does not have a reference back to ThreePhaseMotorInput.

I am getting an error that JPA can't find the attributes that are part of the ValidationMessage class when accessed via ThreePhaseMotor.  (See error text below)

Thanks for thinking about my question!

Query

```<code>select msg.validationMsg, COUNT(m.id) from ThreePhaseMotorInput AS m JOIN m.valMessages AS msg GROUP BY msg.validationMsg
</code>```

Error

```<code> org.eclipse.persistence.exceptions.JPQLException:
Exception Description: Problem compiling [select msg.validationMsg, COUNT(m.id) from ThreePhaseMotorInput AS m JOIN m.valMessages AS msg GROUP BY msg.validationMsg].
[7, 24] The state field path 'msg.validationMsg' cannot be resolved to a valid type.
[71, 84] The collection-valued path 'm.valMessages' cannot be resolved to a valid association field.
[119, 136] The state field path 'msg.validationMsg' cannot be resolved to a valid type.
</code>```

ThreePhaseMotorInput class

```<code>@Entity
@Table(name = "three_phase_motor_input")
public class ThreePhaseMotorInput implements IThreePhaseMotorInput, Serializable {
    private static final long serialVersionUID = 8084370807289186987L;
    @Transient
    private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Version
    private Integer version;
    private Integer status;
    @Transient
    private Integer numMessages;

    @OneToOne(cascade = CascadeType.ALL, optional = true, targetEntity = UnapprovedThreePhaseMotor.class)
    @JoinColumn(name = "unapproved_id")
    private IThreePhaseMotor unapprovedMotor;

    @OneToOne(cascade = CascadeType.ALL, optional = true, targetEntity = ApprovedThreePhaseMotor.class)
    @JoinColumn(name = "approved_id")
    private IThreePhaseMotor approvedMotor;

    @OneToMany(orphanRemoval = true, cascade = CascadeType  .ALL, fetch = FetchType.LAZY, targetEntity = ValidationMessage.class)
    @JoinColumn(name = "input_id", referencedColumnName = "id", nullable = false)
    @OrderColumn(name = "idx")
    private List<IValidationMessage> valMessages;
</code>```

ValidationMessage class

```<code>@Entity
@Table(name = "validation_message")
public class ValidationMessage implements Serializable, IValidationMessage {
    private static final long serialVersionUID = 8765213112015434057L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "record_id")
    private Long recordId;
    @Column(name = "field_name")
    private String fieldName;
    @Column(name = "validation_msg")
    private String validationMsg;
    private Integer status;
    @Column(name = "fail_field")
    private String failField;
    @Column(name = "error_source")
    private Integer errorSource;
</code>```

答:
you should use JOINs if you want to jump to another entity's properties. try the following JPQL query </p>

```<code>select m, COUNT(msg) from ThreePhaseMotorInput AS m LEFT JOIN m.valMessages AS msg GROUP BY msg.validationMsg
</code>```

Body:
I need assistance in troubleshooting a relationship / query with EclipseLink 2.5.x provider.

The relationship from ThreePhaseMotorInput to ValidationMessage  is supposed to be a uni-directional OneToMany, i.e. each motor can have 0..n messages and in Java object graph ValidationMessage does not have a reference back to ThreePhaseMotorInput.

I am getting an error that JPA can't find the attributes that are part of the ValidationMessage class when accessed via ThreePhaseMotor.  (See error text below)

Thanks for thinking about my question!

Query

select msg.validationMsg, COUNT(m.id) from ThreePhaseMotorInput AS m JOIN m.valMessages AS msg GROUP BY msg.validationMsg

Error

 org.eclipse.persistence.exceptions.JPQLException:
Exception Description: Problem compiling [select msg.validationMsg, COUNT(m.id) from ThreePhaseMotorInput AS m JOIN m.valMessages AS msg GROUP BY msg.validationMsg].
[7, 24] The state field path 'msg.validationMsg' cannot be resolved to a valid type.
[71, 84] The collection-valued path 'm.valMessages' cannot be resolved to a valid association field.
[119, 136] The state field path 'msg.validationMsg' cannot be resolved to a valid type.

ThreePhaseMotorInput class

@Entity
@Table(name = "three_phase_motor_input")
public class ThreePhaseMotorInput implements IThreePhaseMotorInput, Serializable {
    private static final long serialVersionUID = 8084370807289186987L;
    @Transient
    private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Version
    private Integer version;
    private Integer status;
    @Transient
    private Integer numMessages;

    @OneToOne(cascade = CascadeType.ALL, optional = true, targetEntity = UnapprovedThreePhaseMotor.class)
    @JoinColumn(name = "unapproved_id")
    private IThreePhaseMotor unapprovedMotor;

    @OneToOne(cascade = CascadeType.ALL, optional = true, targetEntity = ApprovedThreePhaseMotor.class)
    @JoinColumn(name = "approved_id")
    private IThreePhaseMotor approvedMotor;

    @OneToMany(orphanRemoval = true, cascade = CascadeType  .ALL, fetch = FetchType.LAZY, targetEntity = ValidationMessage.class)
    @JoinColumn(name = "input_id", referencedColumnName = "id", nullable = false)
    @OrderColumn(name = "idx")
    private List<IValidationMessage> valMessages;

ValidationMessage class

@Entity
@Table(name = "validation_message")
public class ValidationMessage implements Serializable, IValidationMessage {
    private static final long serialVersionUID = 8765213112015434057L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "record_id")
    private Long recordId;
    @Column(name = "field_name")
    private String fieldName;
    @Column(name = "validation_msg")
    private String validationMsg;
    private Integer status;
    @Column(name = "fail_field")
    private String failField;
    @Column(name = "error_source")
    private Integer errorSource;

Body:
you should use JOINs if you want to jump to another entity's properties. try the following JPQL query

select m, COUNT(msg) from ThreePhaseMotorInput AS m LEFT JOIN m.valMessages AS msg GROUP BY msg.validationMsg


问:
C linked list won't change when I push data onto an initialised stack
I'm trying to implement a stack using a linked list in C but I am getting segfaults whenever I try to call the value after I push a new one onto the stack. I know this is happening because the program still says the stack is null even if I add to it. For some reason the changes that I make in the push don't stay when the function terminates and I can't figure out why.

Here's my code for the stack struct, initialization, and push:

```<code>typedef struct stack
{
    int value;
    struct stack * next;
} * stack_T;

stack_T
new_stack()
{
    return NULL;
}

int
push_stack(stack_T s, int data)
{
    stack_T new = malloc(sizeof(stack_T));
    new = s;
    if (s == NULL)
    {
        s = malloc(sizeof(stack_T));
        if (s == NULL)
            return 1;
    }
    s->value = data;
    s->next = new;
    return 0;
}
</code>```

EDIT: Thanks for the help but I forgot to mention that the push has to be done with exactly those parameters, it's part of an assignment. I'm not looking for how to do it but rather what I'm doing wrong. I know that I can emulate pass by reference but as I said it has to be:

```<code>int push_stack(stack_T s, int data)
</code>```

I've made structs before with this style and had functions that just take them as a parameter and changes stay but they won't in this case and I have no idea why.

答:
It looks like you haven't labeled s as a double pointer. It looks like you're attempting to push into the front of the linked list. What you need is to pass in double pointer of the reference to the head of the stack in order to change the address value stored at the memory. This way you would always have reference the top of the stack.

```<code>int
push_stack(stack_T **s, int data)
{
    stack_T *new = malloc(sizeof(stack_T));
    if (new == NULL)
        return (1);
    if (s == NULL)
    {
        free(new);
        return (1);
    }
    new->value = data;
    new->next = *s;
    *s = new;
    return 0;
}
</code>```

I would have to see how your main function is being called that would result in the segfault. However, it does seem that you don't have the proper reference to the top of the stack. Also, I don't quite understand why you are malloc out space for two nodes. Malloc returns a pointer that is being claimed by the size that you've designated.

what you wrote here:

```<code>stack_T new = malloc(sizeof(stack_T));
new = s;
if (s == NULL)
    {
        s = malloc(sizeof(stack_T));
        if (s == NULL)
            return 1;
    }
</code>```

Will never be met with NULL is a a type of void pointer and s as you assigned it is not of a pointer type, so you are attempting to store a variable of the 12 bytes when malloc returns a pointer of 8 bytes.

Also a tip is that you can compile with gcc -g and use valgrind to determine the line in which the segfault is occuring

Body:
I'm trying to implement a stack using a linked list in C but I am getting segfaults whenever I try to call the value after I push a new one onto the stack. I know this is happening because the program still says the stack is null even if I add to it. For some reason the changes that I make in the push don't stay when the function terminates and I can't figure out why.

Here's my code for the stack struct, initialization, and push:

typedef struct stack
{
    int value;
    struct stack * next;
} * stack_T;

stack_T
new_stack()
{
    return NULL;
}

int
push_stack(stack_T s, int data)
{
    stack_T new = malloc(sizeof(stack_T));
    new = s;
    if (s == NULL)
    {
        s = malloc(sizeof(stack_T));
        if (s == NULL)
            return 1;
    }
    s->value = data;
    s->next = new;
    return 0;
}

EDIT: Thanks for the help but I forgot to mention that the push has to be done with exactly those parameters, it's part of an assignment. I'm not looking for how to do it but rather what I'm doing wrong. I know that I can emulate pass by reference but as I said it has to be:

int push_stack(stack_T s, int data)

I've made structs before with this style and had functions that just take them as a parameter and changes stay but they won't in this case and I have no idea why.

Body:
It looks like you haven't labeled s as a double pointer. It looks like you're attempting to push into the front of the linked list. What you need is to pass in double pointer of the reference to the head of the stack in order to change the address value stored at the memory. This way you would always have reference the top of the stack.

int
push_stack(stack_T **s, int data)
{
    stack_T *new = malloc(sizeof(stack_T));
    if (new == NULL)
        return (1);
    if (s == NULL)
    {
        free(new);
        return (1);
    }
    new->value = data;
    new->next = *s;
    *s = new;
    return 0;
}

I would have to see how your main function is being called that would result in the segfault. However, it does seem that you don't have the proper reference to the top of the stack. Also, I don't quite understand why you are malloc out space for two nodes. Malloc returns a pointer that is being claimed by the size that you've designated.

what you wrote here:

stack_T new = malloc(sizeof(stack_T));
new = s;
if (s == NULL)
    {
        s = malloc(sizeof(stack_T));
        if (s == NULL)
            return 1;
    }

Will never be met with NULL is a a type of void pointer and s as you assigned it is not of a pointer type, so you are attempting to store a variable of the 12 bytes when malloc returns a pointer of 8 bytes.

Also a tip is that you can compile with gcc -g and use valgrind to determine the line in which the segfault is occuring


问:
Embedding SVGs into PDFs with embedded fonts
I want to embed an SVG image into a PDF, and have the font families specified in the SVG text elements render using the correct fonts.

The fonts I am using are the 'Lato' TTF fonts.

Here is the code I have used to convert the fonts to TCPDF's "native format":

```<code>$variants = [
    'Black',
    'BlackItalic',
    'Bold',
    'BoldItalic',
    'Hairline',
    'HairlineItalic',
    'Heavy',
    'HeavyItalic',
    'Italic',
    'Light',
    'LightItalic',
    'Medium',
    'MediumItalic',
    'Regular',
    'Semibold',
    'SemiboldItalic',
    'Thin',
    'ThinItalic',
];

foreach ($variants as $variant) {
    \TCPDF_FONTS::addTTFfont(
        '/var/www/fonts/Lato-' . $variant . '.ttf',
        '',
        '',
        32,
        '/var/www/fonts/output/'
    );
}
</code>```

And here is the code I've used to generate a test PDF with an embedded SVG:

```<code>$svg_content = '<svg width="600px" height="800px">';
foreach ($variants as $key => $variant) {
    $svg_content .= '<text x="30" y="' . ( 30 * ( $key + 1 ) ) . '" fill="#ED6E46" font-size="20" font-family="\'Lato-' . $variant . '\'" text-anchor="start">The quick brown fox jumped over the lazy dog (' . $variant . ').</text>';
}
$svg_content .= '</svg>';

$pdf = new TCPDF();

$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->SetMargins(0, 0, -1, true);
$pdf->SetAutoPageBreak(false, 0);

$pdf->AddPage();

$pdf->AddFont('Lato-Black', '', '/var/www/fonts/output/latoblack.php');

$pdf->ImageSVG('@' . $svg_content, 0, 0, 300, 300, '', $align='', $palign='C', $border=0, false);

$pdf->Output(
    preg_replace('/[^A-Za-z0-9]/', '', $influencer->getName()) . '.pdf',
    'I'
);
</code>```

The result I get is that all the text is rendered in what I assume is Helvetica:

If I add a line just before the call to ImageSVG() like this:

```<code>$pdf->SetFont('Lato-Black', '', null, '/var/www/fonts/output/latoblack.php');
</code>```

Then all the text is rendered in Lato-Black:

It seems to me that the fonts are being embedded in the PDF fine, but the SetFont obviously sets the current font for subsequent PDF text elements, and the text elements within the SVG image render using this font.

My desired behaviour is that the font-family attributes defined on the SVG text elements are honoured within the PDF, so that each line renders using the font variant mentioned in the brackets at the end of the line.

How can I do this?

答:
You could start with the following code and work backwards incorporating your changes.

To be clear I'm not specifically advocating this as the way to do it, only that this is one way that works and so should help as a starting point.

Font Converter:

```<code>$variants = [
    'Black',
    'BlackItalic',
    'Bold',
    'BoldItalic',
    'Hairline',
    'HairlineItalic',
    'Heavy',
    'HeavyItalic',
    'Italic',
    'Light',
    'LightItalic',
    'Medium',
    'MediumItalic',
    'Regular',
    'Semibold',
    'SemiboldItalic',
    'Thin',
    'ThinItalic',
];

foreach ($variants as $variant) {
    \TCPDF_FONTS::addTTFfont(dirname(__FILE__) . '/fonts/Lato-' . $variant . '.ttf', 'TrueTypeUnicode', '', 96);
}

echo 'Done!';
</code>```

This puts the .php, .z and .ctg.z files within /tecnickcom/tcpdf/fonts.

PDF Generator:

Note the different font-family names in the $variants array:

```<code>$variants = [
    'lato',
    'latob',
    'latobi',
    'latoblack',
    'latoblacki',
    'latohairline',
    'latohairlinei',
    'latoheavy',
    'latoheavyi',
    'latoi',
    'latolight',
    'latolighti',
    'latomedium',
    'latomediumi',
    'latosemib',
    'latosemibi',
    'latothin',
    'latothini'
];

$svg_content = '<svg width="600px" height="800px">';

foreach ($variants as $key => $variant) {
    $svg_content .= '<text x="30" y="' . ( 30 * ( $key + 1 ) ) . '" fill="#ED6E46" font-size="20" font-family="\'' . $variant . '\'" text-anchor="start">The quick brown fox jumped over the lazy dog (' . $variant . ').</text>';
}

$svg_content .= '</svg>';

ob_start();

$pdf = new TCPDF();

$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->SetMargins(0, 0, -1, true);
$pdf->SetAutoPageBreak(false, 0);

$pdf->AddPage();
//$pdf->AddFont('latoblack', '', dirname(__FILE__) . '/fonts/output/latoblack.php');

$pdf->ImageSVG('@' . $svg_content, 0, 0, 300, 300, '', $align='', $palign='C', $border=0, false);

$pdf->Output('example_001.pdf', 'I');
</code>```

Output:

Body:
I want to embed an SVG image into a PDF, and have the font families specified in the SVG text elements render using the correct fonts.

The fonts I am using are the 'Lato' TTF fonts.

Here is the code I have used to convert the fonts to TCPDF's "native format":

$variants = [
    'Black',
    'BlackItalic',
    'Bold',
    'BoldItalic',
    'Hairline',
    'HairlineItalic',
    'Heavy',
    'HeavyItalic',
    'Italic',
    'Light',
    'LightItalic',
    'Medium',
    'MediumItalic',
    'Regular',
    'Semibold',
    'SemiboldItalic',
    'Thin',
    'ThinItalic',
];

foreach ($variants as $variant) {
    \TCPDF_FONTS::addTTFfont(
        '/var/www/fonts/Lato-' . $variant . '.ttf',
        '',
        '',
        32,
        '/var/www/fonts/output/'
    );
}

And here is the code I've used to generate a test PDF with an embedded SVG:

$svg_content = '<svg width="600px" height="800px">';
foreach ($variants as $key => $variant) {
    $svg_content .= '<text x="30" y="' . ( 30 * ( $key + 1 ) ) . '" fill="#ED6E46" font-size="20" font-family="\'Lato-' . $variant . '\'" text-anchor="start">The quick brown fox jumped over the lazy dog (' . $variant . ').</text>';
}
$svg_content .= '</svg>';

$pdf = new TCPDF();

$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->SetMargins(0, 0, -1, true);
$pdf->SetAutoPageBreak(false, 0);

$pdf->AddPage();

$pdf->AddFont('Lato-Black', '', '/var/www/fonts/output/latoblack.php');

$pdf->ImageSVG('@' . $svg_content, 0, 0, 300, 300, '', $align='', $palign='C', $border=0, false);

$pdf->Output(
    preg_replace('/[^A-Za-z0-9]/', '', $influencer->getName()) . '.pdf',
    'I'
);

The result I get is that all the text is rendered in what I assume is Helvetica:

If I add a line just before the call to ImageSVG() like this:

$pdf->SetFont('Lato-Black', '', null, '/var/www/fonts/output/latoblack.php');

Then all the text is rendered in Lato-Black:

It seems to me that the fonts are being embedded in the PDF fine, but the SetFont obviously sets the current font for subsequent PDF text elements, and the text elements within the SVG image render using this font.

My desired behaviour is that the font-family attributes defined on the SVG text elements are honoured within the PDF, so that each line renders using the font variant mentioned in the brackets at the end of the line.

How can I do this?

Body:
You could start with the following code and work backwards incorporating your changes.

To be clear I'm not specifically advocating this as the way to do it, only that this is one way that works and so should help as a starting point.

Font Converter:

$variants = [
    'Black',
    'BlackItalic',
    'Bold',
    'BoldItalic',
    'Hairline',
    'HairlineItalic',
    'Heavy',
    'HeavyItalic',
    'Italic',
    'Light',
    'LightItalic',
    'Medium',
    'MediumItalic',
    'Regular',
    'Semibold',
    'SemiboldItalic',
    'Thin',
    'ThinItalic',
];

foreach ($variants as $variant) {
    \TCPDF_FONTS::addTTFfont(dirname(__FILE__) . '/fonts/Lato-' . $variant . '.ttf', 'TrueTypeUnicode', '', 96);
}

echo 'Done!';

This puts the .php, .z and .ctg.z files within /tecnickcom/tcpdf/fonts.

PDF Generator:

Note the different font-family names in the $variants array:

$variants = [
    'lato',
    'latob',
    'latobi',
    'latoblack',
    'latoblacki',
    'latohairline',
    'latohairlinei',
    'latoheavy',
    'latoheavyi',
    'latoi',
    'latolight',
    'latolighti',
    'latomedium',
    'latomediumi',
    'latosemib',
    'latosemibi',
    'latothin',
    'latothini'
];

$svg_content = '<svg width="600px" height="800px">';

foreach ($variants as $key => $variant) {
    $svg_content .= '<text x="30" y="' . ( 30 * ( $key + 1 ) ) . '" fill="#ED6E46" font-size="20" font-family="\'' . $variant . '\'" text-anchor="start">The quick brown fox jumped over the lazy dog (' . $variant . ').</text>';
}

$svg_content .= '</svg>';

ob_start();

$pdf = new TCPDF();

$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->SetMargins(0, 0, -1, true);
$pdf->SetAutoPageBreak(false, 0);

$pdf->AddPage();
//$pdf->AddFont('latoblack', '', dirname(__FILE__) . '/fonts/output/latoblack.php');

$pdf->ImageSVG('@' . $svg_content, 0, 0, 300, 300, '', $align='', $palign='C', $border=0, false);

$pdf->Output('example_001.pdf', 'I');

Output:


问:
Json data not converting to List
I have a json data which was not serialized properly.
I have attached the expected and bad one.

I need to handle the bad json, get in a right format

Expected

```<code>"channels": {
    "heart-rate": {
        "events": {
            "type": "Project.Model.ChannelEvents.HeartRateChannelEvent, Project, Version=1.2.7.0, Culture=neutral, PublicKeyToken=null",
            "structure": [
                "beatsPerMinute",
                "offset"
            ],
            "list": [
                [
                    40,
                    0
                ]
            ]
        }
    },
    "location": {
        "events": {
            "type": "Project.Model.ChannelEvents.LocationChannelEvent, Project, Version=1.2.7.0, Culture=neutral, PublicKeyToken=null",
            "structure": [
                "latitude",
                "longitude",
                "offset"
            ],
            "list": [
                [
                    0.0,
                    0.0,
                    0
                ]
            ]
        }

    }
}
</code>```

badjson
This is the bad json data which needs to be formatted, in a console application

```<code>"channels": {
    "heart-rate": {
        "events": {
            "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
            "$values": [{
                    "$type": "Project.Model.ChannelEvents.HeartRateChannelEvent, Project",
                    "beatsPerMinute": 40,
                    "offset": 0
                }
            ]
        }
    },
    "location": {
        "events": {
            "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
            "$values": [{
                    "$type": "Project.Model.ChannelEvents.LocationChannelEvent, Project",
                    "latitude": 0.0,
                    "longitude": 0.0,
                    "offset": 0
                }
            ]
        }
    }
}
</code>```

答: Use Json.NET to Serialize and Deserialize your JSON</p>

Title: Json data not converting to List

Body:
I have a json data which was not serialized properly.
I have attached the expected and bad one.

I need to handle the bad json, get in a right format

Expected

"channels": {
    "heart-rate": {
        "events": {
            "type": "Project.Model.ChannelEvents.HeartRateChannelEvent, Project, Version=1.2.7.0, Culture=neutral, PublicKeyToken=null",
            "structure": [
                "beatsPerMinute",
                "offset"
            ],
            "list": [
                [
                    40,
                    0
                ]
            ]
        }
    },
    "location": {
        "events": {
            "type": "Project.Model.ChannelEvents.LocationChannelEvent, Project, Version=1.2.7.0, Culture=neutral, PublicKeyToken=null",
            "structure": [
                "latitude",
                "longitude",
                "offset"
            ],
            "list": [
                [
                    0.0,
                    0.0,
                    0
                ]
            ]
        }

    }
}

badjson
This is the bad json data which needs to be formatted, in a console application

"channels": {
    "heart-rate": {
        "events": {
            "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
            "$values": [{
                    "$type": "Project.Model.ChannelEvents.HeartRateChannelEvent, Project",
                    "beatsPerMinute": 40,
                    "offset": 0
                }
            ]
        }
    },
    "location": {
        "events": {
            "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
            "$values": [{
                    "$type": "Project.Model.ChannelEvents.LocationChannelEvent, Project",
                    "latitude": 0.0,
                    "longitude": 0.0,
                    "offset": 0
                }
            ]
        }
    }
}


问:
Multiple jquery ajax on page not working
I've got 2 ajax requests on one page. Both work fine on separate pages, but when they're both on the same page, one stops working after the first has been run.

I'm using the Colorbox plugin for one request and this works fine. The other I've put together myself (I'm new to jquery, so may well have errors) and works if I run it first. But once Colorbox has been activated it stops working.

The page is here: http://dev.thetram.net/times/test2.php and the code below.

Would really appreciate some pointers to where I'm going wrong, thanks!

```<code><script type="text/javascript">
<!--
$(document).ready(function(){

$(function() {
$('#parkride').change(function () {

$.ajax({
    type: "POST",
 url: "http://dev.thetram.net/inc/parkingfinder_script.asp",
 dataType: "application/x-www-form-urlencoded",
 data: "Action=GetPR&Val=" + $("#parkride").val(),
 async: false,
 success: function(msg) {
     $('#output').html("<li>" + msg + "</li>");
 }
 });
return false;
    });
  });

$(function() {
//if submit button is clicked
$('form#frm_journeyplanner #submit').click(function () {

//get form values
var str = $("form#frm_journeyplanner").serialize();

$.ajax({
    type: "POST",
    url: "http://dev.thetram.net/inc/journeyplanner/jp_testscript.asp",
 dataType: "application/x-www-form-urlencoded",
    data: str,
 async: false,
 success: function(msg) {
  $('#results').html(msg);
  $.colorbox({inline:true, href:"#results", opacity:0.6, innerWidth:620, innerHeight:580, title:"Find tram times",
  onOpen:function(){  $("#results").show(); }, //make sure results show in the modal window
  onClosed:function(){ $("#results").hide(); } //stop results from displaying on the main page
   });
 }
 });
return false;
    });
  });

}); // end of doc ready
-->
</script>
</code>```

答:
I've debugged it and it's clear what the problem is.

The second ajax request will inject another HTML element (DIV in this case) with the same id="output" which will then cause the first ajax query on subsequent calls to put the result in that DIV instead of in the UL that you want.

How did I know? I used debugging tools provided with Google Chrome. I noticed that $("#output") (I made a watch expression for this) 'points' to the UL at first, but then as soon as second ajax request if finished, all of the sudden this same expression points to DIV element. Then I examined the return value of the second ajax request and indeed it's one DIV element with the id="output".

Don't forget - when you say $("#output") you might get multiple elements with the id="output". If you only want UL elements with that id, then you should specify that, otherwise you'll get back all elements with that particular id.

In short, what you want at the end of the first ajax query is:

```<code>$('ul#output').html("<li>" + msg + "</li>");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've debugged it and it's clear what the problem is.

The second ajax request will inject another HTML element (DIV in this case) with the same id="output" which will then cause the first ajax query on subsequent calls to put the result in that DIV instead of in the UL that you want.

How did I know? I used debugging tools provided with Google Chrome. I noticed that $("#output") (I made a watch expression for this) 'points' to the UL at first, but then as soon as second ajax request if finished, all of the sudden this same expression points to DIV element. Then I examined the return value of the second ajax request and indeed it's one DIV element with the id="output".

Don't forget - when you say $("#output") you might get multiple elements with the id="output". If you only want UL elements with that id, then you should specify that, otherwise you'll get back all elements with that particular id.

In short, what you want at the end of the first ajax query is:

$('ul#output').html("<li>" + msg + "</li>");


问:
How can i change number Of Rows In each Components

How can i change number Of Rows In each Components
i have this:

```<code>- (NSInteger) pickerView:(UIPickerView *)pickerView  numberOfRowsInComponent:(NSInteger)component
{
return 3;
}
</code>```

BUT this change all of Components rows number,

And The next question is : How can i Change the values in third component Like UIDatePicker : for example: in Date (in january) days are 31 but (in February) days are (29/28) an the third components must change and values will be between 1-29 or 1-28.

答:
Depends on your need. Return different number.</p>

```<code>- (NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{

if(CONDITION 1)
return 2;
else if(CONDITION 2)
return 3;
}
</code>```

Body:
How can i change number Of Rows In each Components
i have this:

- (NSInteger) pickerView:(UIPickerView *)pickerView  numberOfRowsInComponent:(NSInteger)component
{
return 3;
}

BUT this change all of Components rows number,

And The next question is : How can i Change the values in third component Like UIDatePicker : for example: in Date (in january) days are 31 but (in February) days are (29/28) an the third components must change and values will be between 1-29 or 1-28.

Body:
Depends on your need. Return different number.

- (NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{

if(CONDITION 1)
return 2;
else if(CONDITION 2)
return 3;
}


问:
Wordpress rewrite rule with custom taxonomy and custom post type
I have custom post_type called 'video' and custom taxonomy "channels"

I want to rewrite my video details page like this:

```<code>http://example.com/funny/<postname>
</code>```

here "funny" is channels term.

I tried some code like:

```<code>add_permastruct( 'video', '%channels%/%video%' );
</code>```

It's working fine but when I'm trying to open post details page whose permalink structure is:

```<code>http://example.com/<parent_category>/<postname>
</code>```

it's not working.  All post single page show 404.

Please help me.

答:
you should achive your result customizing the rewrite property on your post type definition:

Custom Post type id -> video

video Custom taxonomy id -> ct_video

Custom Post type id -> channels

channels custom taxonomy id -> ct_channels

if you want to customize your custom post type or cutom taxonomy archive or page:

```<code>'rewrite' => array('slug' => '[custom url]')
</code>```

to personalize the url of your posts I advise you to download Custom Post Type Permalinks : https://wordpress.org/plugins/custom-post-type-permalinks/
and you can use it like this:

defining the custom post type post url using the structure tags

Body:
I have custom post_type called 'video' and custom taxonomy "channels"

I want to rewrite my video details page like this:

http://example.com/funny/<postname>

here "funny" is channels term.

I tried some code like:

add_permastruct( 'video', '%channels%/%video%' );

It's working fine but when I'm trying to open post details page whose permalink structure is:

http://example.com/<parent_category>/<postname>

it's not working.  All post single page show 404.

Please help me.

Body:
you should achive your result customizing the rewrite property on your post type definition:

Custom Post type id -> video

video Custom taxonomy id -> ct_video

Custom Post type id -> channels

channels custom taxonomy id -> ct_channels

if you want to customize your custom post type or cutom taxonomy archive or page:

'rewrite' => array('slug' => '[custom url]')

to personalize the url of your posts I advise you to download Custom Post Type Permalinks : https://wordpress.org/plugins/custom-post-type-permalinks/
and you can use it like this:

defining the custom post type post url using the structure tags


问:
How to print lines that contains specific string?
I want to print lines that contains date in the string , i am using split module to achieve that task. below code is always printing else statement.

ctrl.js

```<code>fs.readFile(dir + '/' + logFile, 'utf8', function(err, data) {
        var lines = data.split('\n');
        var linesWithDate = lines.split('|')[0].replace(/[\[\]']+/g,'');
        lines.forEach(function(line) {
            if (linesWithDate) {
                console.log('print lines with date',line);
             } else {
                console.log('print lines without date',line);
             }
        }
    });
</code>```

file data

```<code>[2017-03-23T18:13:16Z]|zlpv7490|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event lorem ipsum
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy
[2017-03-23T19:20:16Z]|zlpv7490|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event lorem ipsum
</code>```

答:
How to print lines that contains specific string?

```<code>const split = require('split');
fs.createReadtStream(path.join(dir, logFile), 'utf8')
  .pipe(split()).on('data', (line) => {
    if (line.indexOf('string') > -1) {
        console.log('Line with string:', line);
    } else {
        console.log('Line without string:', line);
    }
});
</code>```

I want to print lines that contains date in the string , i am using split module to achieve that task. below code is always printing else statement

I don't think you were using the split module. This example does:

```<code>const split = require('split');
const regex = require('regex-iso-date');
fs.createReadtStream(path.join(dir, logFile), 'utf8')
  .pipe(split()).on('data', (line) => {
    if (regex().test(line)) {
        console.log('Line with date:', line);
    } else {
        console.log('Line without date:', line);
    }
});
</code>```

Note that this will not necessarily be a valid date, as it may match dates like 2017-13-13... - to test for valid dates only see this answer:

Check if a string is a date value

Or if you want to match for your specific strings like [2017-03-23T18:13:16Z] then you may try something like this:

```<code>const split = require('split');
const regex = /\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\w+\]/;
fs.createReadtStream(path.join(dir, logFile), 'utf8')
  .pipe(split()).on('data', (line) => {
    if (regex.test(line)) {
        console.log('Line with date:', line);
    } else {
        console.log('Line without date:', line);
    }
});
</code>```

Note that it will also match invalid dates if you have them in your files.

Body:
I want to print lines that contains date in the string , i am using split module to achieve that task. below code is always printing else statement.

ctrl.js

fs.readFile(dir + '/' + logFile, 'utf8', function(err, data) {
        var lines = data.split('\n');
        var linesWithDate = lines.split('|')[0].replace(/[\[\]']+/g,'');
        lines.forEach(function(line) {
            if (linesWithDate) {
                console.log('print lines with date',line);
             } else {
                console.log('print lines without date',line);
             }
        }
    });

file data

[2017-03-23T18:13:16Z]|zlpv7490|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event lorem ipsum
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy
[2017-03-23T19:20:16Z]|zlpv7490|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event lorem ipsum

Body:
How to print lines that contains specific string?

const split = require('split');
fs.createReadtStream(path.join(dir, logFile), 'utf8')
  .pipe(split()).on('data', (line) => {
    if (line.indexOf('string') > -1) {
        console.log('Line with string:', line);
    } else {
        console.log('Line without string:', line);
    }
});

I want to print lines that contains date in the string , i am using split module to achieve that task. below code is always printing else statement

I don't think you were using the split module. This example does:

const split = require('split');
const regex = require('regex-iso-date');
fs.createReadtStream(path.join(dir, logFile), 'utf8')
  .pipe(split()).on('data', (line) => {
    if (regex().test(line)) {
        console.log('Line with date:', line);
    } else {
        console.log('Line without date:', line);
    }
});

Note that this will not necessarily be a valid date, as it may match dates like 2017-13-13... - to test for valid dates only see this answer:

Check if a string is a date value

Or if you want to match for your specific strings like [2017-03-23T18:13:16Z] then you may try something like this:

const split = require('split');
const regex = /\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\w+\]/;
fs.createReadtStream(path.join(dir, logFile), 'utf8')
  .pipe(split()).on('data', (line) => {
    if (regex.test(line)) {
        console.log('Line with date:', line);
    } else {
        console.log('Line without date:', line);
    }
});

Note that it will also match invalid dates if you have them in your files.


问:
Processing table rows in Typescript
I have been trying to convert a JavaScript web form to Typescript, and have been unable to work out how to convert statements involving table rows, such as the following:

```<code>let body = document.getElementById("selectStackBody");

let rowCount = body.rows.length;

let row = body.insertRow(rowCount);

body.deleteRow(i);
</code>```

I can see how to get the body by doing the following:

```<code>let body = <HTMLBodyElement>document.getElementById("selectStackBody");
</code>```

but I can't see how to get the right syntax for the rows.

答:
You don't necessarily have to do anything TypeScript specific here. Basic DOM syntax can do this for you.

If document.getElementById("selectStackBody") gives to the table body node then simply do body.childNodes.length to get the number of rows.

Similarly, to append a row, use the DOM syntax to add a child node.

Here's a sample:

```<code>const body = document.getElementById('selectStackBody')

// Total number of rows
let numberOfRows = body.childNodes.length

// Add a new row
let newRow = document.createElement('tr')
body.appendChild(newRow)

// Remove the first row
body.removeChild(body.childNodes[0])
</code>```

Title: Processing table rows in Typescript

Body:
I have been trying to convert a JavaScript web form to Typescript, and have been unable to work out how to convert statements involving table rows, such as the following:

let body = document.getElementById("selectStackBody");

let rowCount = body.rows.length;

let row = body.insertRow(rowCount);

body.deleteRow(i);

I can see how to get the body by doing the following:

let body = <HTMLBodyElement>document.getElementById("selectStackBody");

but I can't see how to get the right syntax for the rows.

Body:
You don't necessarily have to do anything TypeScript specific here. Basic DOM syntax can do this for you.

If document.getElementById("selectStackBody") gives to the table body node then simply do body.childNodes.length to get the number of rows.

Similarly, to append a row, use the DOM syntax to add a child node.

Here's a sample:

const body = document.getElementById('selectStackBody')

// Total number of rows
let numberOfRows = body.childNodes.length

// Add a new row
let newRow = document.createElement('tr')
body.appendChild(newRow)

// Remove the first row
body.removeChild(body.childNodes[0])


答:
Here is some code which prints out only valid parsed dates by line. I use the readline module instead of readfile, but you should be able to easily adapt the logic by replacing input: process.stdin:
    'use strict';

```<code>var sExample = '[2017-03-23T18:13:16Z]|zlpv7490|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event lorem ipsum';

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.setPrompt('Enter example string to test > ');
rl.prompt();

rl.on('line', (line) => {
  var sCandidate = line.split('|')[0].replace(/[\[\]']+/g,'');

  if (Date.parse(sCandidate)) {                   //it is a valid date
    console.log(sCandidate);
  }

  process.exit(0);
});
</code>```

Title: How to print lines that contains specific string?

Body:
Here is some code which prints out only valid parsed dates by line. I use the readline module instead of readfile, but you should be able to easily adapt the logic by replacing input: process.stdin:
    'use strict';

var sExample = '[2017-03-23T18:13:16Z]|zlpv7490|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event lorem ipsum';

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.setPrompt('Enter example string to test > ');
rl.prompt();

rl.on('line', (line) => {
  var sCandidate = line.split('|')[0].replace(/[\[\]']+/g,'');

  if (Date.parse(sCandidate)) {                   //it is a valid date
    console.log(sCandidate);
  }

  process.exit(0);
});


问:
AMP form validation for Safari
AMP form only allows me to use HTML5 form validation to validate users inputs. It works well in desktop Chrome browser. But Safari couldn't support HTML5 form validation until now. I found solution, requires external Javascript to implement form validation on Safari browser. But in my case, AMP doesn't allow me to do so.

Is there any hacks or trick to bypass HTML5 validation inputs for Safari?

答:
Try comparing your AMP document to the AMP by Example amp-form demo. The amp-form extension implements a form validation API polyfill for browsers that don't support native validation. If you're using amp-form in Safari versions without native support, the polyfill behavior should run automatically.

The polyfill validation should look something like this:

Title: AMP form validation for Safari


问:
Get specific value from nested collections using LINQ
I have a collection of "product" objects that each contain a collection of benefit objects. See below:

```<code><Products>
        <Product ID="454">
            <ProductName>Economy</ProductName>
            <Benefits>
                <Benefit>
                    <Name>Medical</Name>
                    <Value>5000000</Value>
                    <Excess>100</Excess>
                </Benefit>
                <Benefit>
                    <Name>Emergency</Name>
                    <Value>350</Value>
                    <Excess>100</Excess>
                </Benefit>
        </Product>
</Products>
</code>```

I'm trying to create a LINQ query to get the "Medical" benefit value for product "454":

```<code><%: Model.Products.Where(x => x.ProductId == "454").SelectMany(p => p.Benefits).Where(b => b.Name == "Medical").Select(v => v.Value.ToString()) %>
</code>```

However this just returns:

```<code>System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String
</code>```

How do I get it to return the actual value I'm after?

答: If you know there is only one (guaranteed) then add .Single() - if there might be none / some and you just want the first, add .FirstOrDefault() (will return null if there are no results)

Body:
I have a collection of "product" objects that each contain a collection of benefit objects. See below:

<Products>
        <Product ID="454">
            <ProductName>Economy</ProductName>
            <Benefits>
                <Benefit>
                    <Name>Medical</Name>
                    <Value>5000000</Value>
                    <Excess>100</Excess>
                </Benefit>
                <Benefit>
                    <Name>Emergency</Name>
                    <Value>350</Value>
                    <Excess>100</Excess>
                </Benefit>
        </Product>
</Products>

I'm trying to create a LINQ query to get the "Medical" benefit value for product "454":

<%: Model.Products.Where(x => x.ProductId == "454").SelectMany(p => p.Benefits).Where(b => b.Name == "Medical").Select(v => v.Value.ToString()) %>

However this just returns:

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String

How do I get it to return the actual value I'm after?


问:
The state field path 'e.id' cannot be resolved to a valid type. Dynamic entity in orm.xml,
This simple SINGLE_TABLE inheritance hierarchy somehow fails when my application tries to access the inheriting entity RootFolderNode.

The entities are defined as dynamic entities access="VIRTUAL", without a Java class backing. The PersistenceUnit is loaded without any complaints.

```<code>Exception Description: Problem compiling
    [SELECT DISTINCT e FROM RootFolderNode e WHERE  e.id =  :param1 ].
[46, 50] The state field path 'e.id' cannot be resolved to a valid type.
</code>```

The relevant part of the ORM.xml

```<code><entity class="FolderNode" access="VIRTUAL" >
    <table name="FOLDER_NODE_PREPARE" />
    <inheritance strategy="SINGLE_TABLE"/>
    <discriminator-value>F</discriminator-value>
    <attributes>
        <id name="id" attribute-type="Long">
            <column name="id" />
            <generated-value strategy="SEQUENCE" generator="FOLDER_NODE_SEQ" />
            <sequence-generator sequence-name="FOLDER_NODE_SEQ" name="FOLDER_NODE_SEQ" allocation-size="1" />
        </id>
        ...
    </attributes>
</entity>

<entity class="RootFolderNode" parent-class="FolderNode" access="VIRTUAL">
    <discriminator-value>R</discriminator-value>
</entity>
</code>```

What am I missing here?

Products in use: EclipseLink 2.5.1. JBoss EAP 6.2.

答:
you should use inheritance strategy to overcome this.please add the following line in your RootFolderNode.</p>

```<code> <inheritance strategy="SINGLE_TABLE"/>
</code>```

Body:
This simple SINGLE_TABLE inheritance hierarchy somehow fails when my application tries to access the inheriting entity RootFolderNode.

The entities are defined as dynamic entities access="VIRTUAL", without a Java class backing. The PersistenceUnit is loaded without any complaints.

Exception Description: Problem compiling
    [SELECT DISTINCT e FROM RootFolderNode e WHERE  e.id =  :param1 ].
[46, 50] The state field path 'e.id' cannot be resolved to a valid type.

The relevant part of the ORM.xml

<entity class="FolderNode" access="VIRTUAL" >

    <inheritance strategy="SINGLE_TABLE"/>
    <discriminator-value>F</discriminator-value>
    <attributes>
        <id name="id" attribute-type="Long">
            <column name="id" />
            <generated-value strategy="SEQUENCE" generator="FOLDER_NODE_SEQ" />
            <sequence-generator sequence-name="FOLDER_NODE_SEQ" name="FOLDER_NODE_SEQ" allocation-size="1" />
        </id>
        ...
    </attributes>
</entity>

<entity class="RootFolderNode" parent-class="FolderNode" access="VIRTUAL">
    <discriminator-value>R</discriminator-value>
</entity>

What am I missing here?

Products in use: EclipseLink 2.5.1. JBoss EAP 6.2.

Body:
you should use inheritance strategy to overcome this.please add the following line in your RootFolderNode.

 <inheritance strategy="SINGLE_TABLE"/>


问:
Xcode - How to config a project for team working?
I'm working on a team project using Git for versioning. All team members got a personal AppleID and bundle identifier. Every time one of us pushes some changes, others need to adjust their Bundle Identifiers and Team. This is where we need to change settings:

Is there a way to work simultaneously on the same project under it versioning with our personal accounts?

答: You should share a common Apple Developer account and add developers personal accounts though the common Apple Dev account. Then you will share the same bundle ID and Xcode's automatic signing will work.</p>


Title: Generate HTML table and load it in div element

Body:
I'd like to load a HTML table into a div-element (id="resultDataDistancesTable") - but the generated string isn't processed (no matter if I use html(), append() or innerHTML). There is no error in the console.

When I paste the console.log(..) output directly to the HTML page I get the table that I want - so why doesn't my JavaScript code work? Is something wrong with the string?

var response = {"distances":[[0,4569,17264,6074,4986,12430,10936,11729,11280,23714,19112,24070,24974,25809,24157,27636,27323,15690,27970,22152],[4837,0,9160,1879,1872,12492,10755,15237,14468,21251,16649,17650,20574,23346,21694,31144,30831,13227,23141,19689],[17807,9681,0,8419,14314,25164,23427,28206,27140,11709,17204,18205,21130,23901,22249,30219,29906,4147,23696,10294],[6156,1736,8271,0,3191,12812,8437,16555,14788,22085,17483,18484,21408,24180,22528,30498,30185,14061,23975,20523],[5438,1642,14335,3147,0,12796,11058,15838,14771,20785,16183,17184,20108,22880,21228,31745,31432,12761,22674,19223],[12266,13371,25607,10970,13329,0,1842,20750,6094,32057,27455,28455,31380,34152,32500,37248,36935,24033,37581,30495],[10434,11651,16093,8428,11608,1842,0,19509,7092,30336,25734,26735,29659,32431,30779,35416,35104,22312,35750,28774],[12355,15633,28328,17138,16050,19963,20849,0,6457,34778,30176,26719,27624,33122,31702,30285,29973,26754,30619,33216],[11054,14433,26669,14776,14391,6088,9450,10828,0,33119,28517,36279,37184,35214,33562,39846,39533,25095,40179,31557],[21936,20085,11649,19803,18444,29293,27556,32335,31269,0,2943,8201,8702,10694,9042,17012,16699,8876,11268,5269],[19141,17291,16426,17009,15649,26499,24762,29541,28475,2924,0,5407,6515,9365,7713,15683,15370,14852,9082,6033],[22777,19065,18201,18783,17424,28274,26536,25758,31348,8188,5556,0,2979,5144,6115,10994,10681,16626,5493,10239],[23722,21760,20895,21478,20118,30968,29231,26703,32292,8634,6627,2994,0,2715,3388,4505,4192,19321,3110,11521],[29801,24947,24082,24665,23305,34155,32417,32782,38371,9673,8179,5136,2704,0,2345,4277,3964,22508,1703,15331],[25139,23289,22424,23007,21647,32497,30760,30797,34473,8016,6521,6129,3394,2340,0,5174,4862,20850,3779,13673],[26964,30242,30040,31748,30660,36952,35458,29945,35534,16511,10598,10365,4526,4274,5182,0,336,28466,1821,15492],[26628,29906,29704,31412,30324,36616,35122,29609,35198,16175,10262,10029,4190,3938,4846,313,0,28130,1485,15156],[16108,9772,4136,13975,12616,23466,21728,26507,25441,8931,10916,11916,14841,17613,15961,23930,23617,0,17407,7516],[27163,30441,23429,24012,22653,37151,35657,30144,35733,11168,9161,5495,3089,1703,3746,1686,1373,21855,0,14055],[22592,20741,10188,20459,19100,29949,28212,32991,31925,5369,5909,10225,11565,14414,12762,20732,20419,7415,14131,0]]};

buildResultTableDistances();

function buildResultTableDistances() {
    var tbl;
    var tr_head = "

distances [meters]	";
    for (var i = 0; i < 20; i++) {
        tr_head += "" + "dummy" + "	";
    }
    tr_head += "
";
    tbl = tr_head;

    for (var i = 0; i < 20; i++) {
        var row = "
" + "dummy" + "	";
        for (var ii = 0; ii < 20; ii++) {
            row += "" + response.distances[i][ii] + "	";
        }
        row += "
";
        tbl += row;
    }
    tbl += "
";
    console.log(tbl);
    $('#resultDataDistancesTable').html(tbl);
}

Body:
I suspect you forgot to insert the HTML or including jQuery, because it works fine here.  If you want, to do this solely in JavaScript by adding the element in jQuery:

$(document.body).append('<div id="resultDataDistancesTable"></div>');

var response = {"distances":[[0,4569,17264,6074,4986,12430,10936,11729,11280,23714,19112,24070,24974,25809,24157,27636,27323,15690,27970,22152],[4837,0,9160,1879,1872,12492,10755,15237,14468,21251,16649,17650,20574,23346,21694,31144,30831,13227,23141,19689],[17807,9681,0,8419,14314,25164,23427,28206,27140,11709,17204,18205,21130,23901,22249,30219,29906,4147,23696,10294],[6156,1736,8271,0,3191,12812,8437,16555,14788,22085,17483,18484,21408,24180,22528,30498,30185,14061,23975,20523],[5438,1642,14335,3147,0,12796,11058,15838,14771,20785,16183,17184,20108,22880,21228,31745,31432,12761,22674,19223],[12266,13371,25607,10970,13329,0,1842,20750,6094,32057,27455,28455,31380,34152,32500,37248,36935,24033,37581,30495],[10434,11651,16093,8428,11608,1842,0,19509,7092,30336,25734,26735,29659,32431,30779,35416,35104,22312,35750,28774],[12355,15633,28328,17138,16050,19963,20849,0,6457,34778,30176,26719,27624,33122,31702,30285,29973,26754,30619,33216],[11054,14433,26669,14776,14391,6088,9450,10828,0,33119,28517,36279,37184,35214,33562,39846,39533,25095,40179,31557],[21936,20085,11649,19803,18444,29293,27556,32335,31269,0,2943,8201,8702,10694,9042,17012,16699,8876,11268,5269],[19141,17291,16426,17009,15649,26499,24762,29541,28475,2924,0,5407,6515,9365,7713,15683,15370,14852,9082,6033],[22777,19065,18201,18783,17424,28274,26536,25758,31348,8188,5556,0,2979,5144,6115,10994,10681,16626,5493,10239],[23722,21760,20895,21478,20118,30968,29231,26703,32292,8634,6627,2994,0,2715,3388,4505,4192,19321,3110,11521],[29801,24947,24082,24665,23305,34155,32417,32782,38371,9673,8179,5136,2704,0,2345,4277,3964,22508,1703,15331],[25139,23289,22424,23007,21647,32497,30760,30797,34473,8016,6521,6129,3394,2340,0,5174,4862,20850,3779,13673],[26964,30242,30040,31748,30660,36952,35458,29945,35534,16511,10598,10365,4526,4274,5182,0,336,28466,1821,15492],[26628,29906,29704,31412,30324,36616,35122,29609,35198,16175,10262,10029,4190,3938,4846,313,0,28130,1485,15156],[16108,9772,4136,13975,12616,23466,21728,26507,25441,8931,10916,11916,14841,17613,15961,23930,23617,0,17407,7516],[27163,30441,23429,24012,22653,37151,35657,30144,35733,11168,9161,5495,3089,1703,3746,1686,1373,21855,0,14055],[22592,20741,10188,20459,19100,29949,28212,32991,31925,5369,5909,10225,11565,14414,12762,20732,20419,7415,14131,0]]};

buildResultTableDistances();

function buildResultTableDistances() {
    var tbl;
    var tr_head = "<table><tr><td>distances [meters]</td>";
    for (var i = 0; i < 20; i++) {
        tr_head += "<td><b>" + "dummy" + "</b></td>";
    }
    tr_head += "</tr>";
    tbl = tr_head;

    for (var i = 0; i < 20; i++) {
        var row = "<tr><td><b>" + "dummy" + "</b></td>";
        for (var ii = 0; ii < 20; ii++) {
            row += "<td>" + response.distances[i][ii] + "</td>";
        }
        row += "</tr>";
        tbl += row;
    }
    tbl += "</table>";
    $('#resultDataDistancesTable').html(tbl);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="resultDataDistancesTable"></div>