问:
Ruby Exceptions -- Why "else"?
I'm trying to understand exceptions in Ruby but I'm a little confused.  The tutorial I'm using says that if an exception occurs that does not match any of the exceptions identified by the rescue statements, you can use an "else" to catch it:

```<code>begin
# -
rescue OneTypeOfException
# -
rescue AnotherTypeOfException
# -
else
# Other exceptions
ensure
# Always will be executed
end
</code>```

However, I also saw later in the tutorial "rescue" being used without an exception specified:

```<code>begin
    file = open("/unexistant_file")
    if file
         puts "File opened successfully"
    end
rescue
    file = STDIN
end
print file, "==", STDIN, "\n"
</code>```

If you can do this, then do I ever need to use else?  Or can I just use a generic rescue at the end like this?

```<code>begin
# -
rescue OneTypeOfException
# -
rescue AnotherTypeOfException
# -
rescue
# Other exceptions
ensure
# Always will be executed
end
</code>```

答:
Thanks to else you sometimes can merge two nested begin end blocks.

So (simplified example from my current code) instead of:

```<code>  begin
    html = begin
      NetHTTPUtils.request_data url
    rescue NetHTTPUtils::Error => e
      raise unless 503 == e.code
      sleep 60
      retry
    end
    redo unless html["market"]
  end
</code>```

you write:

```<code>  begin
    html = NetHTTPUtils.request_data url
  rescue NetHTTPUtils::Error => e
    raise unless 503 == e.code
    sleep 60
    retry
  else
    redo unless html["market"]
  end
</code>```

Title: Ruby Exceptions -- Why "else"?

Body:
I'm trying to understand exceptions in Ruby but I'm a little confused.  The tutorial I'm using says that if an exception occurs that does not match any of the exceptions identified by the rescue statements, you can use an "else" to catch it:

begin
# -
rescue OneTypeOfException
# -
rescue AnotherTypeOfException
# -
else
# Other exceptions
ensure
# Always will be executed
end

However, I also saw later in the tutorial "rescue" being used without an exception specified:

begin
    file = open("/unexistant_file")
    if file
         puts "File opened successfully"
    end
rescue
    file = STDIN
end
print file, "==", STDIN, "\n"

If you can do this, then do I ever need to use else?  Or can I just use a generic rescue at the end like this?

begin
# -
rescue OneTypeOfException
# -
rescue AnotherTypeOfException
# -
rescue
# Other exceptions
ensure
# Always will be executed
end

Body:
Thanks to else you sometimes can merge two nested begin end blocks.

So (simplified example from my current code) instead of:

  begin
    html = begin
      NetHTTPUtils.request_data url
    rescue NetHTTPUtils::Error => e
      raise unless 503 == e.code
      sleep 60
      retry
    end
    redo unless html["market"]
  end

you write:

  begin
    html = NetHTTPUtils.request_data url
  rescue NetHTTPUtils::Error => e
    raise unless 503 == e.code
    sleep 60
    retry
  else
    redo unless html["market"]
  end


来源: stackexchange

问:
ArrayList inside for-loop for ngx image gallery
this.imageDataPoints is my dynamic ArrayList, and I want to set the media_url property to  this.galleryImages = [
          {
            small: '',
            medium: '',
            big: '',
          }
        ];

please help me to bind this using loop or any other solution.

```<code>this.imageDataPoints = [
   {
      "user_id":11,
      "media_type":"IMAGE",
      "media_uri":"https://www.googleapis.com/download/storage/v1/b/dev_platform_media_ingest/o/155%2Ftemp_photo.png?generation=1512207708761660&alt=media",
      "media_name":"155/temp_photo.png"
   },
   {
      "user_id":43,
      "media_type":"IMAGE",
      "media_uri":"https://www.googleapis.com/download/storage/v1/b/dev_platform_ingest_media/o/155%2FKendall%20Jenner.jfif?generation=1511847043169272&alt=media",
      "media_name":"155/Kendall Jenner.jfif"
   },
   {
      "user_id":11,
      "media_type":"IMAGE",
      "media_uri":"https://www.googleapis.com/download/storage/v1/b/dev_platform_media_ingest/o/155%2Fmaxres.jpg?generation=1512207530832065&alt=media",
      "media_name":"155/maxres.jpg"
   },
   {
      "user_id":43,
      "media_type":"IMAGE",
      "media_uri":"https://www.googleapis.com/download/storage/v1/b/dev_platform_ingest_media/o/155%2Fmaxres.jpg?generation=1511869575663768&alt=media",
      "media_name":"155/maxres.jpg"
   },
   {
      "user_id":11,
      "media_type":"IMAGE",
      "media_uri":"https://www.googleapis.com/download/storage/v1/b/dev_platform_media_ingest/o/155%2FFacebook%20Cover%20-%20Untitled.jpg?generation=1512490205942447&alt=media",
      "media_name":"155/Facebook Cover - Untitled.jpg"
   },
   {
      "user_id":43,
      "media_type":"IMAGE",
      "media_uri":"https://www.googleapis.com/download/storage/v1/b/dev_platform_ingest_media/o/155%2FKendall%20Jenner.jpg?generation=1511869598503407&alt=media",
      "media_name":"155/Kendall Jenner.jpg"
   }
]
</code>```

答:
As far as i understand your Question a simple forEach (MDN-Link) would be enough.

  this.imageDataPoints.forEach((picture, index) => {
     picture.media_uri = this.galleryImages[index];
  });
```

Plunker: https://plnkr.co/edit/AiTTBuWliNaev3AXksYJ?p=preview

Please correct me, if i understood the Question wrong and give more Detail about it.

ContentLicense: CC BY-SA 3.0

Body:
this.imageDataPoints is my dynamic ArrayList, and I want to set the media_url property to  this.galleryImages = [
          {
            small: '',
            medium: '',
            big: '',
          }
        ];

please help me to bind this using loop or any other solution.

this.imageDataPoints = [
   {
      "user_id":11,
      "media_type":"IMAGE",
      "media_uri":"https://www.googleapis.com/download/storage/v1/b/dev_platform_media_ingest/o/155%2Ftemp_photo.png?generation=1512207708761660&alt=media",
      "media_name":"155/temp_photo.png"
   },
   {
      "user_id":43,
      "media_type":"IMAGE",
      "media_uri":"https://www.googleapis.com/download/storage/v1/b/dev_platform_ingest_media/o/155%2FKendall%20Jenner.jfif?generation=1511847043169272&alt=media",
      "media_name":"155/Kendall Jenner.jfif"
   },
   {
      "user_id":11,
      "media_type":"IMAGE",
      "media_uri":"https://www.googleapis.com/download/storage/v1/b/dev_platform_media_ingest/o/155%2Fmaxres.jpg?generation=1512207530832065&alt=media",
      "media_name":"155/maxres.jpg"
   },
   {
      "user_id":43,
      "media_type":"IMAGE",
      "media_uri":"https://www.googleapis.com/download/storage/v1/b/dev_platform_ingest_media/o/155%2Fmaxres.jpg?generation=1511869575663768&alt=media",
      "media_name":"155/maxres.jpg"
   },
   {
      "user_id":11,
      "media_type":"IMAGE",
      "media_uri":"https://www.googleapis.com/download/storage/v1/b/dev_platform_media_ingest/o/155%2FFacebook%20Cover%20-%20Untitled.jpg?generation=1512490205942447&alt=media",
      "media_name":"155/Facebook Cover - Untitled.jpg"
   },
   {
      "user_id":43,
      "media_type":"IMAGE",
      "media_uri":"https://www.googleapis.com/download/storage/v1/b/dev_platform_ingest_media/o/155%2FKendall%20Jenner.jpg?generation=1511869598503407&alt=media",
      "media_name":"155/Kendall Jenner.jpg"
   }
]

Body:
As far as i understand your Question a simple forEach (MDN-Link) would be enough.

  this.imageDataPoints.forEach((picture, index) => {
     picture.media_uri = this.galleryImages[index];
  });

Plunker: https://plnkr.co/edit/AiTTBuWliNaev3AXksYJ?p=preview

Please correct me, if i understood the Question wrong and give more Detail about it.


问:
What is Crystal's Char::Reader defined as a Struct and not a Class?
Char::Reader is defined in the standard library as a Struct. What was the reasoning behind choosing a Struct instead of a Class?

答:
I think that was choosen for performance reasons. According to the docs:

A struct is mostly used for performance reasons to avoid lots of small memory allocations when passing small copies might be more efficient.

So how do you choose between a struct and a class? The rule of thumb is that if no instance variable is ever reassigned, i.e. your type is immutable, you could use a struct, otherwise use a class.

Char::Reader is mutable (because has instance variables reassigned), but it seems to be safe enough to do what the compiler internals do even if reader is a struct:

```<code>reader = Char::Reader.new(pattern)
while reader.has_next?
  char = reader.current_char
  reader = check_char reader, char
  reader.next_char
end
</code>```

Body:
I think that was choosen for performance reasons. According to the docs:

A struct is mostly used for performance reasons to avoid lots of small memory allocations when passing small copies might be more efficient.

So how do you choose between a struct and a class? The rule of thumb is that if no instance variable is ever reassigned, i.e. your type is immutable, you could use a struct, otherwise use a class.

Char::Reader is mutable (because has instance variables reassigned), but it seems to be safe enough to do what the compiler internals do even if reader is a struct:

reader = Char::Reader.new(pattern)
while reader.has_next?
  char = reader.current_char
  reader = check_char reader, char
  reader.next_char
end


问:
Batch File to copy folders from a text file to another directory
I am trying to create a batch file to read off a text file and copy the folder with the files to another directory:

```<code>set dest=f:\Test
for /f %%i in (C:\dirs.txt) do copy "%%i" %dest%
</code>```

When I run this batch file, only the files copy.  I want to copy the folders with the files.

IE folder\files to destination\folder\files.

答:
The solutions above seem to copy the directory contents to the root of the destination. And have problems with folders that have spaces in them.
try the lines below to solve that...

```<code>set dest=e:\Test
for /f "delims=" %%i in (folders.txt) do xcopy "%%i\*" "%dest%\%%i\*" /E /F /Y

