问:
pairing each RDD value with all the other values in RDD in scala
I am trying to pair each value in the RDD with all the other values of the same RDD. But I am not able to come up with a proper solution.

RDD : Below Image represents the RDD data with pair as-> (UserId, MovieName::Rating).   (UserId, MovieName::Rating) ">

I want to pair the moviename and ratings of each user as below:

from the above image:

user 1 rated Edison Kinetoscopic.. as 10 and La sortie... as 10

user 2 rated The Arrival .. as 8, Le manoir..  as 7, Edison Kinetoscopic.. as 7 etc...

SO, the output should be..

```<code>**key**: (Edison Kinetoscopic,La sortie des)
**Value** : (10,10), (7,8)   -> Since user 1 and user two rated these two movies
**Key**: (The Arrival, Le manoir)
**value**: (8,7)    -> only user-2 rated these two movies.
</code>```

Any help appreciated.

答:
If you're trying to build a recommender system, or compute movie-movie similarity, there are must better ways to do this.

However, to solve your problem, you can do the following:

```<code>val rdd = sc.parallelize(List(
      (1,"Edison", 10),
      (1,"La sortie", 10),
      (2,"The Arrival", 8),
      (2,"Le manoir", 7),
      (2,"Edison", 7),
      (2,"La sortie", 8),
      (2,"Le voyage", 8),
      (2,"The Great", 7)
))

// first group user movies
val pairings = rdd.map{case (user,movie,rating) => (user, List((movie,rating)))}.reduceByKey(_++_)

// then get all pairs for each user
val allPairs = pairings.flatMap{case (user, movieRatings) => (1 until movieRatings.length).flatMap(i => movieRatings.zip(movieRatings drop i))}

// re-structure pairings into format we want
val finalPairing = allPairs.map{case ((m1,r1),(m2,r2)) => m1.compareTo(m2) match {case -1 => ((m1,m2),List((r1,r2))); case _ => ((m2,m1),List((r2,r1)))}}.

// group by pairings
val groupByPair = finalPairing.reduceByKey(_++_)

// look at our pairings
pairings.take(100).foreach(println)
</code>```

the compareTo is needed to guarantee that movies appear in the same order in the tuple, and thus can be grouped.

Body:
I am trying to pair each value in the RDD with all the other values of the same RDD. But I am not able to come up with a proper solution.

RDD : Below Image represents the RDD data with pair as-> (UserId, MovieName::Rating).   (UserId, MovieName::Rating) ">

I want to pair the moviename and ratings of each user as below:

from the above image:

user 1 rated Edison Kinetoscopic.. as 10 and La sortie... as 10

user 2 rated The Arrival .. as 8, Le manoir..  as 7, Edison Kinetoscopic.. as 7 etc...

SO, the output should be..

**key**: (Edison Kinetoscopic,La sortie des)
**Value** : (10,10), (7,8)   -> Since user 1 and user two rated these two movies
**Key**: (The Arrival, Le manoir)
**value**: (8,7)    -> only user-2 rated these two movies.

Any help appreciated.

Body:
If you're trying to build a recommender system, or compute movie-movie similarity, there are must better ways to do this.

However, to solve your problem, you can do the following:

val rdd = sc.parallelize(List(
      (1,"Edison", 10),
      (1,"La sortie", 10),
      (2,"The Arrival", 8),
      (2,"Le manoir", 7),
      (2,"Edison", 7),
      (2,"La sortie", 8),
      (2,"Le voyage", 8),
      (2,"The Great", 7)
))

// first group user movies
val pairings = rdd.map{case (user,movie,rating) => (user, List((movie,rating)))}.reduceByKey(_++_)

// then get all pairs for each user
val allPairs = pairings.flatMap{case (user, movieRatings) => (1 until movieRatings.length).flatMap(i => movieRatings.zip(movieRatings drop i))}

// re-structure pairings into format we want
val finalPairing = allPairs.map{case ((m1,r1),(m2,r2)) => m1.compareTo(m2) match {case -1 => ((m1,m2),List((r1,r2))); case _ => ((m2,m1),List((r2,r1)))}}.

// group by pairings
val groupByPair = finalPairing.reduceByKey(_++_)

// look at our pairings
pairings.take(100).foreach(println)

the compareTo is needed to guarantee that movies appear in the same order in the tuple, and thus can be grouped.


来源: stackexchange

问:
Will providing APIs help deter screen scraping?
I have been thinking quite a bit here lately about screen scraping and what a task it can be. So I pose the following question.

Would you as a site developer expose simple APIs to prevent users from screen scraping, such as JSON results?

These results could then implement caching, and they are much smaller for traffic than the huge amounts of markup that could potentially be downloaded.

I am not looking at prevention, but deterring scraping.

Scraping Bandwidth Sample

((users * (% / 100)) * ((freq * 60) * 24)) * filesize

users: 200,000

% of users using utility: 5

filesize: 1kb

freq: 1 minute

Formula:

((users * (% / 100)) * ((freq * 60) * 24)) * filesize

10,000 * 1440 * 1

14400000kb or 13.73291015625gb

Assuming your JSON result is 200 bytes that's now (10,000 * 1440 * 0.2) or 2.74658203125gb a day.

That's a change of about 11gb of traffic a day.

My Stack Overflow profile is 96k for reference.

The reason for this question prompted asking for a JSON result from users profiles:

http://stackoverflow.uservoice.com/pages/general/suggestions/101342-add-json-for-user-information

I wanted to find out if other developers would expose this type of API, and if it is worth your time to provide these APIs to reduce bandwidth.

答: Providing an API should definitely reduce the amount of screen scraping that gets done against your site.  Using a good REST API is much easier and safer than screen scraping.  Screens can change without notice, and that makes screen scraping code much harder to maintain.  As a developer, if I need information from a site, I'd never scrape the site if the same information was available through an API.</p>

OwnerDisplayName: Tom Anderson

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Tom Anderson

OwnerDisplayName: Bill the Lizard


问:
Ruby on Rails. Large condition in controller
I'm faced a situation unfamiliar to me and I need advice.
There is a controller with the action 'update'

```<code>def update
  @arrival = find_arrival
  @details = @arrival.arrival_details

  if check_conditions(@arrival)
    flash[:notice] = 'Документ прихода отредактирован'
  else
    flash[:error] = 'Возникла ошибка. Проверьте правильность заполнения формы'
  end
  redirect_to edit_admin_arrival_path(@arrival)
end
</code>```

and few private methods:

```<code>def check_conditions(arrival)
  new_status = arrival_params[:status]

  case @arrival.status
  when 'draft'
    return unless check_dependencies
    recalculate_balance if new_status == 'accrued'
    @arrival.update(arrival_params)
  when 'canceled'
    return unless new_status == 'draft'
    @arrival.update(status: arrival_params[:status])
  when 'accrued'
    return if new_status == 'draft'
    recalculate_balance if new_status == 'canceled'
    @arrival.update(new_status)
  end
end

def recalculate_balance
  puts '[PRY] recalculated'
end

def check_dependencies
  Provider.exists?(arrival_params[:provider_id]) &&
  Warehouse.exists?(arrival_params[:warehouse_id])
end
</code>```

I'm interested in the following - do I need to move this condition to a separate class or some Service Object for example? I do not think that this huge condition should be in the controller. What can you advise?

答:
Definitely, it's not a Controller logic. Slim controllers are preferred. Better move this one to a service object, or to Arrival class and use as an arrival instance object method @arrival.check_conditions.

And I'd recommend to use state machine here: https://github.com/pluginaweek/state_machine

ContentLicense: CC BY-SA 3.0

Body:
I'm faced a situation unfamiliar to me and I need advice.
There is a controller with the action 'update'

def update
  @arrival = find_arrival
  @details = @arrival.arrival_details

  if check_conditions(@arrival)
    flash[:notice] = 'Документ прихода отредактирован'
  else
    flash[:error] = 'Возникла ошибка. Проверьте правильность заполнения формы'
  end
  redirect_to edit_admin_arrival_path(@arrival)
end

and few private methods:

def check_conditions(arrival)
  new_status = arrival_params[:status]

  case @arrival.status
  when 'draft'
    return unless check_dependencies
    recalculate_balance if new_status == 'accrued'
    @arrival.update(arrival_params)
  when 'canceled'
    return unless new_status == 'draft'
    @arrival.update(status: arrival_params[:status])
  when 'accrued'
    return if new_status == 'draft'
    recalculate_balance if new_status == 'canceled'
    @arrival.update(new_status)
  end
end

def recalculate_balance
  puts '[PRY] recalculated'
end

def check_dependencies
  Provider.exists?(arrival_params[:provider_id]) &&
  Warehouse.exists?(arrival_params[:warehouse_id])
end

I'm interested in the following - do I need to move this condition to a separate class or some Service Object for example? I do not think that this huge condition should be in the controller. What can you advise?


问:
How can I do a recursive find/replace of a string with awk or sed?
How do I find and replace every occurrence of:

```<code>subdomainA.example.com
</code>```

with

```<code>subdomainB.example.com
</code>```

in every text file under the /home/www/ directory tree recursively?

答:
For replace all occurrences in a git repository you can use:

```<code>git ls-files -z | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g'
</code>```

See List files in local git repo? for other options to list all files in a repository. The -z options tells git to separate the file names with a zero byte, which assures that xargs (with the option -0) can separate filenames, even if they contain spaces or whatnot.

ContentLicense: CC BY-SA 4.0

Body:
How do I find and replace every occurrence of:

subdomainA.example.com

with

subdomainB.example.com

in every text file under the /home/www/ directory tree recursively?

Body:
For replace all occurrences in a git repository you can use:

git ls-files -z | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g'

See List files in local git repo? for other options to list all files in a repository. The -z options tells git to separate the file names with a zero byte, which assures that xargs (with the option -0) can separate filenames, even if they contain spaces or whatnot.


问:
Removing acoustic echo in an Android mic to speaker app
I am trying to make an android app which takes input from the headset mic when connected and output it to the earphones. The problem is I am getting an echo while streaming the live mic data to the earphones. I am using AudioRecorder class in Android and I read that in some mobiles the internal "ACOUSTIC ECHO CANCELLATION" is not working in Android.</p>

答:
Use a conference microphone/speaker with built-in noise cancelling.

Android implement noise cancelling API (http://developer.android.com/reference/android/media/audiofx/NoiseSuppressor.html)


问:
need click twice after hide a shown bootstrap popover

$('#popoverlink').popover();

$("#popoverhide").click(function() {
   $("#popoverlink").popover("hide");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#popoverlink {
    position: absolute;
    top: 100px;
    left: 100px;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
Popover
hide```
</div>
</div>
</p>

<p>Same with the fiddle. Sorry the previous link was wrong. This one is correct.</p>

<p>After I hide the shown popover, I need to click the popover trigger twice to show it again.</p>

<p>Is this a bug? Is there anything can avoid this?</p>

<p><strong>UPDATE</strong>
I means I used another button to hide a popover by </p>

```$("#popoverTrigger").popover("hide");
```

<p>Than I need to click the "#popoverTrigger" twice to show it.</p>

<p><strong>STUPID SOLUTION</strong></p>

```$("popoverhide").click(function() {
    var f = false;
    if($("popoverlink").next('div.popover:visible')) {
        f = true;
        $("popoverlink").popover("hide");
    }
    if(f) {
        $("popoverlink").click();
    }
})
```

Is there another good idea?

答:
I recently came across this bug and this is how I fixed it:</p>

```<code>$('.myPopoverClass')
    .popover({
        trigger: 'manual', /* <- important, instantiates popover */
        container: 'body', /* optional */
        animation: false
    })
    .click(function(e) {
        $('.popover').not(this).hide(); /* optional, hide other popovers */
        $(this).popover('show'); /* show popover now it's setup */
        e.preventDefault();
    });
</code>```

Body:
$('#popoverlink').popover();

$("#popoverhide").click(function() {
   $("#popoverlink").popover("hide");
});

#popoverlink {
    position: absolute;
    top: 100px;
    left: 100px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
Popover
hide

Same with the fiddle. Sorry the previous link was wrong. This one is correct.

After I hide the shown popover, I need to click the popover trigger twice to show it again.

Is this a bug? Is there anything can avoid this?

UPDATE
I means I used another button to hide a popover by

$("#popoverTrigger").popover("hide");

Than I need to click the "#popoverTrigger" twice to show it.

STUPID SOLUTION

$("popoverhide").click(function() {
    var f = false;
    if($("popoverlink").next('div.popover:visible')) {
        f = true;
        $("popoverlink").popover("hide");
    }
    if(f) {
        $("popoverlink").click();
    }
})

Is there another good idea?

Body:
I recently came across this bug and this is how I fixed it:

$('.myPopoverClass')
    .popover({
        trigger: 'manual', /* <- important, instantiates popover */
        container: 'body', /* optional */
        animation: false
    })
    .click(function(e) {
        $('.popover').not(this).hide(); /* optional, hide other popovers */
        $(this).popover('show'); /* show popover now it's setup */
        e.preventDefault();
    });


问:
How to know wheter the given identifier is Stored procedure or Table or View
Is there anyway to know whether the given identifier is a table or view or a procedure, etc... in oracle?

Example: I have an identifer "PICKUPON", I want to know the object type of this identifier. I took few mins to know it is procedure by browsing in Schema browser in Toad. Is there any query to get this job done.

答:
I don't have a Oracle database to work with but could you use the OBJECT_TYPE column from this?

https://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_2005.htm#i1583352


问:
Put a Linearlayout under the ListView
I'm facing problem to put a linearlayout under the listview like what is shown in this image link:

I want the layout with the Add icon and text:"Add New Members" to be displayed under the listview. What am I doing wrong? Pls help me to solve the problem. Thank you very much.

This is the xml file for the layout

```<code><LinearLayout 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:orientation="vertical"
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.thomasbrown.myapplication.MemberActivity"
android:background="@android:color/white">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/groupID"
    android:textSize="20sp"
    android:layout_marginBottom="15dp" />

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

    <ListView
        android:id="@+id/ListView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@android:color/white"
        android:layout_weight="1" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            app:srcCompat="@drawable/add"
            android:id="@+id/imageView2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_width="80dp"
            android:layout_height="60dp"
            android:layout_weight="1" />

        <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/addMember"
                android:text="Add New Members"
                android:textSize="18sp"
                android:textColor="@android:color/holo_red_dark"
            android:layout_weight="1"
            android:layout_gravity="center_vertical" />
    </LinearLayout>

</LinearLayout>

<Button
    android:text="Leave this group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/leaveGroupButton"
    android:background="@color/colorPrimary"
    android:layout_gravity="bottom|end" />

</LinearLayout>
</code>```

答:
You have to make changes in you list view item for this, check this.

Add below lines into Adapter get view method:

```<code>    @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            view = LayoutInflater.from(TestListActivity.this).inflate(R.layout.dummy, viewGroup,false);

                    LinearLayout layout =  (LinearLayout)view.findViewById(R.id.add_bottom_ll);
                    if(i==getCount()-1){
                        layout.setVisibility(View.VISIBLE);
                    }else{
                        layout.setVisibility(View.GONE);
                    }
            return view;

        }
</code>```

List view Item view xml

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

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp">

            <ImageView
                android:id="@+id/profile"
                android:layout_width="72dp"
                android:layout_height="72dp"
                android:src="@drawable/arrow" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/profile"
                android:layout_alignParentTop="true"
                android:layout_marginLeft="10dp"
                android:layout_toRightOf="@id/profile"
                android:gravity="center_vertical"
                android:text="user Name"
                android:textSize="18sp" />
        </RelativeLayout>

        <LinearLayout
            android:id="@+id/add_bottom_ll"
            android:layout_width="363dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="80dp"
                android:layout_height="60dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_weight="1"
                android:src="@drawable/index" />

            <TextView
                android:id="@+id/addMember"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:text="Add New Members"
                android:textColor="@android:color/holo_red_dark"
                android:textSize="18sp" />
        </LinearLayout>

    </LinearLayout>
</code>```

View(Activity or Fragment) xml:

```<code><LinearLayout 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:orientation="vertical"
        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.thomasbrown.myapplication.MemberActivity"
        android:background="@android:color/white">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/groupID"
            android:textSize="20sp"
            android:layout_marginBottom="15dp" />

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

            <ListView
                android:id="@+id/ListView1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:background="@android:color/white"
                />

        </LinearLayout>

        <Button
            android:text="Leave this group"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/leaveGroupButton"
            android:background="@color/colorPrimary"
            android:layout_gravity="bottom|end" />

    </LinearLayout>
</code>```

Title: Put a Linearlayout under the ListView

Body:
I'm facing problem to put a linearlayout under the listview like what is shown in this image link:

I want the layout with the Add icon and text:"Add New Members" to be displayed under the listview. What am I doing wrong? Pls help me to solve the problem. Thank you very much.

This is the xml file for the layout

<LinearLayout 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:orientation="vertical"
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.thomasbrown.myapplication.MemberActivity"
android:background="@android:color/white">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/groupID"
    android:textSize="20sp"
    android:layout_marginBottom="15dp" />

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

    <ListView
        android:id="@+id/ListView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@android:color/white"
        android:layout_weight="1" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            app:srcCompat="@drawable/add"
            android:id="@+id/imageView2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_width="80dp"
            android:layout_height="60dp"
            android:layout_weight="1" />

        <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/addMember"
                android:text="Add New Members"
                android:textSize="18sp"
                android:textColor="@android:color/holo_red_dark"
            android:layout_weight="1"
            android:layout_gravity="center_vertical" />
    </LinearLayout>

</LinearLayout>

<Button
    android:text="Leave this group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/leaveGroupButton"
    android:background="@color/colorPrimary"
    android:layout_gravity="bottom|end" />

</LinearLayout>

Body:
You have to make changes in you list view item for this, check this.

Add below lines into Adapter get view method:

    @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            view = LayoutInflater.from(TestListActivity.this).inflate(R.layout.dummy, viewGroup,false);

                    LinearLayout layout =  (LinearLayout)view.findViewById(R.id.add_bottom_ll);
                    if(i==getCount()-1){
                        layout.setVisibility(View.VISIBLE);
                    }else{
                        layout.setVisibility(View.GONE);
                    }
            return view;

        }

List view Item view xml

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

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp">

            <ImageView
                android:id="@+id/profile"
                android:layout_width="72dp"
                android:layout_height="72dp"
                android:src="@drawable/arrow" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/profile"
                android:layout_alignParentTop="true"
                android:layout_marginLeft="10dp"
                android:layout_toRightOf="@id/profile"
                android:gravity="center_vertical"
                android:text="user Name"
                android:textSize="18sp" />
        </RelativeLayout>

        <LinearLayout
            android:id="@+id/add_bottom_ll"
            android:layout_width="363dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="80dp"
                android:layout_height="60dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_weight="1"
                android:src="@drawable/index" />

            <TextView
                android:id="@+id/addMember"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:text="Add New Members"
                android:textColor="@android:color/holo_red_dark"
                android:textSize="18sp" />
        </LinearLayout>

    </LinearLayout>

View(Activity or Fragment) xml:

<LinearLayout 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:orientation="vertical"
        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.thomasbrown.myapplication.MemberActivity"
        android:background="@android:color/white">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/groupID"
            android:textSize="20sp"
            android:layout_marginBottom="15dp" />

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

            <ListView
                android:id="@+id/ListView1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:background="@android:color/white"
                />

        </LinearLayout>

        <Button
            android:text="Leave this group"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/leaveGroupButton"
            android:background="@color/colorPrimary"
            android:layout_gravity="bottom|end" />

    </LinearLayout>


问:
Fastest way to assign item from a list to another item in a list
I've two class which is product and order, please look at the class attribute blow

```<code>public class Product()
{
  public int ProductId { get;set; }
  public string ProductName { get;set; }
  public List<Order> OrderList { get;set; }
}

public class Order()
{
  public int OrderId { get;set; }
  public int ProductId { get;set; }
  public string OrderNumber { get;set; }
  public string OrderDescription { get;set; }
}
</code>```

and i have a separate call to get the data from each of the class

```<code>var productList = ProductService.GetAllProductList();
var orderList = OrderService.GetAllOrderList();
</code>```

What i'm trying to achieve here is that i want to assign order list object to product, i can achieve this by doing like below

```<code>  foreach(var product in productList)
  {
     var selectedOrderList = orderList.Where(x => x.ProductId = product.ProductId).ToList();
     product.OrderList = selectedOrderList;
  }
</code>```

Imaging if my product and order has large amount of data, it could caused some performance issue.

It's because we are doing unnecessary lookup in orderList as some of the order data is already assigned.

Is there any better way to achieve this ?

答:
If you are already returning a list of all orders from the service in orderList... then doing a linq WHERE from a list in memory shouldn't have any performance issues. </p>

<p>Or you change the service to populate product.OrderList before returning it. </p>

Body:
I've two class which is product and order, please look at the class attribute blow

public class Product()
{
  public int ProductId { get;set; }
  public string ProductName { get;set; }
  public List<Order> OrderList { get;set; }
}

public class Order()
{
  public int OrderId { get;set; }
  public int ProductId { get;set; }
  public string OrderNumber { get;set; }
  public string OrderDescription { get;set; }
}

and i have a separate call to get the data from each of the class

var productList = ProductService.GetAllProductList();
var orderList = OrderService.GetAllOrderList();

What i'm trying to achieve here is that i want to assign order list object to product, i can achieve this by doing like below

  foreach(var product in productList)
  {
     var selectedOrderList = orderList.Where(x => x.ProductId = product.ProductId).ToList();
     product.OrderList = selectedOrderList;
  }

Imaging if my product and order has large amount of data, it could caused some performance issue.

It's because we are doing unnecessary lookup in orderList as some of the order data is already assigned.

Is there any better way to achieve this ?

Body:
If you are already returning a list of all orders from the service in orderList... then doing a linq WHERE from a list in memory shouldn't have any performance issues.

Or you change the service to populate product.OrderList before returning it.


问:
301 Redirect Best Practices - multiple sites to single site
I have around 15+ sites, and we want to drop these sites and merge them into only one site (create pages for each one in the new site).

The 15+ site's domains should be redirected to one site as below:

```<code>a.com -> z.com/a
b.com -> z.com/b
c.com -> z.com/c
..
</code>```

Also, we want to redirect (301) page by page from the old domains to the new the new domain to keep the page's ranking:

```<code> a.com/about-us     -> z.com/a/about-us
 b.com/about/abouus -> z.com/b/about-s
 c.com/contactus    -> z.com/c/contact-us
</code>```

Each one of the 15+ sites is running on its own server with a different platform while the new server is IIS.

Currently, I'm thinking of two approaches:

Point the old DNS records to the new server of z.com, and handle all the redirects on the server.

Keep the old site running, and configure redirect rules on each server to redirect each page to the matching page on the new site.

Which approach is better, any other approaches? So far I think the first approach is better since we will control all the redirects in one place - but from the performance wise, is it going to add more headache on the server?

答:
The Scenario

You created a new site and you want to redirect all old sites(15+) to new site (page to page).

All old sites are running in it's own server on different platforms whereas the new one is IIS.

Your options

Point the old DNS records to the new server of z.com, and handle all the redirects on the server.

Advantage

Less cost - you can remove all old sites and the server cost can be saved.

Internal redirection. So, time will be less

Disadvantage

Complex to perform

take care of conflict of similar pages(double check the redirection path)

Keep the old site running, and configure redirect rules on each server to redirect each page to the matching page on the new site

If you can afford the cost of running 15 different sites on 15 servers just to redirect, then only go for this method.

It is just a waste of money and the redirection time will be more.

Body:
I have around 15+ sites, and we want to drop these sites and merge them into only one site (create pages for each one in the new site).

The 15+ site's domains should be redirected to one site as below:

a.com -> z.com/a
b.com -> z.com/b
c.com -> z.com/c
..

Also, we want to redirect (301) page by page from the old domains to the new the new domain to keep the page's ranking:

 a.com/about-us     -> z.com/a/about-us
 b.com/about/abouus -> z.com/b/about-s
 c.com/contactus    -> z.com/c/contact-us

Each one of the 15+ sites is running on its own server with a different platform while the new server is IIS.

Currently, I'm thinking of two approaches:

Point the old DNS records to the new server of z.com, and handle all the redirects on the server.

Keep the old site running, and configure redirect rules on each server to redirect each page to the matching page on the new site.

Which approach is better, any other approaches? So far I think the first approach is better since we will control all the redirects in one place - but from the performance wise, is it going to add more headache on the server?


问:
Filtering a string of unwanted chars in Java
I am looping through hundreds of data entries, most of them valid according to my rules but there are some special characters or unwanted whitespace that must be filtered before the entry is used.

I only want = and , characters to be allowed along with digits and letters. No other special characters. There can be single white spaces but ONLY following a , to separate data.

I am calling a filter method inside a loop:

```<code>private String filterText(String textToBeFiltered) {
    String filteredText = null;

    // Remove all chars apart from = and , with whitespace only allowed
    // after the ,

    return filteredText;
}
</code>```

I am completely new to regex but have been trawling tutorials and would appreciate any ideas.

Thanks!

Frank

答:
You can use the replaceAll method as:

```<code>input = input.replaceAll("[^=,\\da-zA-Z\\s]|(?<!,)\\s","");
</code>```

Ideone Link

The regex used is: [^=,\\da-zA-Z\\s]|(?<!,)\\s which means:

replace any character other than =,
, or a any digit or any letter or
any non-space with "", effectively
deleting it.

Also delete any whitespace but only
if it is not preceded by a ,

Body:
I am looping through hundreds of data entries, most of them valid according to my rules but there are some special characters or unwanted whitespace that must be filtered before the entry is used.

I only want = and , characters to be allowed along with digits and letters. No other special characters. There can be single white spaces but ONLY following a , to separate data.

I am calling a filter method inside a loop:

private String filterText(String textToBeFiltered) {
    String filteredText = null;

    // Remove all chars apart from = and , with whitespace only allowed
    // after the ,

    return filteredText;
}

I am completely new to regex but have been trawling tutorials and would appreciate any ideas.

Thanks!

Frank

Body:
You can use the replaceAll method as:

input = input.replaceAll("[^=,\\da-zA-Z\\s]|(?<!,)\\s","");

Ideone Link

The regex used is: [^=,\\da-zA-Z\\s]|(?<!,)\\s which means:

replace any character other than =,
, or a any digit or any letter or
any non-space with "", effectively
deleting it.

Also delete any whitespace but only
if it is not preceded by a ,


问:
How to delete duplicate records in a table using Orientdb
```<code>Select * from table
cola colb
a     b
a     c
a     b
a     b
</code>```

How to delete duplicate records excluding the first entry in a table.Expected result :

```<code> Select * from table
cola colb
a     b
a     c
</code>```

答: delete from your_table where @rid not in(select first(list(@rid)) from your_table group by cola, colb order by @rid) </p>

Body:
Select * from table
cola colb
a     b
a     c
a     b
a     b

How to delete duplicate records excluding the first entry in a table.Expected result :

 Select * from table
cola colb
a     b
a     c


答:
You can check against all_objects and look in the object_type column like

```<code>select *
  from all_objects
 where object_name like '%PICKUPON%'
</code>```

Title: How to know wheter the given identifier is Stored procedure or Table or View

Body:
Is there anyway to know whether the given identifier is a table or view or a procedure, etc... in oracle?

Example: I have an identifer "PICKUPON", I want to know the object type of this identifier. I took few mins to know it is procedure by browsing in Schema browser in Toad. Is there any query to get this job done.

Body:
You can check against all_objects and look in the object_type column like

select *
  from all_objects
 where object_name like '%PICKUPON%'


问:
Setting DYLD_LIBRARY_PATH on Mac OS X Sierra (CoolProp)
Disclaimer: This question started as a GitHub issue.

Question

I'll put the X question right up front:
Does anyone know a way to set DYLD_LIBRARY_PATH in a way that Excel 2016 will recognize on MacOS Sierra?

The actual problem (Y): How (else) can the developers of CoolProp allow their dynamic library to be used in Excel?

Background

I am trying to get Excel 2016 for Mac to recognize the CoolProp plugin using these instructions, which basically boil down to using this startup.plist:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>my.startup</string>
<key>ProgramArguments</key>
<array>
  <string>sh</string>
  <string>-c</string>
  <string>launchctl setenv DYLD_LIBRARY_PATH "/Users/$USER/Library/Group Containers/UBF8T346G9.Office"</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
</code>```

to set DYLD_LIBRARY_PATH to a location where Excel can access the dynamic library and copying the libCoolProp.dylib file into that same directory. Unfortunately, it appears that due to SIP, one can no longer set any environment variable which starts with DYLD_.

To verify this, I have built a test spreadsheet which contains this VBA function and =ENV("DYLD_LIBRARY_PATH") in cell A1.

```<code>Public Function Env(Value As Variant) As String
    Env = Environ(Value)
End Function
</code>```

I observe this behaviour:

```<code>$ launchctl setenv DYLD_LIBRARY_PATH "/Users/${USER}/Library/Group Containers/UBF8T346G9.Office"
$ launchctl getenv DYLD_LIBRARY_PATH  # empty output
$ launchctl setenv DYLDLIBRARYPATH "/Users/${USER}/Library/Group Containers/UBF8T346G9.Office" # Same kind of thing, but no underscores
$ launchctl getenv DYLDLIBRARYPATH # works fine
/Users/alchemyst/Library/Group Containers/UBF8T346G9.Office
</code>```

After running this sequence of commands in my terminal and restarting Excel, I am able to retrieve the contents of "DYLDLIBRARYPATH" using the test spreadsheet. I have also edited the startup.plist and obtained similar results. I appear to be following all the right steps, but it appears that "DYLD_*" is simply not being set when I call setenv. The result is the same if I do it as root.

So basically I am looking for any way in which I can still use this plugin on the Mac.

Versions: MacOS Sierra (10.12.3), Excel 2016 (15.32), CoolProp 6.10

答:
due to SIP, one can no longer set any environment variable which starts with DYLD_

Yes and no. SIP protects Apple binaries from DYLD_; Microsoft's Excel is not protected by SIP and DYLD_INSERT_LIBRARIES works as expected.

How do we know this?

There's a library, libGMalloc.dylib that can be used to monitor debug allocations of applications. From the terminal, execute the following: -

```<code>DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib /Applications/Microsoft\ Excel.app/Contents/MacOS/Microsoft\ Excel
</code>```

You'll see that Excel is launched and works, though a little slower than usual, due to the overhead of the inserted library that's busy monitoring all memory allocations.

In addition, using Activity Monitor and looking at the Excel process's open files, we can clearly see the libGMalloc.dylib that has been inserted into its process.

I suggest using DYLD_INSERT_LIBRARIES instead of DYLD_LIBRARY_PATH and referencing the Coolprop library from the command line, as demonstrated here.

Body:
Disclaimer: This question started as a GitHub issue.

Question

I'll put the X question right up front:
Does anyone know a way to set DYLD_LIBRARY_PATH in a way that Excel 2016 will recognize on MacOS Sierra?

The actual problem (Y): How (else) can the developers of CoolProp allow their dynamic library to be used in Excel?

Background

I am trying to get Excel 2016 for Mac to recognize the CoolProp plugin using these instructions, which basically boil down to using this startup.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>my.startup</string>
<key>ProgramArguments</key>
<array>
  <string>sh</string>
  <string>-c</string>
  <string>launchctl setenv DYLD_LIBRARY_PATH "/Users/$USER/Library/Group Containers/UBF8T346G9.Office"</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>

to set DYLD_LIBRARY_PATH to a location where Excel can access the dynamic library and copying the libCoolProp.dylib file into that same directory. Unfortunately, it appears that due to SIP, one can no longer set any environment variable which starts with DYLD_.

To verify this, I have built a test spreadsheet which contains this VBA function and =ENV("DYLD_LIBRARY_PATH") in cell A1.

Public Function Env(Value As Variant) As String
    Env = Environ(Value)
End Function

I observe this behaviour:

$ launchctl setenv DYLD_LIBRARY_PATH "/Users/${USER}/Library/Group Containers/UBF8T346G9.Office"
$ launchctl getenv DYLD_LIBRARY_PATH  # empty output
$ launchctl setenv DYLDLIBRARYPATH "/Users/${USER}/Library/Group Containers/UBF8T346G9.Office" # Same kind of thing, but no underscores
$ launchctl getenv DYLDLIBRARYPATH # works fine
/Users/alchemyst/Library/Group Containers/UBF8T346G9.Office

After running this sequence of commands in my terminal and restarting Excel, I am able to retrieve the contents of "DYLDLIBRARYPATH" using the test spreadsheet. I have also edited the startup.plist and obtained similar results. I appear to be following all the right steps, but it appears that "DYLD_*" is simply not being set when I call setenv. The result is the same if I do it as root.

So basically I am looking for any way in which I can still use this plugin on the Mac.

Versions: MacOS Sierra (10.12.3), Excel 2016 (15.32), CoolProp 6.10

Body:
due to SIP, one can no longer set any environment variable which starts with DYLD_

Yes and no. SIP protects Apple binaries from DYLD_; Microsoft's Excel is not protected by SIP and DYLD_INSERT_LIBRARIES works as expected.

How do we know this?

There's a library, libGMalloc.dylib that can be used to monitor debug allocations of applications. From the terminal, execute the following: -

DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib /Applications/Microsoft\ Excel.app/Contents/MacOS/Microsoft\ Excel

You'll see that Excel is launched and works, though a little slower than usual, due to the overhead of the inserted library that's busy monitoring all memory allocations.

In addition, using Activity Monitor and looking at the Excel process's open files, we can clearly see the libGMalloc.dylib that has been inserted into its process.

I suggest using DYLD_INSERT_LIBRARIES instead of DYLD_LIBRARY_PATH and referencing the Coolprop library from the command line, as demonstrated here.


问:
Remove Scriptlet <%some text here%> tags from string in C#
How Can we remove all the scriptlet tags i.e. <% some text here %> from a string. Example string: this is a string <% test text %> containing scriptlet tags <% test text %> how to remove all the tags with the text inside.

答:
You can use regular expressions to achieve this. The Regex.Replace method will do this for you.

```<code>var text = "<% test text %> containing scriptlet tags <% test text %> how to remove all the tags with the text inside.";
var pattern = "<%[^>]*%>";
var regex = new Regex(pattern);
var result = regex.Replace(text, string.Empty);
</code>```

This will result in

containing scriptlet tags  how to remove all the tags with the text inside.

If you want to test and/or learn more about regular expressions have a look at regexr

Body:
You can use regular expressions to achieve this. The Regex.Replace method will do this for you.

var text = "<% test text %> containing scriptlet tags <% test text %> how to remove all the tags with the text inside.";
var pattern = "<%[^>]*%>";
var regex = new Regex(pattern);
var result = regex.Replace(text, string.Empty);

This will result in

containing scriptlet tags  how to remove all the tags with the text inside.

If you want to test and/or learn more about regular expressions have a look at regexr


问:
How to display column name in jquery table?
I want to display my data from SQLite in jquery table. When I run the app in my mobile, it only shows my data from SQLite. The column name is not showing.  How can I display the column name?

table in html

```<code>     <div data-role="main" class="ui-content">
         <table data-role="table" id="mytable" data-mode="reflow">
            <thead>
             <tr>
              <th>ID</th>
              <th>event</th>
              <th>location</th>
             </tr>
            </thead>
            <tbody id="abc"></tbody>
         </table>
    </div>
</code>```

javascript

```<code>function view() {
if (db==null) {
    alert('Error: Database is null.');
    return;
}

db.executeSql(
    'SELECT `id`, `data`, `data2` FROM `info` ORDER BY `data` ASC',
    [],
    function(resultset) {
        var length = resultset.rows.length;
        for(var i=0; i<length; i++) {
            $('#abc').append('<tr><th>'+resultset.rows.item(i).id+'</th>','<td>'+resultset.rows.item(i).data+'</td>','<td>'+resultset.rows.item(i).data2+'</td></tr>');
        }
        //$("#listData").listview( "refresh" );
    },
    function(error) {
        alert('Error: '+error.message);
    }
);
</code>```

答:
Remove the  tag on the appended row.

```<code>db.executeSql(
'SELECT `id`, `data`, `data2` FROM `info` ORDER BY `data` ASC',
[],
function(resultset) {
    var length = resultset.rows.length;
    for(var i=0; i<length; i++) {
        $('#abc').append('<tr><td>'+resultset.rows.item(i).id+'</td>','<td>'+resultset.rows.item(i).data+'</td>','<td>'+resultset.rows.item(i).data2+'</td></tr>');
    }
    //$("#listData").listview( "refresh" );
},
function(error) {
    alert('Error: '+error.message);
}
</code>```

);

Body:
I want to display my data from SQLite in jquery table. When I run the app in my mobile, it only shows my data from SQLite. The column name is not showing.  How can I display the column name?

table in html

              ID
              event
              location

javascript

function view() {
if (db==null) {
    alert('Error: Database is null.');
    return;
}

db.executeSql(
    'SELECT `id`, `data`, `data2` FROM `info` ORDER BY `data` ASC',
    [],
    function(resultset) {
        var length = resultset.rows.length;
        for(var i=0; i<length; i++) {
            $('#abc').append('
'+resultset.rows.item(i).id+'	',''+resultset.rows.item(i).data+'	',''+resultset.rows.item(i).data2+'
');
        }
        //$("#listData").listview( "refresh" );
    },
    function(error) {
        alert('Error: '+error.message);
    }
);

Body:
Remove the  tag on the appended row.

db.executeSql(
'SELECT `id`, `data`, `data2` FROM `info` ORDER BY `data` ASC',
[],
function(resultset) {
    var length = resultset.rows.length;
    for(var i=0; i<length; i++) {
        $('#abc').append('<tr><td>'+resultset.rows.item(i).id+'</td>','<td>'+resultset.rows.item(i).data+'</td>','<td>'+resultset.rows.item(i).data2+'</td></tr>');
    }
    //$("#listData").listview( "refresh" );
},
function(error) {
    alert('Error: '+error.message);
}

);


问:
XSLT: Xpath to count items with attribute value matching another specific sibling
I have the following (simplified; there are more Property-Lines) XML-File that I need to process by XSLT:

```<code><Collection Name="Columns" Type="OutputColumn">
<SubRecord>
    <Property Name="Name">SID</Property>
    <Property Name="SqlType">BigInt</Property>
    <Property Name="Derivation">inputstream1.SID</Property>
    <Property Name="Description">Main key</Property>
</SubRecord>
<SubRecord>
    <Property Name="Name">name</Property>
    <Property Name="SqlType">Char</Property>
    <Property Name="Derivation">inputstream2.name</Property>
    <Property Name="Description">Surname</Property>
</SubRecord>
    <SubRecord>
    <Property Name="Name">street</Property>
    <Property Name="SqlType">Char</Property>
    <Property Name="Derivation">inputstream1.streetname + inputstream1.number</Property>
    <Property Name="Description">Full street</Property>
</SubRecord></Collection>
</code>```

I now need to know two things as a variable in XSLT to decide what to do further in an if-Condition:

Is there at least one SubRecord where substring-after(Derivation, '.') matches the sibling Property "Name" (so like in the first two SubRecords)?

Is there at least one SubRecord where substring-after(Derivation, '.') does not match the sibling Property "Name" (so like in the third SubRecord)?

I tried to do this by Xpath with the Count()-Functionality but simply can't figure out how to do the comparison to the sibling Property node with "Name" as it's name...I'm also open for other ideas if you know an alternative to Count().

答:
I'm not sure I completely understood the issue, so check below and let me know if it's not what you actually want

First can be done with below XPath:

```<code>boolean(//SubRecord[substring-after(./Property[@Name="Derivation"]/text(), '.')=./Property[@Name="Name"]/text()])
</code>```

This should return true because XPath matches first two SubRecord elements.

Using not() should allow to return true because XPath matches third SubRecord element:

```<code>boolean(//SubRecord[not(substring-after(./Property[@Name="Derivation"]/text(), '.')=./Property[@Name="Name"]/text())])
</code>```

Body:
I have the following (simplified; there are more Property-Lines) XML-File that I need to process by XSLT:

<Collection Name="Columns" Type="OutputColumn">
<SubRecord>
    <Property Name="Name">SID</Property>
    <Property Name="SqlType">BigInt</Property>
    <Property Name="Derivation">inputstream1.SID</Property>
    <Property Name="Description">Main key</Property>
</SubRecord>
<SubRecord>
    <Property Name="Name">name</Property>
    <Property Name="SqlType">Char</Property>
    <Property Name="Derivation">inputstream2.name</Property>
    <Property Name="Description">Surname</Property>
</SubRecord>
    <SubRecord>
    <Property Name="Name">street</Property>
    <Property Name="SqlType">Char</Property>
    <Property Name="Derivation">inputstream1.streetname + inputstream1.number</Property>
    <Property Name="Description">Full street</Property>
</SubRecord></Collection>

I now need to know two things as a variable in XSLT to decide what to do further in an if-Condition:

Is there at least one SubRecord where substring-after(Derivation, '.') matches the sibling Property "Name" (so like in the first two SubRecords)?

Is there at least one SubRecord where substring-after(Derivation, '.') does not match the sibling Property "Name" (so like in the third SubRecord)?

I tried to do this by Xpath with the Count()-Functionality but simply can't figure out how to do the comparison to the sibling Property node with "Name" as it's name...I'm also open for other ideas if you know an alternative to Count().

Body:
I'm not sure I completely understood the issue, so check below and let me know if it's not what you actually want

First can be done with below XPath:

boolean(//SubRecord[substring-after(./Property[@Name="Derivation"]/text(), '.')=./Property[@Name="Name"]/text()])

This should return true because XPath matches first two SubRecord elements.

Using not() should allow to return true because XPath matches third SubRecord element:

boolean(//SubRecord[not(substring-after(./Property[@Name="Derivation"]/text(), '.')=./Property[@Name="Name"]/text())])


问:
Database Design: name-value pairs - good or bad?
Say I have an online store wherein each product has a single category (and there are hundreds of categories to choose from) assigned to it (e.g. "book", "portable DVD player", etc.). If I needed to provide descriptive fields for each category (e.g. "author" would be a field for the "book" category), what is the best way to represent this in a database?

Option 1 (name value pairs):

```<code>===========================
 field
===========================
- field_id
- category_id (FK, referring to category like "book")
- name
- value
</code>```

This means I can rely on one table for any category. I'm concerned that the pivoting required to display this data side by side with other books might be a potential problem.

Option 2 (individual tables):

```<code>===========================
 book_field
===========================
- book_field_id
- book_id (FK, referring to the actual book)
- author
- title
- publisher
- date_published
...
</code>```

This means I need a table for each category.

NOTE: not that I think it matters, but the category would be coming from a hierarchy of categories (e.g. Electronics ->  DVD Players -> Portable DVD Players).

答:
I would suggest you to base your design on the one that internet tag are based on.

Let me explain you :

You will need 4 tables more your main object table.

First one : The name tag table, this is a basic table id | name, that will store attribute of object : "author", "size", "weight"; anything that can describe an object

```<code>tag_table
id    varchar(36)
tag   varchar(36)
</code>```

Second one : This table will match the value with the tag names stored in the tag_table value. It does have the same design

```<code>value_table
id    varchar(36)
value varchar(36)
</code>```

Third one : will determine which value is which tag.

```<code>tag_value
id_pair  varchar(36)
id_tag   varchar(36)
id_value varchar(36)
</code>```

Fourth one : will join an Object with its data that carectrize it

```<code>object_tag_value
id_object  varchar(36)
id_pair    varchar(36)
</code>```

And finally your object table.

Implementing hierarchy system :

For the one-to-many or many-to-many hierarchy implement an extra table that would relate the two object :

```<code>object_relation
id_parent varchar(36)
id_son    varchar(36)
</code>```

For the many-to-one (Employee table with manager_id for example) just add the id_parent as a member of your object.

With this schema you will be highly scalable an object can have now an infinite characteristic you are not limited any more. Plus you avoid data redundancy because tags name are unique.

Hope I was clear enough and that it helps you,

Body:
Say I have an online store wherein each product has a single category (and there are hundreds of categories to choose from) assigned to it (e.g. "book", "portable DVD player", etc.). If I needed to provide descriptive fields for each category (e.g. "author" would be a field for the "book" category), what is the best way to represent this in a database?

Option 1 (name value pairs):

===========================
 field
===========================
- field_id
- category_id (FK, referring to category like "book")
- name
- value

This means I can rely on one table for any category. I'm concerned that the pivoting required to display this data side by side with other books might be a potential problem.

Option 2 (individual tables):

===========================
 book_field
===========================
- book_field_id
- book_id (FK, referring to the actual book)
- author
- title
- publisher
- date_published
...

This means I need a table for each category.

NOTE: not that I think it matters, but the category would be coming from a hierarchy of categories (e.g. Electronics ->  DVD Players -> Portable DVD Players).

Body:
I would suggest you to base your design on the one that internet tag are based on.

Let me explain you :

You will need 4 tables more your main object table.

First one : The name tag table, this is a basic table id | name, that will store attribute of object : "author", "size", "weight"; anything that can describe an object

tag_table
id    varchar(36)
tag   varchar(36)

Second one : This table will match the value with the tag names stored in the tag_table value. It does have the same design

value_table
id    varchar(36)
value varchar(36)

Third one : will determine which value is which tag.

tag_value
id_pair  varchar(36)
id_tag   varchar(36)
id_value varchar(36)

Fourth one : will join an Object with its data that carectrize it

object_tag_value
id_object  varchar(36)
id_pair    varchar(36)

And finally your object table.

Implementing hierarchy system :

For the one-to-many or many-to-many hierarchy implement an extra table that would relate the two object :

object_relation
id_parent varchar(36)
id_son    varchar(36)

For the many-to-one (Employee table with manager_id for example) just add the id_parent as a member of your object.

With this schema you will be highly scalable an object can have now an infinite characteristic you are not limited any more. Plus you avoid data redundancy because tags name are unique.

Hope I was clear enough and that it helps you,


问:
Check if an object exists in other objects' sub-objects within an array
I have kind of this Array :

```<code>array = [
     {
      a:0,
      b:{x:1,y:2}
     },
     {
      c:0,
      b:{x:3,y:2}},
    ]
</code>```

And I have a new object like this

```<code>{
 e:0,
 b:{x:2,y:5}
}
</code>```

I want to test whether the objects in array have the same nested b object or not, if so I'll push the new object there, if it already exists, I'll replace the whole object with the newer one.
Any help how could I achieve that please (Lodash, ES6..),
I'm using Typescript btw.

答:
The following  IsExists() retun true if same object already exists and return false if same object not exists.

```<code>function IsExists(YourList,Object ) {
        var i;
        for (i = 0; i < YourList.length; i++) {
            if (YourList[i].c === Object .c && YourList[i].b === Object .b) {
                return true;
            }
        }

        return false;
    }
</code>```

call you function like:

```<code>    var NewObject={
     e:0,
     b:{x:2,y:5}
    }

if (!IsExists(array ,NewObject.b))
{
array .push(NewObject);
}
</code>```

if the IsExists(array ,NewObject.b)return false then push this object into array

Body:
I have kind of this Array :

array = [
     {
      a:0,
      b:{x:1,y:2}
     },
     {
      c:0,
      b:{x:3,y:2}},
    ]

And I have a new object like this

{
 e:0,
 b:{x:2,y:5}
}

I want to test whether the objects in array have the same nested b object or not, if so I'll push the new object there, if it already exists, I'll replace the whole object with the newer one.
Any help how could I achieve that please (Lodash, ES6..),
I'm using Typescript btw.

Body:
The following  IsExists() retun true if same object already exists and return false if same object not exists.

function IsExists(YourList,Object ) {
        var i;
        for (i = 0; i < YourList.length; i++) {
            if (YourList[i].c === Object .c && YourList[i].b === Object .b) {
                return true;
            }
        }

        return false;
    }

call you function like:

    var NewObject={
     e:0,
     b:{x:2,y:5}
    }

if (!IsExists(array ,NewObject.b))
{
array .push(NewObject);
}

if the IsExists(array ,NewObject.b)return false then push this object into array


问:
Laravel 5.3 - How to log all queries on a page?
My team and I are working on a rather big project. There's queries going on everywhere - in controllers, in view composers in views (lazy loading) and probably in some other services as well. It's getting hard to keep a track of it all and the page load speed is fairly slow at the moment.

Where would I put \DB::enableQueryLog() and \DB::getQueryLog() to log ALL the queries and dump them? Basically I'm looking for some place in code that happens before any of the queries happen (to put enableQueryLog()) and I'm looking for a place that happens after the views render (to dump getQueryLog()).

What would be a good way to go about this?

Thanks in advance.

答:
You can add this to the Providers/AppServiceProvider.php file and check them in the laravel log file with tail:

```<code>tail -f storage/logs/laravel.log
</code>```

You can even filter with queries you want to log. For example, here I was using Laravel Passport, and didn't want to log all the oauth queries.

```<code>use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;

public function register() {
    if (App::environment('local') && env('APP_URL') == 'http://localhost') {
        Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
            // filter oauth ones
            if (!str_contains($query->sql, 'oauth')) {
                Log::debug($query->sql . ' - ' . serialize($query->bindings));
            }
        });
    }
}
</code>```

Body:
You can add this to the Providers/AppServiceProvider.php file and check them in the laravel log file with tail:

tail -f storage/logs/laravel.log

You can even filter with queries you want to log. For example, here I was using Laravel Passport, and didn't want to log all the oauth queries.

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;

public function register() {
    if (App::environment('local') && env('APP_URL') == 'http://localhost') {
        Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
            // filter oauth ones
            if (!str_contains($query->sql, 'oauth')) {
                Log::debug($query->sql . ' - ' . serialize($query->bindings));
            }
        });
    }
}


问:
Generate test-jar of unit testing project and use in other maven projects
I created a unit-test maven project as a base project which other project can extend and use Described here. Here is the pom.xml -

```<code><dependencies>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-mockito-release-full</artifactId>
            <version>1.6.4</version>
            <type>pom</type>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</code>```

This generates two jars in target -

unit-test-0.0.1-SNAPSHOT.jar

unit-test-0.0.1-SNAPSHOT-tests.jar

Now, I have some spring boot microservice projects say service-a and service-b which are using another maven project say super-service as dependency. service-a and service-b are using super-service as following declaration in respective services pom.xml -

```<code><dependency>
    <groupId>com.super.service</groupId>
    <artifactId>super-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>
</code>```

I have written unit test for classes in super-service by using above unit-test maven project which is working fine. The pom.xml of super-service is -

```<code><dependency>
    <groupId>com.unit-test</groupId>
    <artifactId>unit-test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <type>test-jar</type>
    <scope>test</scope>
</dependency>
</code>```

But service-a and service-b is not working in same manner. I thought above dependency should get resolved through the base i.e. super-service but it's not and test gets fail. Then I have tried to repeat the same dependency declaration in each services pom.xml but still maven test gets fail.

I tried the other way described in that URL which tells to move source files from src/test/java to src/main/java but that also worked only for super-service project and not for service-a and service-b.

答:
You're doing the wrong thing. You should not run the unit-tests of your dependencies -- if you don't think it can pass its tests you shouldn't be using it.

Only use a dependency when you have evidence that it passed its tests. This is controlled by your CI process which should only put successfully tested binaries in your binary repository. For most people this means that Jenkins should run your tests and if they all pass only then should it put the binary in nexus for you to depend on it. As it does the release to nexus the CI process, through maven, should also update the version number from a snapshot to a release version so that you're never depending on snapshots.

Body:
I created a unit-test maven project as a base project which other project can extend and use Described here. Here is the pom.xml -

<dependencies>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-mockito-release-full</artifactId>
            <version>1.6.4</version>
            <type>pom</type>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

This generates two jars in target -

unit-test-0.0.1-SNAPSHOT.jar

unit-test-0.0.1-SNAPSHOT-tests.jar

Now, I have some spring boot microservice projects say service-a and service-b which are using another maven project say super-service as dependency. service-a and service-b are using super-service as following declaration in respective services pom.xml -

<dependency>
    <groupId>com.super.service</groupId>
    <artifactId>super-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

I have written unit test for classes in super-service by using above unit-test maven project which is working fine. The pom.xml of super-service is -

<dependency>
    <groupId>com.unit-test</groupId>
    <artifactId>unit-test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <type>test-jar</type>
    <scope>test</scope>
</dependency>

But service-a and service-b is not working in same manner. I thought above dependency should get resolved through the base i.e. super-service but it's not and test gets fail. Then I have tried to repeat the same dependency declaration in each services pom.xml but still maven test gets fail.

I tried the other way described in that URL which tells to move source files from src/test/java to src/main/java but that also worked only for super-service project and not for service-a and service-b.


问:
Calling restfull services using powerbuilder
Is it possible to call restfull services in powerbuilder 10.0 ?</p>

答:
You can call restful service by using the following method : </p>

```<code>Long ll_result
String ls_url

OLEObject OLE_url

OLE_url = <rest service URL>
CREATE OLEObject

OLE_url.ConnectToNewObject("WinHttp.WinHttpRequest.5.1")
OLE_url.OPEN("GET", ls_url, FALSE)

OLE_url.Send()
ll_result = Long(OLE_url.ResponseText()) //To get reply from rest service, if any
</code>```

Body:
You can call restful service by using the following method :

Long ll_result
String ls_url

OLEObject OLE_url

OLE_url = <rest service URL>
CREATE OLEObject

OLE_url.ConnectToNewObject("WinHttp.WinHttpRequest.5.1")
OLE_url.OPEN("GET", ls_url, FALSE)

OLE_url.Send()
ll_result = Long(OLE_url.ResponseText()) //To get reply from rest service, if any


答:
In Oracle, you have the system views ALL_OBJECTS, DBA_OBJECTS, USER_OBJECTS  which enable you to query the database schema.

You can query them just like a table, as in

```<code>SELECT OBJECT_TYPE FROM ALL_OBJECTS where OBJECT_NAME = '...'
</code>```

Note that the tree views are a little different, and the results depemnd on the priveleges of user DB user:

USER_OBJECTS shows the current user objects.

ALL_OBJECTS shows all objects of current and those object which you have rights to access.

DBA_OBJECTS shows all object of all users .

Body:
In Oracle, you have the system views ALL_OBJECTS, DBA_OBJECTS, USER_OBJECTS  which enable you to query the database schema.

You can query them just like a table, as in

SELECT OBJECT_TYPE FROM ALL_OBJECTS where OBJECT_NAME = '...'

Note that the tree views are a little different, and the results depemnd on the priveleges of user DB user:

USER_OBJECTS shows the current user objects.

ALL_OBJECTS shows all objects of current and those object which you have rights to access.

DBA_OBJECTS shows all object of all users .


问:
No data found message inside h:dataTable or rich:dataTable?
How do i display a 'No Data Found' message inside a h:dataTable or a rich:dataTable. The header of the table should show the fields say Name, Roll Number and Class; The UI should show the header and a no data found message in the data section of the h:dataTable

Thanks.

答:
That's not possible with h:dataTable or rich:dataTable. The PrimeFaces p:dataTable has an emptyMessage attribute which does exactly that.

Your best bet is to put a message below the table which is rendered when the table is empty. You could use CSS to give it the same style as the table so that it look like part of the table.

```<code><h:dataTable value="#{bean.list}">
    ...
</h:dataTable>
<h:outputText value="Table is empty" rendered="#{empty bean.list}">
</code>```

Body:
That's not possible with h:dataTable or rich:dataTable. The PrimeFaces p:dataTable has an emptyMessage attribute which does exactly that.

Your best bet is to put a message below the table which is rendered when the table is empty. You could use CSS to give it the same style as the table so that it look like part of the table.

<h:dataTable value="#{bean.list}">
    ...
</h:dataTable>
<h:outputText value="Table is empty" rendered="#{empty bean.list}">


问:
OpenCV 3 and SVM training
I already searched for this type of error but I did not find anything similar...

My question is related to opencv3 and SVM. Basically, I have this:

```<code>int labels[2] = {1, -1};
Mat labelsMat(2, 1, CV_32S, labels);
float trainingData[2][2] = { { 501, 10 }, { 255, 10 } };
Mat training_samples(2, 2, CV_64FC1, trainingData);

...

training_samples.convertTo(training_samples, CV_32S);
labelsMat.convertTo(labelsMat, CV_32F);
Ptr<ml::SVM> svm = ml::SVM::create();
svm->setType(ml::SVM::C_SVC);
svm->setKernel(ml::SVM::LINEAR);
svm->setC(1);
svm->train(training_samples, ml::SampleTypes::ROW_SAMPLE, labelsMat);
</code>```

When I compile, I get this error:

OpenCV Error: Bad argument (in the case of classification problem the responses must be categorical; either specify varType when creating TrainData, or pass integer responses) in train, file /home/develop/_Morpheos/opencv/opencv/modules/ml/src/svm.cpp, line 1618 terminate called after throwing an instance of 'cv::Exception' what(): /home/develop/_Morpheos/opencv/opencv/modules/ml/src/svm.cpp:1618: error: (-5) in the case of classification problem the responses must be categorical; either specify varType when creating TrainData, or pass integer responses in function train

I tried almost everything but I do not catch the error.

Could you help me?

答:
CV_64F means double, but you need float, i.e. CV_32F. Use:

```<code>// Change me!
Mat training_samples(2, 2, CV_32FC1, trainingData);
</code>```

Also there's no need to convert to integer type, so you can remove the line:

```<code>// Remove me!
training_samples.convertTo(training_samples, CV_32S);
</code>```

And labels should be of integer type in classification, so remove also:

```<code>// Remove me!
labelsMat.convertTo(labelsMat, CV_32F);
</code>```

You can look here for a complete example.

Title: OpenCV 3 and SVM training

Body:
I already searched for this type of error but I did not find anything similar...

My question is related to opencv3 and SVM. Basically, I have this:

int labels[2] = {1, -1};
Mat labelsMat(2, 1, CV_32S, labels);
float trainingData[2][2] = { { 501, 10 }, { 255, 10 } };
Mat training_samples(2, 2, CV_64FC1, trainingData);

...

training_samples.convertTo(training_samples, CV_32S);
labelsMat.convertTo(labelsMat, CV_32F);
Ptr<ml::SVM> svm = ml::SVM::create();
svm->setType(ml::SVM::C_SVC);
svm->setKernel(ml::SVM::LINEAR);
svm->setC(1);
svm->train(training_samples, ml::SampleTypes::ROW_SAMPLE, labelsMat);

When I compile, I get this error:

OpenCV Error: Bad argument (in the case of classification problem the responses must be categorical; either specify varType when creating TrainData, or pass integer responses) in train, file /home/develop/_Morpheos/opencv/opencv/modules/ml/src/svm.cpp, line 1618 terminate called after throwing an instance of 'cv::Exception' what(): /home/develop/_Morpheos/opencv/opencv/modules/ml/src/svm.cpp:1618: error: (-5) in the case of classification problem the responses must be categorical; either specify varType when creating TrainData, or pass integer responses in function train

I tried almost everything but I do not catch the error.

Could you help me?

Body:
CV_64F means double, but you need float, i.e. CV_32F. Use:

// Change me!
Mat training_samples(2, 2, CV_32FC1, trainingData);

Also there's no need to convert to integer type, so you can remove the line:

// Remove me!
training_samples.convertTo(training_samples, CV_32S);

And labels should be of integer type in classification, so remove also:

// Remove me!
labelsMat.convertTo(labelsMat, CV_32F);

You can look here for a complete example.


问:
How to call a AWS Lambda outside of AWS
This is a quite basic question, but I was unable to find it out: How can I call a lambda via https without using an EC2 instance or something similar which has to run 24/7. So that I can call my method from an App, via CURL or what every tool which supports http.

I found some references to some Gateway APIs, but I don't know how to call them. Also do I need to setup some access permissions? Can I setup also access control or do I need to implement that within the lambda?

答:
AWS doesn't care where your code is running, when you access its APIs.

The service endpoints are all accessible via the Internet.

There's nothing magical about accessing the APIs from "inside," because that isn't what you're doing, in the most logical sense, when you run code on EC2.

Technically speaking, the API requests always go out to the Internet.  If you are accessing an AWS service within the same AWS region, your requests still logically go out to the Internet, even though the traffic between your application and the API endpoint never actually leaves the AWS IP infrastructure... but if you have an EC2 instance that can't access the Internet, then it can't access the service API endpoints, either.

(One exception exists  if you have an S3 VPC endpoint configured, but this is something you have to configure, and it only allows access to S3 buckets within the same region).

The same code, without modification, should work from inside and outside.

Title: How to call a AWS Lambda outside of AWS


问:
How to convert an Int32 array pointer to an Int8_t array pointer?
Any idea.
I tried this:

```<code>int *p = (int*)malloc(N*sizeof(int));
...//set the value of p
int8_t *q = reinterpret_cast<int8_t *>(p);
</code>```

But it doesn't work. I want to get the result q to be
continuous. But the result shows that, if p has 4 elements:{1,2,3,4,5,6,7,8}, Then q would be {1,0,0,0,2,0,0,0}

答:
You cast a pointer of one type to a pointer of another type. You're basically only assign a pointer to another pointer. That's it.

There is no copying of the data the first pointer is pointing to. There is no modification of the data the first pointer is pointing to. After the assignment you will have two different pointers both pointing to the exact same data.

Something like this:

```
+---+
| p | --\
+---+    \     +------------------------------+
          >--> | 32-bit integer data here ... |
+---+    /     +------------------------------+
| q | --/
+---+
```

As for why the 32-bit integer 1 is resulting in the four bytes 1, 0, 0 and 0, first remember that 1 as a 32-bit integer is equal to 0x00000001, i.e. three bytes of zeroes and a byte with the value 1. That the zeroes and one seems reversed is because of you being on a little-endian system.

Body:
Any idea.
I tried this:

int *p = (int*)malloc(N*sizeof(int));
...//set the value of p
int8_t *q = reinterpret_cast<int8_t *>(p);

But it doesn't work. I want to get the result q to be
continuous. But the result shows that, if p has 4 elements:{1,2,3,4,5,6,7,8}, Then q would be {1,0,0,0,2,0,0,0}

Body:
You cast a pointer of one type to a pointer of another type. You're basically only assign a pointer to another pointer. That's it.

There is no copying of the data the first pointer is pointing to. There is no modification of the data the first pointer is pointing to. After the assignment you will have two different pointers both pointing to the exact same data.

Something like this:

+---+
| p | --\
+---+    \     +------------------------------+
          >--> | 32-bit integer data here ... |
+---+    /     +------------------------------+
| q | --/
+---+

As for why the 32-bit integer 1 is resulting in the four bytes 1, 0, 0 and 0, first remember that 1 as a 32-bit integer is equal to 0x00000001, i.e. three bytes of zeroes and a byte with the value 1. That the zeroes and one seems reversed is because of you being on a little-endian system.


问:
Looping inside an object
I had encountered something unclear to me in the for loop:

```<code>var info = {
"full_name" : "John Doe",
"title" : "FrontEnd",
"links" : {
    "blog"     : "JohnDoe.com",
    "facebook" : "http://facebook.com/JohnDoe",
        "youtube"  : "http://www.youtube.com/JohnDoe",
        "twitter"  : "http://twitter.com/JohnDoe"
    }
};
</code>```

I'm looping through this object with this loop:

```<code>var output = "";

for (var key in info.links ) {
    if (info.links.hasOwnProperty(key)) {
        output += '<li>' +
        '<a href = "' + info.links[key] +
        '">' + key + '</a>' +
        '</li>';
        console.log(key);
    }
}
var update = document.getElementById('links');
update.innerHTML = output;
</code>```

And my question is, what is var key in this loop and why it works when there is no var key in scope of this loop? In this case var key becomes blog, facebook etc. inside info.links object. But why?

答:
Look this for a sample solution. The key represents the keys of the info.links object say blog, facebook etc, thus info.links[key] represents the value i.e,

```<code>info.links["blog"] = "JohnDoe.com",
info.links["facebook"] = "http://facebook.com/JohnDoe"
</code>```

Hope this is clear.

Look this link for loop description

Title: Looping inside an object

Body:
I had encountered something unclear to me in the for loop:

var info = {
"full_name" : "John Doe",
"title" : "FrontEnd",
"links" : {
    "blog"     : "JohnDoe.com",
    "facebook" : "http://facebook.com/JohnDoe",
        "youtube"  : "http://www.youtube.com/JohnDoe",
        "twitter"  : "http://twitter.com/JohnDoe"
    }
};

I'm looping through this object with this loop:

var output = "";

for (var key in info.links ) {
    if (info.links.hasOwnProperty(key)) {
        output += '
' +
        '' + key + '' +
        '
';
        console.log(key);
    }
}
var update = document.getElementById('links');
update.innerHTML = output;

And my question is, what is var key in this loop and why it works when there is no var key in scope of this loop? In this case var key becomes blog, facebook etc. inside info.links object. But why?

Body:
Look this for a sample solution. The key represents the keys of the info.links object say blog, facebook etc, thus info.links[key] represents the value i.e,

info.links["blog"] = "JohnDoe.com",
info.links["facebook"] = "http://facebook.com/JohnDoe"

Hope this is clear.

Look this link for loop description


问:
JavaFx on Eclipse, impossibility loading .fxml
I have created a new JavaFX project,and I can comfortably run.

Main:

```<code>package application;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            BorderPane root = new BorderPane();
            Scene scene = new Scene(root,400,400);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

If I try to copy and paste some my old .fxml I receive some error.

The fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.BorderPane?>

<BorderPane prefHeight="691.0" prefWidth="668.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.ControllerStart">

      <Pane prefHeight="599.0" prefWidth="668.0" BorderPane.alignment="CENTER">
         <children>

            <CheckBox fx:id="CB_smcProblem" disable="true" layoutX="206.0" layoutY="211.0" mnemonicParsing="false" text="problem" />
            <CheckBox fx:id="CB_smcCheck" disable="true" layoutX="205.0" layoutY="242.0" mnemonicParsing="false" text="check" />
            <CheckBox fx:id="CB_smc" layoutX="72.0" layoutY="221.0" mnemonicParsing="false" onAction="#SMC_click" text="SMC" />
            <CheckBox fx:id="CB_sketch" layoutX="72.0" layoutY="330.0" mnemonicParsing="false" text="Sketch" />
            <CheckBox fx:id="CB_sketchProblem" disable="true" layoutX="206.0" layoutY="320.0" mnemonicParsing="false" text="problem" />
            <CheckBox fx:id="CB_sketchCheck" disable="true" layoutX="206.0" layoutY="351.0" mnemonicParsing="false" text="check" />
            <CheckBox fx:id="CB_configuration" layoutX="72.0" layoutY="457.0" mnemonicParsing="false" text="Configuration" />
            <CheckBox fx:id="CB_configurationProblem" disable="true" layoutX="207.0" layoutY="447.0" mnemonicParsing="false" text="problem" />
            <CheckBox fx:id="CB_configurationCheck" disable="true" layoutX="207.0" layoutY="478.0" mnemonicParsing="false" text="check" />
            <Button fx:id="B_closed" disable="true" layoutX="249.0" layoutY="591.0" mnemonicParsing="false" text="Closed">

            </Button>
            <CheckBox fx:id="CB_supportH" layoutX="366.0" layoutY="221.0" mnemonicParsing="false" text="Support on helicopter" />
            <CheckBox fx:id="CB_qualityS" layoutX="364.0" layoutY="291.0" mnemonicParsing="false" text="Quality support " />
            <CheckBox fx:id="CB_releaseD" layoutX="365.0" layoutY="362.0" mnemonicParsing="false" text="Release of documents" />
            <CheckBox fx:id="CB_other" layoutX="368.0" layoutY="515.0" mnemonicParsing="false" text="Other" />
            <TextField fx:id="TF_other" editable="false" layoutX="483.0" layoutY="510.0" prefHeight="31.0" prefWidth="136.0" />
            <CheckBox fx:id="CB_requestC" layoutX="364.0" layoutY="426.0" mnemonicParsing="false" text="Request ciclie" />
            <Button layoutX="112.0" layoutY="613.0" mnemonicParsing="false" onAction="#SMC_click" text="Button" />
         </children>
      </Pane>

</BorderPane>
```

<p>This is the modification of main file:</p>

```        ...
        BorderPane root = new BorderPane(); //old part
        root= FXMLLoader.load(getClass().getResource("Start.fxml")); //new part
        Scene scene = new Scene(root,400,400); //old part
        ...
```

<p>I have also added a class ControllerStart.java.</p>

<p>This is my error when i run the project now:</p>

```javafx.fxml.LoadException: /C:/eclipse/workspace/neon/TAP1/bin/application/Start.fxml:47

  at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
  at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
  at application.Main.start(Main.java:15)
  at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
  at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
  at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
  at java.security.AccessController.doPrivileged(Native Method)
  at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
  at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
  at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
  at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
  at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: Can not set java.awt.TextField field application.ControllerStart.TF_other to javafx.scene.control.TextField
  at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
  at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
  at sun.reflect.UnsafeObjectFieldAccessorImpl.set(Unknown Source)
  at java.lang.reflect.Field.set(Unknown Source)
  at javafx.fxml.FXMLLoader.injectFields(FXMLLoader.java:1163)
  at javafx.fxml.FXMLLoader.access$1600(FXMLLoader.java:103)
  at javafx.fxml.FXMLLoader$ValueElement.processValue(FXMLLoader.java:857)
  at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:751)
  at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
... 17 more
```

答:
The error line which is helpful for you is:

```<code>at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException:
Can not set java.awt.TextField field application.ControllerStart.TF_other to javafx.scene.control.TextField
</code>```

Basically you have a field in your controller called TF_other which is an AWT TextField annotated with @FXML. You're probably mistakenly importing java.awt.TextField when you should be importing javafx.scene.control.TextField.

So funnily enough all of the code you posted is irrelevant and the code you didn't post is where the error is.

Body:
I have created a new JavaFX project,and I can comfortably run.

Main:

package application;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            BorderPane root = new BorderPane();
            Scene scene = new Scene(root,400,400);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

If I try to copy and paste some my old .fxml I receive some error.

The fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.BorderPane?>

<BorderPane prefHeight="691.0" prefWidth="668.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.ControllerStart">

      <Pane prefHeight="599.0" prefWidth="668.0" BorderPane.alignment="CENTER">
         <children>

            <CheckBox fx:id="CB_smcProblem" disable="true" layoutX="206.0" layoutY="211.0" mnemonicParsing="false" text="problem" />
            <CheckBox fx:id="CB_smcCheck" disable="true" layoutX="205.0" layoutY="242.0" mnemonicParsing="false" text="check" />
            <CheckBox fx:id="CB_smc" layoutX="72.0" layoutY="221.0" mnemonicParsing="false" onAction="#SMC_click" text="SMC" />
            <CheckBox fx:id="CB_sketch" layoutX="72.0" layoutY="330.0" mnemonicParsing="false" text="Sketch" />
            <CheckBox fx:id="CB_sketchProblem" disable="true" layoutX="206.0" layoutY="320.0" mnemonicParsing="false" text="problem" />
            <CheckBox fx:id="CB_sketchCheck" disable="true" layoutX="206.0" layoutY="351.0" mnemonicParsing="false" text="check" />
            <CheckBox fx:id="CB_configuration" layoutX="72.0" layoutY="457.0" mnemonicParsing="false" text="Configuration" />
            <CheckBox fx:id="CB_configurationProblem" disable="true" layoutX="207.0" layoutY="447.0" mnemonicParsing="false" text="problem" />
            <CheckBox fx:id="CB_configurationCheck" disable="true" layoutX="207.0" layoutY="478.0" mnemonicParsing="false" text="check" />
            <Button fx:id="B_closed" disable="true" layoutX="249.0" layoutY="591.0" mnemonicParsing="false" text="Closed">

            </Button>
            <CheckBox fx:id="CB_supportH" layoutX="366.0" layoutY="221.0" mnemonicParsing="false" text="Support on helicopter" />
            <CheckBox fx:id="CB_qualityS" layoutX="364.0" layoutY="291.0" mnemonicParsing="false" text="Quality support " />
            <CheckBox fx:id="CB_releaseD" layoutX="365.0" layoutY="362.0" mnemonicParsing="false" text="Release of documents" />
            <CheckBox fx:id="CB_other" layoutX="368.0" layoutY="515.0" mnemonicParsing="false" text="Other" />
            <TextField fx:id="TF_other" editable="false" layoutX="483.0" layoutY="510.0" prefHeight="31.0" prefWidth="136.0" />
            <CheckBox fx:id="CB_requestC" layoutX="364.0" layoutY="426.0" mnemonicParsing="false" text="Request ciclie" />
            <Button layoutX="112.0" layoutY="613.0" mnemonicParsing="false" onAction="#SMC_click" text="Button" />
         </children>
      </Pane>

</BorderPane>

This is the modification of main file:

        ...
        BorderPane root = new BorderPane(); //old part
        root= FXMLLoader.load(getClass().getResource("Start.fxml")); //new part
        Scene scene = new Scene(root,400,400); //old part
        ...

I have also added a class ControllerStart.java.

This is my error when i run the project now:

javafx.fxml.LoadException: /C:/eclipse/workspace/neon/TAP1/bin/application/Start.fxml:47

  at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
  at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
  at application.Main.start(Main.java:15)
  at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
  at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
  at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
  at java.security.AccessController.doPrivileged(Native Method)
  at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
  at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
  at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
  at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
  at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: Can not set java.awt.TextField field application.ControllerStart.TF_other to javafx.scene.control.TextField
  at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
  at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
  at sun.reflect.UnsafeObjectFieldAccessorImpl.set(Unknown Source)
  at java.lang.reflect.Field.set(Unknown Source)
  at javafx.fxml.FXMLLoader.injectFields(FXMLLoader.java:1163)
  at javafx.fxml.FXMLLoader.access$1600(FXMLLoader.java:103)
  at javafx.fxml.FXMLLoader$ValueElement.processValue(FXMLLoader.java:857)
  at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:751)
  at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
  at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
... 17 more

Body:
The error line which is helpful for you is:

at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException:
Can not set java.awt.TextField field application.ControllerStart.TF_other to javafx.scene.control.TextField

Basically you have a field in your controller called TF_other which is an AWT TextField annotated with @FXML. You're probably mistakenly importing java.awt.TextField when you should be importing javafx.scene.control.TextField.

So funnily enough all of the code you posted is irrelevant and the code you didn't post is where the error is.


问:
How to get access to the current request and route in Flask and check if it's ajax or not?
I have the following route:

```<code>@app.route("/my_page")
@app.route("/my_page.json")
def targets():

  # .....
</code>```

I want to return an html template if it's a simple http request, and json if it's an ajax request and the route ends with ".json". How can I determine that? I've tried accessing "request" but it was none.

```<code>*** NameError: name 'request' is not defined
</code>```

答:
As noted in the documentation, you need to import the request before you can use it.</p>

```<code>from flask import request

...
def targets():
    if request.is_xhr():
        ...
</code>```

Body:
I have the following route:

@app.route("/my_page")
@app.route("/my_page.json")
def targets():

  # .....

I want to return an html template if it's a simple http request, and json if it's an ajax request and the route ends with ".json". How can I determine that? I've tried accessing "request" but it was none.

*** NameError: name 'request' is not defined

Body:
As noted in the documentation, you need to import the request before you can use it.

from flask import request

...
def targets():
    if request.is_xhr():
        ...