/E also copies empty subdirectories
/F lists the full filenames to copies (for debugging purposes)
/Y answers questions with yes.
</code>```

Directories that don't exist will be created with this command and it will overwrite files when they exist in the destination.

The delims= part makes sure that the directories read from the textfiles can contain spaces

Body:
I am trying to create a batch file to read off a text file and copy the folder with the files to another directory:

set dest=f:\Test
for /f %%i in (C:\dirs.txt) do copy "%%i" %dest%

When I run this batch file, only the files copy.  I want to copy the folders with the files.

IE folder\files to destination\folder\files.

Body:
The solutions above seem to copy the directory contents to the root of the destination. And have problems with folders that have spaces in them.
try the lines below to solve that...

set dest=e:\Test
for /f "delims=" %%i in (folders.txt) do xcopy "%%i\*" "%dest%\%%i\*" /E /F /Y

/E also copies empty subdirectories
/F lists the full filenames to copies (for debugging purposes)
/Y answers questions with yes.

Directories that don't exist will be created with this command and it will overwrite files when they exist in the destination.

The delims= part makes sure that the directories read from the textfiles can contain spaces


问:
function issue in appcelerator titanium
In My app i am calling function like below but toJSDate function not invoked. What is the problem can anyone tell why.

In console i get only getIssueProgress Called.

Below i am sharing code.

```<code>function toJSDate(){
      Ti.API.info('getIssueProgress Called');
}
function getIssueProgress() {
    Ti.API.info('getIssueProgress Called');
    var check_Date = toJSDate('anil');
}
</code>```

答:
your toJSDate() doesn't expect a parameters but your calling it with a parameter var check_Date = toJSDate('anil');. Remove 'anil':

function toJSDate(){
    console.log('toJSDate');
   //Ti.API.info('getIssueProgress Called');
}
function getIssueProgress() {
    console.log('getIssueProgress');
    //Ti.API.info('getIssueProgress Called');
    var check_Date = toJSDate();//not: toJSDate('anil');
}

getIssueProgress();```
</div>
</div>
</p>

<p>If you do want to pass that parameter you need to add it to the function declaration</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//add parameter here
function toJSDate(param){
    console.log('toJSDate');
    console.log(param);
   //Ti.API.info('getIssueProgress Called');
}
function getIssueProgress() {
    console.log('getIssueProgress');
    //Ti.API.info('getIssueProgress Called');
    var check_Date = toJSDate('anil');
}

getIssueProgress();</code>```

Title: function issue in appcelerator titanium

Body:
In My app i am calling function like below but toJSDate function not invoked. What is the problem can anyone tell why.

In console i get only getIssueProgress Called.

Below i am sharing code.

function toJSDate(){
      Ti.API.info('getIssueProgress Called');
}
function getIssueProgress() {
    Ti.API.info('getIssueProgress Called');
    var check_Date = toJSDate('anil');
}

Body:
your toJSDate() doesn't expect a parameters but your calling it with a parameter var check_Date = toJSDate('anil');. Remove 'anil':

function toJSDate(){
    console.log('toJSDate');
   //Ti.API.info('getIssueProgress Called');
}
function getIssueProgress() {
    console.log('getIssueProgress');
    //Ti.API.info('getIssueProgress Called');
    var check_Date = toJSDate();//not: toJSDate('anil');
}

getIssueProgress();

If you do want to pass that parameter you need to add it to the function declaration

//add parameter here
function toJSDate(param){
    console.log('toJSDate');
    console.log(param);
   //Ti.API.info('getIssueProgress Called');
}
function getIssueProgress() {
    console.log('getIssueProgress');
    //Ti.API.info('getIssueProgress Called');
    var check_Date = toJSDate('anil');
}

getIssueProgress();


问:
Entity Framework if statement inside select
I have a problem in generating an Entity Framework query and not okay with linq style one :.....

This is my attempt:

```<code>var query = db.table
              .Where(x => x.colA == 1)
              .GroupBy(x => new {x.min,x.max})
              .Select(y => if(y.key.min==0 && y.key.max==0)
                              { " unchanged " }
                           else
                              { y.key.min.tostring()+" "+y.key.max.tostring() })
              .ToList()
</code>```

I want to get "unchanged" string, if both value ofmin and max are zero, otherwise concat them

答:
Apparently all elements in your table have properties min and max

After GroupBy(x=> new {x.min,x.max}) you'll have a sequence of groups, where each group has a key {min, max}, all elements in the group have this value for their min and max properties.

After the GroupBy, you take every group, and from every group you'll select exactly one string. You get rid of the element of the group.

The string that you select depends on the key of the group: if the key = {0, 0} you select the string "unchanged", else you select the string:

```<code>y.key.min.tostring()+" "+y.key.max.tostring()
</code>```

The result is a list of strings, something like:

```<code> "3 7",
 "4 10,
 "unchanged",
 "2 8",
</code>```

Are you sure you want this?

In that case you won't need the GroupBy. Distinct will be simpler and faster

```<code>List<string> result = db.table
   .Where(tableRow => tableRow.colA == 1)
   .Select(tableRow => tableRow.min==0 && tableRow.max==0
         ? " unchanged "
         : tableRow.min.tostring()+" "+tableRow.max.tostring())
   // from here you have a sequence of strings
   // get rid of duplicates:
   .Distinct()
   .ToList();
</code>```

Body:
I have a problem in generating an Entity Framework query and not okay with linq style one :.....

This is my attempt:

var query = db.table
              .Where(x => x.colA == 1)
              .GroupBy(x => new {x.min,x.max})
              .Select(y => if(y.key.min==0 && y.key.max==0)
                              { " unchanged " }
                           else
                              { y.key.min.tostring()+" "+y.key.max.tostring() })
              .ToList()

I want to get "unchanged" string, if both value ofmin and max are zero, otherwise concat them

Body:
Apparently all elements in your table have properties min and max

After GroupBy(x=> new {x.min,x.max}) you'll have a sequence of groups, where each group has a key {min, max}, all elements in the group have this value for their min and max properties.

After the GroupBy, you take every group, and from every group you'll select exactly one string. You get rid of the element of the group.

The string that you select depends on the key of the group: if the key = {0, 0} you select the string "unchanged", else you select the string:

y.key.min.tostring()+" "+y.key.max.tostring()

The result is a list of strings, something like:

 "3 7",
 "4 10,
 "unchanged",
 "2 8",

Are you sure you want this?

In that case you won't need the GroupBy. Distinct will be simpler and faster

List<string> result = db.table
   .Where(tableRow => tableRow.colA == 1)
   .Select(tableRow => tableRow.min==0 && tableRow.max==0
         ? " unchanged "
         : tableRow.min.tostring()+" "+tableRow.max.tostring())
   // from here you have a sequence of strings
   // get rid of duplicates:
   .Distinct()
   .ToList();


问:
How can I close an android DrawerLayout when touched outside of it?
I have created a DrawerLayout and it works fine. But I want it to close when the user touches the background. This can be implemented with a DrawerLayout with listView but here i'm using a NavigationView. So is there a way to accomplish this?

Here is the menu layout for the NavigationView

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/home" android:title="Home Parent" android:icon="@drawable/ic_home_black"/>
    <item android:id="@+id/send" android:title="Send" android:icon="@drawable/ic_send_black"/>
    <item android:id="@+id/add" android:title="Add" android:icon="@drawable/ic_add_black"/>
</menu>
</code>```

Here is the java code

```<code>public class ParentActivity extends AppCompatActivity {

    private NavigationView mNavigationView;
    private User mCurrentUser;
    private UserLocalStore mUserLocalStore;
    private CircleImageView mProfilePic;
    private TextView mProfileName;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;

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

        mUserLocalStore = new UserLocalStore(this);
        mCurrentUser = mUserLocalStore.getUserDetails();

        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
        mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mNavigationView = (NavigationView)findViewById(R.id.navigationView);
        setNavigationViewMenu(mCurrentUser.userType);
        mProfileName = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.profileName);
        mProfileName.setText(mCurrentUser.getName());
        mProfilePic = (CircleImageView) mNavigationView.getHeaderView(0).findViewById(R.id.circleImageProfile);
        Picasso.with(this).load("https://www.sonypark360.net/wp-content/uploads/2017/08/profile-pictures.png").into(mProfilePic);

        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                mDrawerLayout.closeDrawers();
                return false;
            }
        });

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(mToggle.onOptionsItemSelected(item)){
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setNavigationViewMenu(String userType) {
        switch (userType){
            case "s":
                mNavigationView.inflateMenu(R.menu.menu_student_navigation_drawer);
                break;
            case "pa":
                mNavigationView.inflateMenu(R.menu.menu_parent_navigation_drawer);
                break;
            case "pr":
                mNavigationView.inflateMenu(R.menu.menu_principal_navigation_drawer);
                break;
            case "t":
                mNavigationView.inflateMenu(R.menu.menu_teacher_navigation_drawer);
                break;
        }
    }
}
</code>```

Here is the DrawerLayout code

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mlpj.www.morascorpions.ParentActivity">

    <android.support.design.widget.NavigationView
        android:id="@+id/navigationView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/navigation_header_layout"

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

I have also looked into this question, but it does not solve my problem

答:
Try this</p>

```<code>@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    Rect viewRect = new Rect();
    mNavigationView.getGlobalVisibleRect(viewRect);

    if (!viewRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {

        //hide your navigation view here.

    }
    return super.dispatchTouchEvent(ev);;
}
</code>```

Body:
I have created a DrawerLayout and it works fine. But I want it to close when the user touches the background. This can be implemented with a DrawerLayout with listView but here i'm using a NavigationView. So is there a way to accomplish this?

Here is the menu layout for the NavigationView

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/home" android:title="Home Parent" android:icon="@drawable/ic_home_black"/>
    <item android:id="@+id/send" android:title="Send" android:icon="@drawable/ic_send_black"/>
    <item android:id="@+id/add" android:title="Add" android:icon="@drawable/ic_add_black"/>
</menu>

Here is the java code

public class ParentActivity extends AppCompatActivity {

    private NavigationView mNavigationView;
    private User mCurrentUser;
    private UserLocalStore mUserLocalStore;
    private CircleImageView mProfilePic;
    private TextView mProfileName;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;

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

        mUserLocalStore = new UserLocalStore(this);
        mCurrentUser = mUserLocalStore.getUserDetails();

        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
        mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mNavigationView = (NavigationView)findViewById(R.id.navigationView);
        setNavigationViewMenu(mCurrentUser.userType);
        mProfileName = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.profileName);
        mProfileName.setText(mCurrentUser.getName());
        mProfilePic = (CircleImageView) mNavigationView.getHeaderView(0).findViewById(R.id.circleImageProfile);
        Picasso.with(this).load("https://www.sonypark360.net/wp-content/uploads/2017/08/profile-pictures.png").into(mProfilePic);

        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                mDrawerLayout.closeDrawers();
                return false;
            }
        });

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(mToggle.onOptionsItemSelected(item)){
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setNavigationViewMenu(String userType) {
        switch (userType){
            case "s":
                mNavigationView.inflateMenu(R.menu.menu_student_navigation_drawer);
                break;
            case "pa":
                mNavigationView.inflateMenu(R.menu.menu_parent_navigation_drawer);
                break;
            case "pr":
                mNavigationView.inflateMenu(R.menu.menu_principal_navigation_drawer);
                break;
            case "t":
                mNavigationView.inflateMenu(R.menu.menu_teacher_navigation_drawer);
                break;
        }
    }
}

Here is the DrawerLayout code

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mlpj.www.morascorpions.ParentActivity">

    <android.support.design.widget.NavigationView
        android:id="@+id/navigationView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/navigation_header_layout"

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

I have also looked into this question, but it does not solve my problem

Body:
Try this

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    Rect viewRect = new Rect();
    mNavigationView.getGlobalVisibleRect(viewRect);

    if (!viewRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {

        //hide your navigation view here.

    }
    return super.dispatchTouchEvent(ev);;
}


问:
How to get param values from deeplinks
I open my app with a deeplink

```<code>myscheme://?param1=value1&param2=value2
</code>```

How can I get the value of the parameters? I found different posts that treat this subject but the once I tried works on http links I think, I alwayse get a warning telling me that BlobURL object is not supported yet.

```<code>var url = new URL(data);
alert(url.searchParams.get("param1"));
</code>```

答:
I have tried your example, and it works, with slight adjustment:

```<code>let myscheme = 'http://www.example.com/?param1=value1&param2=value2'
var url = new URL(myscheme);
alert(url.searchParams.get("param1"));
</code>```

More details can be found here.

Title: How to get param values from deeplinks

Body:
I open my app with a deeplink

myscheme://?param1=value1&param2=value2

How can I get the value of the parameters? I found different posts that treat this subject but the once I tried works on http links I think, I alwayse get a warning telling me that BlobURL object is not supported yet.

var url = new URL(data);
alert(url.searchParams.get("param1"));

Body:
I have tried your example, and it works, with slight adjustment:

let myscheme = 'http://www.example.com/?param1=value1&param2=value2'
var url = new URL(myscheme);
alert(url.searchParams.get("param1"));

More details can be found here.


问:
How to get my own ICultureSelector implementation injected in the framework
I have implemented my version of ICultureSelector, in a custom module.
Here it is a part of its definition (my question is not about the logic to select the culture; I tried with my own namespace and also with a namespace same as the namespace used in the module Orchard.Localization):

```<code>namespace Orchard.Localization.Selectors
{
    [OrchardFeature("Orchard.Localization.CultureSelector")]
    public class ShortRouteCultureSelector : ICultureSelector
    {
        public CultureSelectorResult GetCulture(HttpContextBase context)
        {
            ...
</code>```

I put a breakpoint in the method GetCurrentCulture of the class CurrentCultureWorkContext in the Orchard.Framework project, and I see that the variable IEnumerable _cultureSelectors contains all the implementation of ICultureSelector of the module Orchard.Localization but not my implementation, that is never used.

What am I missing?

答: Remove the OrchardFeature attribute or define your own feature name as Orchard.Localization.CultureSelector is defined in Orchard.Localization module already.

Body:
I have implemented my version of ICultureSelector, in a custom module.
Here it is a part of its definition (my question is not about the logic to select the culture; I tried with my own namespace and also with a namespace same as the namespace used in the module Orchard.Localization):

namespace Orchard.Localization.Selectors
{
    [OrchardFeature("Orchard.Localization.CultureSelector")]
    public class ShortRouteCultureSelector : ICultureSelector
    {
        public CultureSelectorResult GetCulture(HttpContextBase context)
        {
            ...

I put a breakpoint in the method GetCurrentCulture of the class CurrentCultureWorkContext in the Orchard.Framework project, and I see that the variable IEnumerable _cultureSelectors contains all the implementation of ICultureSelector of the module Orchard.Localization but not my implementation, that is never used.

What am I missing?


问:
unhashable type: 'list' in printing Tensorflow vector
I am printing vector and matrix of Tensorflow. It prints scalar but shows error for vector, Matrix and Tensor

Code goes below:

```<code>import tensorflow as tf
scalar = tf.constant([2])
vector = tf.constant([3,4,5])
Matrix = tf.constant([1,2,3],[4,5,6],[7,8,9])
Tensor = tf.constant([ [[1,2,3],[4,5,6],[7,8,9]],
                       [[1,2,3],[4,5,6],[7,8,9]],
                       [[1,2,3],[4,5,6],[7,8,9]] ])
with tf.Session() as session:
    result = session.run(scalar)
    print (result)
    result = session.run(vector)
    print (result)
    result = session.run(Matrix)
    print (result)
    result = session.run(Tensor)
    print (result)
</code>```

I get the following error:

```<code>TypeError: unhashable type: 'list'
</code>```

How can I resolve this?

答:
You have an error with your 4th statement:
Use

```<code>Matrix = tf.constant([ [1,2,3],[4,5,6],[7,8,9] ])
#                    ^ extra parenthesis here
</code>```

instead of

```<code>Matrix = tf.constant([1,2,3],[4,5,6],[7,8,9])
</code>```

Body:
I am printing vector and matrix of Tensorflow. It prints scalar but shows error for vector, Matrix and Tensor

Code goes below:

import tensorflow as tf
scalar = tf.constant([2])
vector = tf.constant([3,4,5])
Matrix = tf.constant([1,2,3],[4,5,6],[7,8,9])
Tensor = tf.constant([ [[1,2,3],[4,5,6],[7,8,9]],
                       [[1,2,3],[4,5,6],[7,8,9]],
                       [[1,2,3],[4,5,6],[7,8,9]] ])
with tf.Session() as session:
    result = session.run(scalar)
    print (result)
    result = session.run(vector)
    print (result)
    result = session.run(Matrix)
    print (result)
    result = session.run(Tensor)
    print (result)

I get the following error:

TypeError: unhashable type: 'list'

How can I resolve this?

Body:
You have an error with your 4th statement:
Use

Matrix = tf.constant([ [1,2,3],[4,5,6],[7,8,9] ])
#                    ^ extra parenthesis here

instead of

Matrix = tf.constant([1,2,3],[4,5,6],[7,8,9])


问:
Bootstrap cells with equal height
I have the following

```<code><div class="row">
  <div class="col-md-6">
    <div class = "box-cell">
      <p>
        Slightly short text
      </p>
    </div>
  </div>
  <div class="col-md-6">
    <div class = "box-cell">
      <p>
        Text that<br>literally<br>spans<br>4 lines
      </p>
    </div>
  </div>
</div>
</code>```

and css

```<code>.box-cell
{
    position:        relative;
    margin:          3px;
    border-style:    groove ridge ridge groove;
    border-width:    3px;
    background-size: cover;
}
</code>```

So the problem that I am facing is that one of the cells is usually taller than the other.IS there any way for me to equalize how much height each cell takes up?
Searching didn't yield me which property I can manipulate to get same height :(

Here is jsfiddle
However in this fiddle I can not get them to be side by side to prove my point

EDIT: I guess I didn't specify it properly. I would like to have the borders be as tall as the tallest cell. So all the examples provided here actually take out the borders and instead color the background. If I do that then yes it gives illusion of every cell being the same, but I would like there to be a border of same height.

答:
```<code><style type="text/css">
.box-cell{
    position:        relative;
    margin:          3px;
    border-style:    groove ridge ridge groove;
    border-width:    3px;
    background-size: cover;
}
</style>
<div class="row">
  <div class="col-md-6">
    <div class = "box-cell">
      <p>
        Slightly short text
      </p>
    </div>
  </div>
  <div class="col-md-6">
    <div class = "box-cell">
      <p>
        <span>Text that</span>
        <span>literally</span>
        <span>s4 lines</span>
        <span>ygthfg</span>
      </p>
    </div>
  </div>
</div>
</code>```

1- you need to add text in span tag.
2- Or take text in one line .

Title: Bootstrap cells with equal height

Body:
I have the following

        Slightly short text

        Text that
literally
spans
4 lines

and css

.box-cell
{
    position:        relative;
    margin:          3px;
    border-style:    groove ridge ridge groove;
    border-width:    3px;
    background-size: cover;
}

So the problem that I am facing is that one of the cells is usually taller than the other.IS there any way for me to equalize how much height each cell takes up?
Searching didn't yield me which property I can manipulate to get same height :(

Here is jsfiddle
However in this fiddle I can not get them to be side by side to prove my point

EDIT: I guess I didn't specify it properly. I would like to have the borders be as tall as the tallest cell. So all the examples provided here actually take out the borders and instead color the background. If I do that then yes it gives illusion of every cell being the same, but I would like there to be a border of same height.

Body:
<style type="text/css">
.box-cell{
    position:        relative;
    margin:          3px;
    border-style:    groove ridge ridge groove;
    border-width:    3px;
    background-size: cover;
}
</style>
<div class="row">
  <div class="col-md-6">
    <div class = "box-cell">
      <p>
        Slightly short text
      </p>
    </div>
  </div>
  <div class="col-md-6">
    <div class = "box-cell">
      <p>
        <span>Text that</span>
        <span>literally</span>
        <span>s4 lines</span>
        <span>ygthfg</span>
      </p>
    </div>
  </div>
</div>

1- you need to add text in span tag.
2- Or take text in one line .


问:
Error: [react-native-router-flux] unique key should be defined
```<code>    import React from 'react';
    import { Scene, Router,Actions } from 'react-native-router-flux';
    import LoginForm from '../src/LoginForm';
    import EmployeeList from '../src/EmployeeList'
    import EmployeeCreate from '../src/EmployeeCreate'

    const RouterComponent=()=>{
        return(
            <Router sceneStyle={{paddingTop:55}}>

                    <Scene
                        key="Login"
                        component={LoginForm}
                        title='Login' />
                    <Scene
                        key="EmployeeList"
                        component={EmployeeList}
                        title='EmployeeList'
                        rightTitle="ADD"
                        onRight={()=>console.log("error")}  />
                    <Scene
                        Key="EmployeeCreate"
                        component={EmployeeCreate}
                        title='Employee'  />

            </Router>
        );

    export default RouterComponent;
</code>```

<p>hi guys im getting this error while use router flux for navigation and when i add a third scene just like in the code it shows this error </p>

答: hi the thing worked when i updated the router flux to 4.0.0</p>

Body:
    import React from 'react';
    import { Scene, Router,Actions } from 'react-native-router-flux';
    import LoginForm from '../src/LoginForm';
    import EmployeeList from '../src/EmployeeList'
    import EmployeeCreate from '../src/EmployeeCreate'

    const RouterComponent=()=>{
        return(
            <Router sceneStyle={{paddingTop:55}}>

                    <Scene
                        key="Login"
                        component={LoginForm}
                        title='Login' />
                    <Scene
                        key="EmployeeList"
                        component={EmployeeList}
                        title='EmployeeList'
                        rightTitle="ADD"
                        onRight={()=>console.log("error")}  />
                    <Scene
                        Key="EmployeeCreate"
                        component={EmployeeCreate}
                        title='Employee'  />

            </Router>
        );

    export default RouterComponent;

hi guys im getting this error while use router flux for navigation and when i add a third scene just like in the code it shows this error


问:
AngularJS: Escape HTML in input fields
What is the best way to escape HTML in the input field? For example, I've search input field

```<code><input id="search" type="text" ng-model="search" placeholder="search...">
</code>```

And I want to escape if somebody types something like this:

```<code><script>alert("test123");</script>
</code>```

答:
You could use pattern for your input box like -

```<code><input type='text' pattern='[a-zA-Z0-9]+'>
</code>```

Use an expression that best suits your needs.

Title: AngularJS: Escape HTML in input fields

Body:
What is the best way to escape HTML in the input field? For example, I've search input field

<input id="search" type="text" ng-model="search" placeholder="search...">

And I want to escape if somebody types something like this:

Body:
You could use pattern for your input box like -

<input type='text' pattern='[a-zA-Z0-9]+'>

Use an expression that best suits your needs.


问:
How do I write a java method to accept click?
I am creating methods for Selenium testing.  How do I write methods that I can use click?

Example

Class.Method(somethingVariable).click()

I know how to make class and method but how do I make .click()

```<code>public class MyClass{

    public static void newMethod(String strName) {
        --------
    }
}
</code>```

I want to do MyClass.newMethod("something")**.click()**or MyClass.newMethod("something")**.attr("html")**etc

答:
It all depends on what are you trying to do. What you can do is called method chaining. The problem is, you are trying to use static method which is not applicable for method chaining.

If you REALLY want to use Class.staticMethod().click(); then you would have to do something like this:

```<code>public class MyClass {
    private WebElement element;

    private MyClass(WebElement element) {
        this.element = element;
    }

    public static MyClass newMethod(String str) {
        //do something and THEN pass WebElement you want to click.
        return new MyClass(element);
    }

    public void click() {
        element.click();
    }
}

//usage
public static void main(String[] args) {
    MyClass.newMethod("myString").click();
}
</code>```

There is probably a lot to explain, so please, ask me in comments because I don't know which parts you do or don't understand.

Body:
I am creating methods for Selenium testing.  How do I write methods that I can use click?

Example

Class.Method(somethingVariable).click()

I know how to make class and method but how do I make .click()

public class MyClass{

    public static void newMethod(String strName) {
        --------
    }
}

I want to do MyClass.newMethod("something")**.click()**or MyClass.newMethod("something")**.attr("html")**etc

Body:
It all depends on what are you trying to do. What you can do is called method chaining. The problem is, you are trying to use static method which is not applicable for method chaining.

If you REALLY want to use Class.staticMethod().click(); then you would have to do something like this:

public class MyClass {
    private WebElement element;

    private MyClass(WebElement element) {
        this.element = element;
    }

    public static MyClass newMethod(String str) {
        //do something and THEN pass WebElement you want to click.
        return new MyClass(element);
    }

    public void click() {
        element.click();
    }
}

//usage
public static void main(String[] args) {
    MyClass.newMethod("myString").click();
}

There is probably a lot to explain, so please, ask me in comments because I don't know which parts you do or don't understand.


问:
postgresql case inside function doesn't trigger
So, i have a couple of functions inside my db.

One function needs to run when the data in a specific table is older than 5 minutes.

I've tried doing it with:

```<code>PERFORM case when now() - '5 minutes'::interval > (select end_time from x order by end_route desc limit 1) then update_x() else null end;
</code>```

When i run the command as a regular select query, it runs OK. But when i put that inside another function (The one being called, returns updated table that is no older than 5 minutes), it never runs. Also, if i just put update_x(), then it runs OK (but every time the function is called).

Does anyone have any idea on how i could fix this?
One idea is to just set a cron to run the function every 5 mins independently, but i'd rather the server is idle since the function is quite resource intensive, and it doesn't get called that often.

I'm on version 8.4(Due to my ISP, so can't change, though i am considering moving to VPS, so if this is something that would work on 9.5 and newer, i can wait).

答:
The function now() gives the start time of the current transaction and is invariable inside it. Use clock_timestamp(), example:

```<code>do $$
begin
    for i in 1..3 loop
        perform pg_sleep(1);
        raise notice 'now(): % clock_timestamp(): %', now(), clock_timestamp();
    end loop;
end $$;

NOTICE:  now(): 2017-12-06 10:22:40.422683+01 clock_timestamp(): 2017-12-06 10:22:41.437099+01
NOTICE:  now(): 2017-12-06 10:22:40.422683+01 clock_timestamp(): 2017-12-06 10:22:42.452456+01
NOTICE:  now(): 2017-12-06 10:22:40.422683+01 clock_timestamp(): 2017-12-06 10:22:43.468124+01
</code>```

Per the documentation:

clock_timestamp() returns the actual current time, and therefore its value changes even within a single SQL command (...)

now() is a traditional PostgreSQL equivalent to transaction_timestamp().

Body:
So, i have a couple of functions inside my db.

One function needs to run when the data in a specific table is older than 5 minutes.

I've tried doing it with:

PERFORM case when now() - '5 minutes'::interval > (select end_time from x order by end_route desc limit 1) then update_x() else null end;

When i run the command as a regular select query, it runs OK. But when i put that inside another function (The one being called, returns updated table that is no older than 5 minutes), it never runs. Also, if i just put update_x(), then it runs OK (but every time the function is called).

Does anyone have any idea on how i could fix this?
One idea is to just set a cron to run the function every 5 mins independently, but i'd rather the server is idle since the function is quite resource intensive, and it doesn't get called that often.

I'm on version 8.4(Due to my ISP, so can't change, though i am considering moving to VPS, so if this is something that would work on 9.5 and newer, i can wait).

Body:
The function now() gives the start time of the current transaction and is invariable inside it. Use clock_timestamp(), example:

do $$
begin
    for i in 1..3 loop
        perform pg_sleep(1);
        raise notice 'now(): % clock_timestamp(): %', now(), clock_timestamp();
    end loop;
end $$;

NOTICE:  now(): 2017-12-06 10:22:40.422683+01 clock_timestamp(): 2017-12-06 10:22:41.437099+01
NOTICE:  now(): 2017-12-06 10:22:40.422683+01 clock_timestamp(): 2017-12-06 10:22:42.452456+01
NOTICE:  now(): 2017-12-06 10:22:40.422683+01 clock_timestamp(): 2017-12-06 10:22:43.468124+01

Per the documentation:

clock_timestamp() returns the actual current time, and therefore its value changes even within a single SQL command (...)

now() is a traditional PostgreSQL equivalent to transaction_timestamp().


问:
Trying to read leak summary from valgrind - Program causes a segmentation fault on my PC, not on another
I have a C code OpenGL program that compiles and runs fine on my ubuntu machine. But when I compile and run it on another linux it causes a segmentation fault. I've used valgrind to see where the problem could be and here is a small portion of the output:

```<code>==21294== LEAK SUMMARY:
==21294==    definitely lost: 72 bytes in 1 blocks
==21294==    indirectly lost: 0 bytes in 0 blocks
==21294==      possibly lost: 0 bytes in 0 blocks
==21294==    still reachable: 191,932 bytes in 1,397 blocks
==21294==         suppressed: 0 bytes in 0 blocks
==21294==
==21294== ERROR SUMMARY: 8 errors from 3 contexts (suppressed: 0 from 0)
==21294==
==21294== 1 errors in context 1 of 3:
==21294== Syscall param ioctl(generic) points to uninitialised byte(s)
==21294==    at 0x5936F07: ioctl (syscall-template.S:84)
==21294==    by 0x7C0E0E7: drmIoctl (in /usr/lib/x86_64-linux-gnu/libdrm.so.2.4.0)
==21294==    by 0x7C10DDE: drmCommandWriteRead (in /usr/lib/x86_64-linux-gnu/libdrm.so.2.4.0)
==21294==    by 0xABF2DA0: nouveau_object_mthd (in /usr/lib/x86_64-linux-gnu/libdrm_nouveau.so.2.0.0)
==21294==    by 0xABF3535: nouveau_device_new (in /usr/lib/x86_64-linux-gnu/libdrm_nouveau.so.2.0.0)
==21294==    by 0xA0B9690: nouveau_drm_screen_create (in /usr/lib/x86_64-linux-gnu/dri/nouveau_dri.so)
==21294==    by 0x9C7FD15: ??? (in /usr/lib/x86_64-linux-gnu/dri/nouveau_dri.so)
==21294==    by 0x9F6C59B: ??? (in /usr/lib/x86_64-linux-gnu/dri/nouveau_dri.so)
==21294==    by 0x9F67BD2: ??? (in /usr/lib/x86_64-linux-gnu/dri/nouveau_dri.so)
==21294==    by 0x4E80AA2: ??? (in /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1.2.0)
==21294==    by 0x4E589C3: ??? (in /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1.2.0)
==21294==    by 0x4E53F00: glXQueryVersion (in /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1.2.0)
</code>```

The full output file from valgrind is 15614 lines long.
I'm still learning it but I could use assistance on reading what I'm looking at and how I can correct my code. Also this is my first post on this site, so any info for this question and posting in general would be appreciated.

答:
Segmentation fault has nothing to do with memory leaks. To fix segmentation fault you should read and fix errors reported by Valgrind, not memory leaks. According to output there are 8 errors found by Valgrind:

```<code>==21294== ERROR SUMMARY: 8 errors from 3 contexts (suppressed: 0 from 0)
</code>```

See the difference between Valgrind errors and memory leaks here:

Error summary in Valgrind output?

Body:
I have a C code OpenGL program that compiles and runs fine on my ubuntu machine. But when I compile and run it on another linux it causes a segmentation fault. I've used valgrind to see where the problem could be and here is a small portion of the output:

==21294== LEAK SUMMARY:
==21294==    definitely lost: 72 bytes in 1 blocks
==21294==    indirectly lost: 0 bytes in 0 blocks
==21294==      possibly lost: 0 bytes in 0 blocks
==21294==    still reachable: 191,932 bytes in 1,397 blocks
==21294==         suppressed: 0 bytes in 0 blocks
==21294==
==21294== ERROR SUMMARY: 8 errors from 3 contexts (suppressed: 0 from 0)
==21294==
==21294== 1 errors in context 1 of 3:
==21294== Syscall param ioctl(generic) points to uninitialised byte(s)
==21294==    at 0x5936F07: ioctl (syscall-template.S:84)
==21294==    by 0x7C0E0E7: drmIoctl (in /usr/lib/x86_64-linux-gnu/libdrm.so.2.4.0)
==21294==    by 0x7C10DDE: drmCommandWriteRead (in /usr/lib/x86_64-linux-gnu/libdrm.so.2.4.0)
==21294==    by 0xABF2DA0: nouveau_object_mthd (in /usr/lib/x86_64-linux-gnu/libdrm_nouveau.so.2.0.0)
==21294==    by 0xABF3535: nouveau_device_new (in /usr/lib/x86_64-linux-gnu/libdrm_nouveau.so.2.0.0)
==21294==    by 0xA0B9690: nouveau_drm_screen_create (in /usr/lib/x86_64-linux-gnu/dri/nouveau_dri.so)
==21294==    by 0x9C7FD15: ??? (in /usr/lib/x86_64-linux-gnu/dri/nouveau_dri.so)
==21294==    by 0x9F6C59B: ??? (in /usr/lib/x86_64-linux-gnu/dri/nouveau_dri.so)
==21294==    by 0x9F67BD2: ??? (in /usr/lib/x86_64-linux-gnu/dri/nouveau_dri.so)
==21294==    by 0x4E80AA2: ??? (in /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1.2.0)
==21294==    by 0x4E589C3: ??? (in /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1.2.0)
==21294==    by 0x4E53F00: glXQueryVersion (in /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1.2.0)

The full output file from valgrind is 15614 lines long.
I'm still learning it but I could use assistance on reading what I'm looking at and how I can correct my code. Also this is my first post on this site, so any info for this question and posting in general would be appreciated.

Body:
Segmentation fault has nothing to do with memory leaks. To fix segmentation fault you should read and fix errors reported by Valgrind, not memory leaks. According to output there are 8 errors found by Valgrind:

==21294== ERROR SUMMARY: 8 errors from 3 contexts (suppressed: 0 from 0)

See the difference between Valgrind errors and memory leaks here:

Error summary in Valgrind output?


问:
How to define custom class, title, and target in Link Browser for content elements and the new rte_ckeditor?
Prerequisites

[x] Can you reproduce the problem on TYPO3 8.7 LTS - YES

[x] Did you [perform a cursory search] to see if your bug or enhancement is already reported? -YES

Description

How do I configure default link target, class, and title for the Link Browser in any element link (usually element titles and images) AND in rte_ckeditor in Typo3 8 LTS? I've spent several hours trying to configure it, but no success and no documentation out there. The fields are empty as you can see on the images below.

Steps to Reproduce the problem

Create any element that you can link the title or image.

Click to open the Link Browser

The options come empty for any type of link (Page, File, Folder, External URL, Email).

Expected behavior:
I want to define default classes, link targets and titles for each type of link if they are empty.
For example External URL, I want to automatically populate with target="_blank", class "external-link", title="Link to External Website", if the link wasn't configure previously. Basically for any new link I just want to have it auto populated with my custom values and not empty values.

This used to work for rtehtmlarea only on previous Typo3 versions, but not I'm not able to set this option system wide on Typo3 8 LTS and ckeditor.

The PageTS that used to work only for rtehtmlarea  was something like this:

```<code>RTE {
    classesAnchor {
        externalLink {
            class = external-link
            type = url
            titleText = Opens external link in new window
            target = _blank
            image =
        }
        externalLinkInNewWindow {
            class = external-link-new-window
            type = url
            titleText = Opens external link in new window
            target = _blank
            image =
        }
        internalLink {
            class = internal-link
            type = page
            titleText =  Opens internal link in this window
            target = _top
            image =
        }
        internalLinkInNewWindow {
            class = internal-link-new-window
            type = page
            titleText = Opens internal link in new window
            target = _blank
            image =
        }
        folder {
            class = folder
            type = folder
            titleText =
            target =
            image =
        }
        download {
            class = download
            type = file
            titleText = Initiates file download
            target = _blank
            image =
        }
        mail {
            class = mail
            type = mail
            titleText = Email Address
            image =
        }
    }
}
</code>```

I would like this to work for the new rte_ckeditor as well for any element options that I can link using the Link Browser.

答:
There is a bug in TYPO3 8.7.8 (only) - see: https://forge.typo3.org/issues/82865

[EDIT] the classesAnchor stuff works only in version 8.7.5 to 8.7.7 and will hopefully work again in 8.7.9

But the correct answer whould be (like Ghanshyam Bhava pointed out in his comment) to switch to YAML configuration.

https://typo3worx.eu/2017/02/configure-ckeditor-in-typo3/

```<code># Load default processing options
imports:
    - { resource: "EXT:rte_ckeditor/Configuration/RTE/Default.yaml" }

classesAnchor:

  externalLink:
    class: 'external-link'
    type: 'url'

  downloadLink:
    class: 'download-link'
    type: 'file'

  mailLink:
    class: 'mail-link'
    type: 'mail'

buttons:
  link:
    properties:
      class:
        allowedClasses: 'external-link,download-link,mail-link'
</code>```

Link Browsers for other fields outside RTE should be possible via TCA-Overrides.

Body:
Prerequisites

[x] Can you reproduce the problem on TYPO3 8.7 LTS - YES

[x] Did you [perform a cursory search] to see if your bug or enhancement is already reported? -YES

Description

How do I configure default link target, class, and title for the Link Browser in any element link (usually element titles and images) AND in rte_ckeditor in Typo3 8 LTS? I've spent several hours trying to configure it, but no success and no documentation out there. The fields are empty as you can see on the images below.

Steps to Reproduce the problem

Create any element that you can link the title or image.

Click to open the Link Browser

The options come empty for any type of link (Page, File, Folder, External URL, Email).

Expected behavior:
I want to define default classes, link targets and titles for each type of link if they are empty.
For example External URL, I want to automatically populate with target="_blank", class "external-link", title="Link to External Website", if the link wasn't configure previously. Basically for any new link I just want to have it auto populated with my custom values and not empty values.

This used to work for rtehtmlarea only on previous Typo3 versions, but not I'm not able to set this option system wide on Typo3 8 LTS and ckeditor.

The PageTS that used to work only for rtehtmlarea  was something like this:

RTE {
    classesAnchor {
        externalLink {
            class = external-link
            type = url
            titleText = Opens external link in new window
            target = _blank
            image =
        }
        externalLinkInNewWindow {
            class = external-link-new-window
            type = url
            titleText = Opens external link in new window
            target = _blank
            image =
        }
        internalLink {
            class = internal-link
            type = page
            titleText =  Opens internal link in this window
            target = _top
            image =
        }
        internalLinkInNewWindow {
            class = internal-link-new-window
            type = page
            titleText = Opens internal link in new window
            target = _blank
            image =
        }
        folder {
            class = folder
            type = folder
            titleText =
            target =
            image =
        }
        download {
            class = download
            type = file
            titleText = Initiates file download
            target = _blank
            image =
        }
        mail {
            class = mail
            type = mail
            titleText = Email Address
            image =
        }
    }
}

I would like this to work for the new rte_ckeditor as well for any element options that I can link using the Link Browser.

Body:
There is a bug in TYPO3 8.7.8 (only) - see: https://forge.typo3.org/issues/82865

[EDIT] the classesAnchor stuff works only in version 8.7.5 to 8.7.7 and will hopefully work again in 8.7.9

But the correct answer whould be (like Ghanshyam Bhava pointed out in his comment) to switch to YAML configuration.

https://typo3worx.eu/2017/02/configure-ckeditor-in-typo3/

# Load default processing options
imports:
    - { resource: "EXT:rte_ckeditor/Configuration/RTE/Default.yaml" }

classesAnchor:

  externalLink:
    class: 'external-link'
    type: 'url'

  downloadLink:
    class: 'download-link'
    type: 'file'

  mailLink:
    class: 'mail-link'
    type: 'mail'

buttons:
  link:
    properties:
      class:
        allowedClasses: 'external-link,download-link,mail-link'

Link Browsers for other fields outside RTE should be possible via TCA-Overrides.


问:
Header guards in C++ and C
At LearnCpp.com | 1.10 — A first look at the preprocessor. Under Header guards, there are those code snippets:

add.h:

```<code>#include "mymath.h"
int add(int x, int y);
</code>```

subtract.h:

```<code>#include "mymath.h"
int subtract(int x, int y);
</code>```

main.cpp:

```<code>#include "add.h"
#include "subtract.h"
</code>```

In implementing the header guard, it is mentioned as follows:

```<code>#ifndef ADD_H
#define ADD_H

// your declarations here

#endif
</code>```

What could the declaration be here? And, should int main() come after #endif?

Is adding _H a convention or a must do thing?

Thanks.

答: No, the int main() goes in a .cpp. The declarations are the other stuff you were gonna put in the header. _H is a convention, you can see various header guard conventions around.

ContentLicense: CC BY-SA 4.0

Title: Header guards in C++ and C

Body:
At LearnCpp.com | 1.10 — A first look at the preprocessor. Under Header guards, there are those code snippets:

add.h:

#include "mymath.h"
int add(int x, int y);

subtract.h:

#include "mymath.h"
int subtract(int x, int y);

main.cpp:

#include "add.h"
#include "subtract.h"

In implementing the header guard, it is mentioned as follows:

#ifndef ADD_H
#define ADD_H

// your declarations here

#endif

What could the declaration be here? And, should int main() come after #endif?

Is adding _H a convention or a must do thing?

Thanks.

ContentLicense: CC BY-SA 2.5


问:
Can't add nodes to galera mariadb 10.1 cluster
I'm trying to setup a galera MariaDB 10.1 cluster on Centos 7.
Here is my master configuration:

```<code>[mysqld]

wsrep_cluster_address="gcomm://10.47.246.45,10.47.246.9"
wsrep_node_address="10.47.246.45"
wsrep_node_name='n1'
wsrep_cluster_name='cluster'
innodb_buffer_pool_size=400M
# Mandatory settings to enable Galera
wsrep_provider=/usr/lib/galera/libgalera_smm.so
binlog_format=ROW
default-storage-engine=InnoDB
innodb_autoinc_lock_mode=2
innodb_doublewrite=1
query_cache_size=0
bind-address=0.0.0.0
# Galera synchronisation configuration
wsrep_sst_method=rsync
</code>```

and when I type

```<code>SHOW GLOBAL STATUS LIKE 'wsrep_cluster_size';
</code>```

I get this output

```<code>+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| wsrep_cluster_size | 1     |
+--------------------+-------+
</code>```

Here is the configuration on the node I'm trying to add

[mysqld]

```<code>wsrep_cluster_address="gcomm://10.47.246.45,10.47.246.9"
wsrep_node_address="10.47.246.9"
wsrep_node_name='n2'
wsrep_cluster_name='cluster'
innodb_buffer_pool_size=400M
# Mandatory settings to enable Galera
wsrep_provider=/usr/lib/galera/libgalera_smm.so
binlog_format=ROW
default-storage-engine=InnoDB
innodb_autoinc_lock_mode=2
innodb_doublewrite=1
query_cache_size=0
bind-address=0.0.0.0
# Galera synchronisation configuration
wsrep_sst_method=rsync
</code>```

and mysql service starts without any errors using:

```<code>service mysql start --wsrep-new-cluster
</code>```

and this is the output from

```<code>SHOW GLOBAL STATUS LIKE 'wsrep_cluster_size';
</code>```

I get his output

```<code>+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| wsrep_cluster_size | 0     |
+--------------------+-------+
</code>```

Any idea what could be wrong with my configuration?

答:
First of all I want to suggest to use minimum three nodes in Galera cluster to prevent split braining there.

The correct configuration related to Galera cluster settings for the first host is (the others should have the same template):

```<code>[mysqld]
log_error               = /var/log/mysql/mysql-error.log
default_storage_engine  = InnoDB
binlog_format           = ROW
wsrep_on                = ON
wsrep_provider          = /usr/lib64/galera/libgalera_smm.so
wsrep_cluster_address   = "gcomm://<node1_ip>,<node2_ip>,<node3_ip>"
wsrep_cluster_name      = cluster
wsrep_node_name         = <node1_name>
wsrep_node_address      = <node1_ip>
innodb_autoinc_lock_mod = 2
wsrep_sst_method        = rsync
</code>```

To start Galera cluster just do the following on the first node:

```<code># galera_new_cluster
</code>```

Check that your cluster has been created:

```<code># mysql -e "show status like '%wsrep_cluster%'"
+--------------------------+--------------------------------------+
| Variable_name            | Value                                |
+--------------------------+--------------------------------------+
| wsrep_cluster_conf_id    | 1234                                 |
| wsrep_cluster_size       | 1                                    |
| wsrep_cluster_state_uuid | 020e3d69-2b31-11e7-9723-4b205d7b7e0c |
| wsrep_cluster_status     | Primary                              |
+--------------------------+--------------------------------------+
</code>```

And start MariaDB on the other hosts:

```<code>systemctl start mariadb
</code>```

Nodes should join your Galera cluster.

If it is not working still, follow logs in /var/log/mysql/mysql-error.log

Body:
I'm trying to setup a galera MariaDB 10.1 cluster on Centos 7.
Here is my master configuration:

[mysqld]

wsrep_cluster_address="gcomm://10.47.246.45,10.47.246.9"
wsrep_node_address="10.47.246.45"
wsrep_node_name='n1'
wsrep_cluster_name='cluster'
innodb_buffer_pool_size=400M
# Mandatory settings to enable Galera
wsrep_provider=/usr/lib/galera/libgalera_smm.so
binlog_format=ROW
default-storage-engine=InnoDB
innodb_autoinc_lock_mode=2
innodb_doublewrite=1
query_cache_size=0
bind-address=0.0.0.0
# Galera synchronisation configuration
wsrep_sst_method=rsync

and when I type

SHOW GLOBAL STATUS LIKE 'wsrep_cluster_size';

I get this output

+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| wsrep_cluster_size | 1     |
+--------------------+-------+

Here is the configuration on the node I'm trying to add

[mysqld]

wsrep_cluster_address="gcomm://10.47.246.45,10.47.246.9"
wsrep_node_address="10.47.246.9"
wsrep_node_name='n2'
wsrep_cluster_name='cluster'
innodb_buffer_pool_size=400M
# Mandatory settings to enable Galera
wsrep_provider=/usr/lib/galera/libgalera_smm.so
binlog_format=ROW
default-storage-engine=InnoDB
innodb_autoinc_lock_mode=2
innodb_doublewrite=1
query_cache_size=0
bind-address=0.0.0.0
# Galera synchronisation configuration
wsrep_sst_method=rsync

and mysql service starts without any errors using:

service mysql start --wsrep-new-cluster

and this is the output from

SHOW GLOBAL STATUS LIKE 'wsrep_cluster_size';

I get his output

+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| wsrep_cluster_size | 0     |
+--------------------+-------+

Any idea what could be wrong with my configuration?

Body:
First of all I want to suggest to use minimum three nodes in Galera cluster to prevent split braining there.

The correct configuration related to Galera cluster settings for the first host is (the others should have the same template):

[mysqld]
log_error               = /var/log/mysql/mysql-error.log
default_storage_engine  = InnoDB
binlog_format           = ROW
wsrep_on                = ON
wsrep_provider          = /usr/lib64/galera/libgalera_smm.so
wsrep_cluster_address   = "gcomm://<node1_ip>,<node2_ip>,<node3_ip>"
wsrep_cluster_name      = cluster
wsrep_node_name         = <node1_name>
wsrep_node_address      = <node1_ip>
innodb_autoinc_lock_mod = 2
wsrep_sst_method        = rsync

To start Galera cluster just do the following on the first node:

# galera_new_cluster

Check that your cluster has been created:

# mysql -e "show status like '%wsrep_cluster%'"
+--------------------------+--------------------------------------+
| Variable_name            | Value                                |
+--------------------------+--------------------------------------+
| wsrep_cluster_conf_id    | 1234                                 |
| wsrep_cluster_size       | 1                                    |
| wsrep_cluster_state_uuid | 020e3d69-2b31-11e7-9723-4b205d7b7e0c |
| wsrep_cluster_status     | Primary                              |
+--------------------------+--------------------------------------+

And start MariaDB on the other hosts:

systemctl start mariadb

Nodes should join your Galera cluster.

If it is not working still, follow logs in /var/log/mysql/mysql-error.log


问:
SplashScreen approach defined in xml (without activity) does not appear
I have defined splash screen like many other without external activity, but it doesn't works for me, I don't understand why.

Is there any limitations for images? Also tried for many other images
This is my splash.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:opacity="opaque">
    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/splash_logo" />
    </item>
</layer-list>
</code>```

Here preview for splash.xml file in android studio looks like perfectly.
Than I have created style like that

```<code><style name="AppTheme.Launcher">
    <item name="android:windowBackground">@drawable/splash</item>
</style>
</code>```

and assigned it to activity theme inside manifest

```<code> <activity
        android:theme="@style/AppTheme.Launcher"
        android:name=".MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</code>```

this is my activity's

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    setTheme(R.style.AppTheme)
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}
</code>```

when activity is loaded blank white screen is shown instead of image, maybe for a one second. I searched this approach and seems that it is the same what others were done. Don't understand what's wrong

EDIT:
I have tested it for another device OS 5.0 and it works, but for 6.0 doesn't

答:
EDIT

Remove this from your activity

```<code>setTheme(R.style.AppTheme)
</code>```

Try this

Style.xml

```<code><style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">

        <item name="android:windowBackground">@drawable/splash_background</item>

</style>
</code>```

splash_background.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/colorPrimary" />

    <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_launcher" />
    </item>
</layer-list>
</code>```

SplashActivity

```<code>public class SplashActivity extends AppCompatActivity {

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

        startActivity(new Intent(SplashActivity.this, MainActivity.class));

        // close splash activity

        finish();
    }
}
</code>```

Manifest

```<code><activity android:name=".SplashActivity"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</code>```

Body:
I have defined splash screen like many other without external activity, but it doesn't works for me, I don't understand why.

Is there any limitations for images? Also tried for many other images
This is my splash.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:opacity="opaque">
    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/splash_logo" />
    </item>
</layer-list>

Here preview for splash.xml file in android studio looks like perfectly.
Than I have created style like that

and assigned it to activity theme inside manifest

 <activity
        android:theme="@style/AppTheme.Launcher"
        android:name=".MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

this is my activity's

override fun onCreate(savedInstanceState: Bundle?) {
    setTheme(R.style.AppTheme)
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

when activity is loaded blank white screen is shown instead of image, maybe for a one second. I searched this approach and seems that it is the same what others were done. Don't understand what's wrong

EDIT:
I have tested it for another device OS 5.0 and it works, but for 6.0 doesn't

Body:
EDIT

Remove this from your activity

setTheme(R.style.AppTheme)

Try this

Style.xml

<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">

        <item name="android:windowBackground">@drawable/splash_background</item>

</style>

splash_background.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/colorPrimary" />

    <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_launcher" />
    </item>
</layer-list>

SplashActivity

public class SplashActivity extends AppCompatActivity {

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

        startActivity(new Intent(SplashActivity.this, MainActivity.class));

        // close splash activity

        finish();
    }
}

Manifest

<activity android:name=".SplashActivity"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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


问:
Relative imports in Python 3
I want to import a function from another file in the same directory.

Usually, one of the following works:

```<code>from .mymodule import myfunction
</code>```
```<code>from mymodule import myfunction
</code>```

...but the other one gives me one of these errors:

ImportError: attempted relative import with no known parent package
```
<pre class="lang-none prettyprint-override"><code>ModuleNotFoundError: No module named 'mymodule'
</code>```

SystemError: Parent module '' not loaded, cannot perform relative import
```

Why is this?

答:
To obviate this problem, I devised a solution with the repackage package, which has worked for me for some time. It adds the upper directory to the lib path:

```<code>import repackage
repackage.up()
from mypackage.mymodule import myfunction
</code>```

Repackage can make relative imports that work in a wide range of cases, using an intelligent strategy (inspecting the call stack).

Title: Relative imports in Python 3

Body:
I want to import a function from another file in the same directory.

Usually, one of the following works:

from .mymodule import myfunction

from mymodule import myfunction

...but the other one gives me one of these errors:

ImportError: attempted relative import with no known parent package

ModuleNotFoundError: No module named 'mymodule'

SystemError: Parent module '' not loaded, cannot perform relative import

Why is this?

Body:
To obviate this problem, I devised a solution with the repackage package, which has worked for me for some time. It adds the upper directory to the lib path:

import repackage
repackage.up()
from mypackage.mymodule import myfunction

Repackage can make relative imports that work in a wide range of cases, using an intelligent strategy (inspecting the call stack).


问:
On adding a class, .click does not trigger - Using jQuery
I added a span with a class, but .click does not trigger.

Adding a span class code

```<code>var TA = '<span class="TS" id="'+$('#TT').attr('value')+'" style=" color:#fff; margin-left:5px; font-family:arial; font-size:12px">* '+$('#TT').attr('value')+'</span>';
$('#QLT').append(TA);
</code>```

This adds a span .TS to a div .TX. I want to trigger .TS using .click, the code

```<code>  $('.TS').click(function() {
   alert("ok");

  });
</code>```

But this does not trigger.  What is wrong, Appreciate all assistance.

Thanks
Jean

答:
It looks like your code is working fine.

Maybe when you're clicking, you're not actually clicking on the text in the span. I think that messes things up sometimes, with click handlers.

Body:
I added a span with a class, but .click does not trigger.

Adding a span class code

var TA = '* '+$('#TT').attr('value')+'';
$('#QLT').append(TA);

This adds a span .TS to a div .TX. I want to trigger .TS using .click, the code

  $('.TS').click(function() {
   alert("ok");

  });

But this does not trigger.  What is wrong, Appreciate all assistance.

Thanks
Jean


答:
this completely depends on your use case. If you just want it to escape it for the users view (so basically sanitizing) you can use angular $sanitize & $sce for it

https://docs.angularjs.org/api/ngSanitize/service/$sanitize and https://docs.angularjs.org/api/ng/service/$sce

however if you want to store it somewhere and want it escaped, you can build a filter. You can find an example here: Escape HTML text in an AngularJS directive

Title: AngularJS: Escape HTML in input fields

Body:
What is the best way to escape HTML in the input field? For example, I've search input field

<input id="search" type="text" ng-model="search" placeholder="search...">

And I want to escape if somebody types something like this:


问:
How to get object in jsonarray firebase android?
Structure Firebase data

DetailItemOrderSetGet

I want to get all data in order_detail or one of data inside order_detail like detail_item_id. I always get error force close because order_detail, but how to make looping for that or How is to get one of array object? I just can get for data with one level like order_customer_name or order_date. this is my code. thanks

```<code>mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            processOrderList.clear();
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                    DetailitemOrderSetGet orderDetail = postSnapshot.child("order_detail").getValue(DetailitemOrderSetGet.class);
                        processOrderList.add(postSnapshot.getValue(OrderHistorySetGet.class));

                }
            processAdapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

答:
You don't need to use JSONArray in order to get data from a Firebase database. You can just iterate over the DataSnapshot object using getChildren() method. Assuming that the Transaction node is a direct child of your Firebase database root and you are storing the detail_item_id as an int, to get the value of your detail_item_id from all childrens under order_detail node, please use the following code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference orderDetailRef = rootRef.child("Transaction").child("4").child("order_detail");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            int detail_item_id = ds.child("detail_item_id").getValue(Integer.class);
            Log.d("TAG", detail_item_id);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
orderDetailRef.addListenerForSingleValueEvent(eventListener);
</code>```

Body:
Structure Firebase data

DetailItemOrderSetGet

I want to get all data in order_detail or one of data inside order_detail like detail_item_id. I always get error force close because order_detail, but how to make looping for that or How is to get one of array object? I just can get for data with one level like order_customer_name or order_date. this is my code. thanks

mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            processOrderList.clear();
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                    DetailitemOrderSetGet orderDetail = postSnapshot.child("order_detail").getValue(DetailitemOrderSetGet.class);
                        processOrderList.add(postSnapshot.getValue(OrderHistorySetGet.class));

                }
            processAdapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Body:
You don't need to use JSONArray in order to get data from a Firebase database. You can just iterate over the DataSnapshot object using getChildren() method. Assuming that the Transaction node is a direct child of your Firebase database root and you are storing the detail_item_id as an int, to get the value of your detail_item_id from all childrens under order_detail node, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference orderDetailRef = rootRef.child("Transaction").child("4").child("order_detail");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            int detail_item_id = ds.child("detail_item_id").getValue(Integer.class);
            Log.d("TAG", detail_item_id);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
orderDetailRef.addListenerForSingleValueEvent(eventListener);


问:
how to use varnish-cache behind a proxy
I would like to use Varnish-cache to cache some of the dependancies of my web application, but I am stuck behind a corporate Proxy setup. Is there any way to tell Varnish-cache to make it's http requests to other services through a proxy?

Many thanks

Simon

答:
For varnish4 this does not work. Doing a bit of network tracing, it would appear that varnish v4 does relative req.url, where a proxy needs a absolute req.url
I'm in a split-brain DNS world, so my backend is the same domain-name as the frontend user see (just resovles differently). Therefore i create a absolute URL by using req.http.host in the req.url variable.</p>

```<code>sub vcl_recv {
    # Setting backend hint
    set req.backend_hint = varnish_backend;
    if (req.url !~ "mydomain.com") {
      set req.url ="http://" + req.http.host + req.url;
}
</code>```

Title: how to use varnish-cache behind a proxy

Body:
For varnish4 this does not work. Doing a bit of network tracing, it would appear that varnish v4 does relative req.url, where a proxy needs a absolute req.url
I'm in a split-brain DNS world, so my backend is the same domain-name as the frontend user see (just resovles differently). Therefore i create a absolute URL by using req.http.host in the req.url variable.

sub vcl_recv {
    # Setting backend hint
    set req.backend_hint = varnish_backend;
    if (req.url !~ "mydomain.com") {
      set req.url ="http://" + req.http.host + req.url;
}


问:
Read multiple characteristics from an Android device using library RxAndroidBle
I am using the library RxAndroidBle in order to scan devices and then connect to one specific device and read 4 GATT characteristics.

I can read one characteristic (Battery Level) ith this code :

```<code>scanSubscription = rxBleClient.scanBleDevices(
            new ScanSettings.Builder()
                    .build()
    )
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext(
                    scanResult -> {
                        if(scanResult.getBleDevice().getName() != null){
                            if(scanResult.getBleDevice().getName().equals("NODE 1")){
                                Log.e("BLE SCAN", "SUCCESS");
                                Log.e("BLE SCAN", scanResult.getBleDevice().getName());
                                Log.e("BLE SCAN", scanResult.getBleDevice().getMacAddress());
                                scanSubscription.unsubscribe();

                                RxBleDevice device = scanResult.getBleDevice();
                                subscription = device.establishConnection(false) // <-- autoConnect flag
                                        .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(UUID.fromString("00002a19-0000-1000-8000-00805f9b34fb")))
                                        .subscribe(
                                                characteristicValue -> {
                                                    Log.e("Characteristic", characteristicValue[0]+"");
                                                },
                                                throwable -> {
                                                    Log.e("Error", throwable.getMessage());
                                                }
                                        );
                            }
                        }
                    }
            )
            .subscribe();
</code>```

I can read two by using :

```<code>.flatMap(rxBleConnection -> Observable.combineLatest( // use the same connection and combine latest emissions
                rxBleConnection.readCharacteristic(aUUID),
                rxBleConnection.readCharacteristic(bUUID),
                Pair::new
        ))
</code>```

But I don't understand how to do that with 4 characteristics for example.

Thank you

答:
The above example is just fine you would only need some data object that would accept more values than Pair. For instance something like:

```<code>class ReadResult {
    final byte[] aValue;
    final byte[] bValue;
    final byte[] cValue;
    final byte[] dValue;

    ReadResult(byte[] aValue, byte[] bValue, byte[] cValue, byte[] dValue) {
        this.aValue = aValue;
        this.bValue = bValue;
        this.cValue = cValue;
        this.dValue = dValue;
    }
}
</code>```

And then the example could look like this:

```<code>disposable = rxBleClient.scanBleDevices(
        new ScanSettings.Builder().build(),
        new ScanFilter.Builder().setDeviceName("NODE 1").build() // one can set filtering by name here
)
        .take(1) // take only the first result and then the upstream will get unsubscribed (scan will end)
        .flatMap(scanResult -> scanResult.getBleDevice().establishConnection(false)) // connect to the first scanned device that matches the filter
        .flatMapSingle(rxBleConnection -> Single.zip( // once connected read all needed values
                rxBleConnection.readCharacteristic(aUUID),
                rxBleConnection.readCharacteristic(bUUID),
                rxBleConnection.readCharacteristic(cUUID),
                rxBleConnection.readCharacteristic(dUUID),
                ReadResult::new // merge them into a single result
        ))
        .take(1) // once the result of all reads is available unsubscribe from the upstream (connection will end)
        .subscribe(
                readResult -> Log.d("Characteristics", /* print the readResult */),
                throwable -> Log.e("Error", throwable.getMessage())
        );
</code>```

Original/Legacy solution for RxAndroidBle based on RxJava1:

```<code>subscription = rxBleClient.scanBleDevices(
        new ScanSettings.Builder().build(),
        new ScanFilter.Builder().setDeviceName("NODE 1").build() // one can set filtering by name here
)
        .take(1) // take only the first result and then the upstream will get unsubscribed (scan will end)
        .flatMap(scanResult -> scanResult.getBleDevice().establishConnection(false)) // connect to the first scanned device that matches the filter
        .flatMap(rxBleConnection -> Observable.combineLatest( // once connected read all needed values
                rxBleConnection.readCharacteristic(aUUID),
                rxBleConnection.readCharacteristic(bUUID),
                rxBleConnection.readCharacteristic(cUUID),
                rxBleConnection.readCharacteristic(dUUID),
                ReadResult::new // merge them into a single result
        ))
        .take(1) // once the result of all reads is available unsubscribe from the upstream (connection will end)
        .subscribe(
                readResult -> Log.d("Characteristics", /* print the readResult */),
                throwable -> Log.e("Error", throwable.getMessage())
        );
</code>```

Body:
I am using the library RxAndroidBle in order to scan devices and then connect to one specific device and read 4 GATT characteristics.

I can read one characteristic (Battery Level) ith this code :

scanSubscription = rxBleClient.scanBleDevices(
            new ScanSettings.Builder()
                    .build()
    )
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext(
                    scanResult -> {
                        if(scanResult.getBleDevice().getName() != null){
                            if(scanResult.getBleDevice().getName().equals("NODE 1")){
                                Log.e("BLE SCAN", "SUCCESS");
                                Log.e("BLE SCAN", scanResult.getBleDevice().getName());
                                Log.e("BLE SCAN", scanResult.getBleDevice().getMacAddress());
                                scanSubscription.unsubscribe();

                                RxBleDevice device = scanResult.getBleDevice();
                                subscription = device.establishConnection(false) // <-- autoConnect flag
                                        .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(UUID.fromString("00002a19-0000-1000-8000-00805f9b34fb")))
                                        .subscribe(
                                                characteristicValue -> {
                                                    Log.e("Characteristic", characteristicValue[0]+"");
                                                },
                                                throwable -> {
                                                    Log.e("Error", throwable.getMessage());
                                                }
                                        );
                            }
                        }
                    }
            )
            .subscribe();

I can read two by using :

.flatMap(rxBleConnection -> Observable.combineLatest( // use the same connection and combine latest emissions
                rxBleConnection.readCharacteristic(aUUID),
                rxBleConnection.readCharacteristic(bUUID),
                Pair::new
        ))

But I don't understand how to do that with 4 characteristics for example.

Thank you

Body:
The above example is just fine you would only need some data object that would accept more values than Pair. For instance something like:

class ReadResult {
    final byte[] aValue;
    final byte[] bValue;
    final byte[] cValue;
    final byte[] dValue;

    ReadResult(byte[] aValue, byte[] bValue, byte[] cValue, byte[] dValue) {
        this.aValue = aValue;
        this.bValue = bValue;
        this.cValue = cValue;
        this.dValue = dValue;
    }
}

And then the example could look like this:

disposable = rxBleClient.scanBleDevices(
        new ScanSettings.Builder().build(),
        new ScanFilter.Builder().setDeviceName("NODE 1").build() // one can set filtering by name here
)
        .take(1) // take only the first result and then the upstream will get unsubscribed (scan will end)
        .flatMap(scanResult -> scanResult.getBleDevice().establishConnection(false)) // connect to the first scanned device that matches the filter
        .flatMapSingle(rxBleConnection -> Single.zip( // once connected read all needed values
                rxBleConnection.readCharacteristic(aUUID),
                rxBleConnection.readCharacteristic(bUUID),
                rxBleConnection.readCharacteristic(cUUID),
                rxBleConnection.readCharacteristic(dUUID),
                ReadResult::new // merge them into a single result
        ))
        .take(1) // once the result of all reads is available unsubscribe from the upstream (connection will end)
        .subscribe(
                readResult -> Log.d("Characteristics", /* print the readResult */),
                throwable -> Log.e("Error", throwable.getMessage())
        );

Original/Legacy solution for RxAndroidBle based on RxJava1:

subscription = rxBleClient.scanBleDevices(
        new ScanSettings.Builder().build(),
        new ScanFilter.Builder().setDeviceName("NODE 1").build() // one can set filtering by name here
)
        .take(1) // take only the first result and then the upstream will get unsubscribed (scan will end)
        .flatMap(scanResult -> scanResult.getBleDevice().establishConnection(false)) // connect to the first scanned device that matches the filter
        .flatMap(rxBleConnection -> Observable.combineLatest( // once connected read all needed values
                rxBleConnection.readCharacteristic(aUUID),
                rxBleConnection.readCharacteristic(bUUID),
                rxBleConnection.readCharacteristic(cUUID),
                rxBleConnection.readCharacteristic(dUUID),
                ReadResult::new // merge them into a single result
        ))
        .take(1) // once the result of all reads is available unsubscribe from the upstream (connection will end)
        .subscribe(
                readResult -> Log.d("Characteristics", /* print the readResult */),
                throwable -> Log.e("Error", throwable.getMessage())
        );


问:
Regarding WPF and web development?
i don't know anything about WPF. so a question has come to my mind that when we develop apps in WPF that can be run as web application without changing code. please comment. thanks.</p>

答:
WPF runs on the client. It is what replaces WinForms. Silverlight was intended for the web. It is a subset of WPF and it allows you to embed into a web page just like Flash.

For web development I would recommend you ASP.NET MVC.

Title: Regarding WPF and web development?


问:
How To pass php variable into ajax data
How can I send PHP  variable sprod into ajax i need to send this id to check.php page </p>

```<code><script>
function getState(val) {

    $.ajax({
    type: "POST",
    url: "check.php",
    data: {id: val, id2:$prod },
    dataType:'json',
    success: function(data){
        $("#style_code").children().remove();
        $("#style_image").children().remove();

         data.option.forEach(function (item) {
                $("#style_code").append('<option value="' + item.color_name + '">' + item.size + '</option>');
                $('#style_image').append('<img  src="images/'+item.image_name+'" data-imagezoom="true" class="img-responsive" alt="" />')
            //$("#style_image").html(data);
            });
    }
    });
}
</script>
</code>```

答:
```<code><script>
 var prod = <?php echo $prod ?>;
</script>
</code>```

Note

This should only works if your page is in .php extension

Title: How To pass php variable into ajax data

Body:
<script>
 var prod = <?php echo $prod ?>;
</script>

Note

This should only works if your page is in .php extension


问:
SQL syntax error on nested if-else statements [mysql]
I have a following sql function where I am trying to use nested if-else statements.

The function is working fine with nested 'if' statement removed. But when added, the error is displayed.

```<code>BEGIN
  DECLARE daysEntitled DECIMAL(4,2);
  DECLARE joinDate DATE;
  DECLARE dayOfMonth INT(4);
  SET joinDate = (SELECT join_date FROM users WHERE id = user);
  SET daysEntitled = TIMESTAMPDIFF(MONTH, joinDate, currentDate);
  IF YEAR(joinDate) = YEAR(currentDate) THEN
    SET currentDate = DATE_FORMAT(currentDate,'%Y-12-31');
    SET daysEntitled = TIMESTAMPDIFF(MONTH, joinDate, currentDate);
    SET dayOfMonth = CAST(DAY(joinDate) AS UNSIGNED);

****** On adding this block ********

    IF dayOfMonth <= 15 THEN
       SET daysEntitled += 1.00;
    ENDIF;

****** On adding this block ********

  ELSEIF YEAR(joinDate) < YEAR(currentDate) THEN
    SET daysEntitled = 8.00;
  ELSEIF YEAR(joinDate) > YEAR(currentDate) THEN
    SET daysEntitled = 12.00;
  ELSE
    SET daysEntitled = 4.00;
  END IF;
  RETURN daysEntitled;
END
</code>```

The code seems to be fine. I couldn't fine what went wrong.
Any help is very much appreciated. Thanks.

答:
There is nothing wrong with having a nested IF statement in MySQL.  I think the problem is the way you are trying to increment the variable:

```<code>SET daysEntitled += 1.00;
                 ^^ not allowed
</code>```

Use this code instead:

```<code>IF dayOfMonth <= 15 THEN
   SET daysEntitled = daysEntitled + 1.00;
ENDIF;
</code>```

Body:
I have a following sql function where I am trying to use nested if-else statements.

The function is working fine with nested 'if' statement removed. But when added, the error is displayed.

BEGIN
  DECLARE daysEntitled DECIMAL(4,2);
  DECLARE joinDate DATE;
  DECLARE dayOfMonth INT(4);
  SET joinDate = (SELECT join_date FROM users WHERE id = user);
  SET daysEntitled = TIMESTAMPDIFF(MONTH, joinDate, currentDate);
  IF YEAR(joinDate) = YEAR(currentDate) THEN
    SET currentDate = DATE_FORMAT(currentDate,'%Y-12-31');
    SET daysEntitled = TIMESTAMPDIFF(MONTH, joinDate, currentDate);
    SET dayOfMonth = CAST(DAY(joinDate) AS UNSIGNED);

****** On adding this block ********

    IF dayOfMonth <= 15 THEN
       SET daysEntitled += 1.00;
    ENDIF;

****** On adding this block ********

  ELSEIF YEAR(joinDate) < YEAR(currentDate) THEN
    SET daysEntitled = 8.00;
  ELSEIF YEAR(joinDate) > YEAR(currentDate) THEN
    SET daysEntitled = 12.00;
  ELSE
    SET daysEntitled = 4.00;
  END IF;
  RETURN daysEntitled;
END

The code seems to be fine. I couldn't fine what went wrong.
Any help is very much appreciated. Thanks.

Body:
There is nothing wrong with having a nested IF statement in MySQL.  I think the problem is the way you are trying to increment the variable:

SET daysEntitled += 1.00;
                 ^^ not allowed

Use this code instead:

IF dayOfMonth <= 15 THEN
   SET daysEntitled = daysEntitled + 1.00;
ENDIF;


答:
All the header guards do is to only allow your headers to be included once. (If they're included multiple times, they're ignored.)

The name you use doesn't matter, but it's conventional to use the file name in caps, including the extension like you demonstrated.

Your main should really be in a .cpp file, but if you're putting it in a header, put it inside the guards so it isn't declared multiple times.

Title: Header guards in C++ and C

Body:
At LearnCpp.com | 1.10 — A first look at the preprocessor. Under Header guards, there are those code snippets:

add.h:

#include "mymath.h"
int add(int x, int y);

subtract.h:

#include "mymath.h"
int subtract(int x, int y);

main.cpp:

#include "add.h"
#include "subtract.h"

In implementing the header guard, it is mentioned as follows:

#ifndef ADD_H
#define ADD_H

// your declarations here

#endif

What could the declaration be here? And, should int main() come after #endif?

Is adding _H a convention or a must do thing?

Thanks.