问:
efficient SQL query to get rows with different conditions in different times
Suppose we have a table users:

user_id, timestamp, condition_a, condition_b

Each user session is a row with same user id, different timestamp and arbitrary conditions a and/or b.

I want to do queries like:

Users who had condition a from t1 to t2 and NOT condition b from t3 to t4.

Users who had condition a before t1 and condition b after t3.

One way to do it is with subqueries:

for the 1st example above:

```<code>SELECT * FROM users WHERE
user_id IN
(SELECT user_id WHERE timestamp BETWEEN t1 AND t2 AND condition_a =1 )
AND user_id NOT IN
(SELECT user_id WHERE timestamp BETWEEN t2 AND t3 AND condition_b =1 )
</code>```

This looks very inefficient to me since it will have to scan the table several times.

Is there a more efficient way to do this that only needs to scan the table once?
(this is for presto eventually, partitions are by time blocks)

答:
In the original attempt, change IN to EXISTS.

Add these:

```<code>INDEX(condition_a, timestamp, user_id)
INDEX(condition_b, timestamp, user_id)
</code>```

The statement of the problem is imprecise.  What do you mean by "had condition a from t1 to t2"?

One row exists with 'a' in that time range, or

Multiple rows, one of which has 'a', or

Multiple rows, all of which have 'a'??

IN is more costly than EXISTS because it must find all of the rows.  EXISTS only handles the first two meanings.

For the second question I suggest

```<code>SELECT u.*
    FROM users AS u
    WHERE EXISTS ( SELECT * FROM ... WHERE condition_a AND timestamp < t1
                                       AND user_id = u.user_id )
      AND EXISTS ( SELECT * FROM ... WHERE condition_b AND timestamp > t3
                                       AND user_id = u.user_id )
</code>```

together with

```<code>INDEX(user_id, condition_a, timestamp)
INDEX(user_id, condition_b, timestamp)
</code>```

This would probably be better (for getting the user_ids) and would need only my first pair of indexes:

```<code>   ( SELECT DISTINCT user_id FROM ... WHERE condition_a AND timestamp < t1 )
   UNION ALL    -- 'ALL' is deliberate, for GROUP and HAVING
   ( SELECT DISTINCT user_id FROM ... WHERE condition_b AND timestamp > t3 )
   GROUP BY user_id
   HAVING COUNT(*) = 2
</code>```

To get user info:

```<code>SELECT u.*
    FROM ( that union ) AS v
    JOIN users AS u  USING(user_id)
</code>```

Body:
Suppose we have a table users:

user_id, timestamp, condition_a, condition_b

Each user session is a row with same user id, different timestamp and arbitrary conditions a and/or b.

I want to do queries like:

Users who had condition a from t1 to t2 and NOT condition b from t3 to t4.

Users who had condition a before t1 and condition b after t3.

One way to do it is with subqueries:

for the 1st example above:

SELECT * FROM users WHERE
user_id IN
(SELECT user_id WHERE timestamp BETWEEN t1 AND t2 AND condition_a =1 )
AND user_id NOT IN
(SELECT user_id WHERE timestamp BETWEEN t2 AND t3 AND condition_b =1 )

This looks very inefficient to me since it will have to scan the table several times.

Is there a more efficient way to do this that only needs to scan the table once?
(this is for presto eventually, partitions are by time blocks)

Body:
In the original attempt, change IN to EXISTS.

Add these:

INDEX(condition_a, timestamp, user_id)
INDEX(condition_b, timestamp, user_id)

The statement of the problem is imprecise.  What do you mean by "had condition a from t1 to t2"?

One row exists with 'a' in that time range, or

Multiple rows, one of which has 'a', or

Multiple rows, all of which have 'a'??

IN is more costly than EXISTS because it must find all of the rows.  EXISTS only handles the first two meanings.

For the second question I suggest

SELECT u.*
    FROM users AS u
    WHERE EXISTS ( SELECT * FROM ... WHERE condition_a AND timestamp < t1
                                       AND user_id = u.user_id )
      AND EXISTS ( SELECT * FROM ... WHERE condition_b AND timestamp > t3
                                       AND user_id = u.user_id )

together with

INDEX(user_id, condition_a, timestamp)
INDEX(user_id, condition_b, timestamp)

This would probably be better (for getting the user_ids) and would need only my first pair of indexes:

   ( SELECT DISTINCT user_id FROM ... WHERE condition_a AND timestamp < t1 )
   UNION ALL    -- 'ALL' is deliberate, for GROUP and HAVING
   ( SELECT DISTINCT user_id FROM ... WHERE condition_b AND timestamp > t3 )
   GROUP BY user_id
   HAVING COUNT(*) = 2

To get user info:

SELECT u.*
    FROM ( that union ) AS v
    JOIN users AS u  USING(user_id)


来源: stackexchange

问:
javascript: get url path
```<code>var url = 'http://domain.com/file.php?id=1';
</code>```

or

```<code>var url = 'https://domain.us/file.php?id=1'
</code>```

or

```<code>var url = 'domain.de/file.php?id=1';
</code>```

or

```<code>var url = 'subdomain.domain.com/file.php?id=1'
</code>```

from either one of these urls I want to get only the path, in the case above:

```<code>var path = '/file.php?id=1';
</code>```

答:
You could do it with regex, but using these native properties are arguably the best way to do it.

```<code>var url = 'subdomain.domain.com/file.php?id=1',
    a = document.createElement('a');

a.href = 'http://' + url;
var path = a.pathname + a.search; // /file.php?id=1
</code>```

See it on jsFiddle.net

ContentLicense: CC BY-SA 2.5

Title: javascript: get url path

Body:
var url = 'http://domain.com/file.php?id=1';

or

var url = 'https://domain.us/file.php?id=1'

or

var url = 'domain.de/file.php?id=1';

or

var url = 'subdomain.domain.com/file.php?id=1'

from either one of these urls I want to get only the path, in the case above:

var path = '/file.php?id=1';

Body:
You could do it with regex, but using these native properties are arguably the best way to do it.

var url = 'subdomain.domain.com/file.php?id=1',
    a = document.createElement('a');

a.href = 'http://' + url;
var path = a.pathname + a.search; // /file.php?id=1

See it on jsFiddle.net


问:
Including one erb file into another
I'm writing a command-line tool that will ultimately output an HTML report. The tool is written in Ruby. (I am not using Rails). I'm trying to keep the logic of the application in one set of files, and the HTML templates (the .erb files) in another set.

I'm having a really annoying problem though: I can't successfully include one .erb file into another.

To be specific, I'm trying to do something like this (in pseudo-code):

```<code><html>
<head>
  <style type='text/css'>
    [include a stylesheet here]
    [and another one here]
  </style>
</head>
<body>
  <p>The rest of my document follows...
</code>```

That example snippet is itself an erb file, which is being invoked from within the application logic.

I'm doing things this way so I can keep my stylesheets out of the main template to make it easier/cleaner to maintain the application. The end product (the report), though, needs to be a single, stand-alone HTML file which has no dependencies, and thus, I want to inline those stylesheets into the document head when the report is generated.

This seems like this should be easy, but I've been banging my head against a wall (and Googling, and RTMF'ing) for the last hour, and I'm not having any luck at all.

How is this supposed to be done? Thanks.

答:
From within my .erb file, I had to do this:

```<code><%= ERB.new(File.read('pathToFile/myFile.erb'), nil, nil, '_sub01').result(binding) %>
</code>```

The other answers in this thread assumed you had a variable with your content in it. This version retrieves the content.

ContentLicense: CC BY-SA 3.0

Title: Including one erb file into another

Body:
I'm writing a command-line tool that will ultimately output an HTML report. The tool is written in Ruby. (I am not using Rails). I'm trying to keep the logic of the application in one set of files, and the HTML templates (the .erb files) in another set.

I'm having a really annoying problem though: I can't successfully include one .erb file into another.

To be specific, I'm trying to do something like this (in pseudo-code):

The rest of my document follows...

That example snippet is itself an erb file, which is being invoked from within the application logic.

I'm doing things this way so I can keep my stylesheets out of the main template to make it easier/cleaner to maintain the application. The end product (the report), though, needs to be a single, stand-alone HTML file which has no dependencies, and thus, I want to inline those stylesheets into the document head when the report is generated.

This seems like this should be easy, but I've been banging my head against a wall (and Googling, and RTMF'ing) for the last hour, and I'm not having any luck at all.

How is this supposed to be done? Thanks.

Body:
From within my .erb file, I had to do this:

<%= ERB.new(File.read('pathToFile/myFile.erb'), nil, nil, '_sub01').result(binding) %>

The other answers in this thread assumed you had a variable with your content in it. This version retrieves the content.


问:
MvxTableViewCell loads an empty view
I needed a custom iOS TableView with different cells depending on the item type. It seemed easy, just define the layouts in the TableViewSource constructor, that is a child of MvxTableViewSource. Registration happens like this:

```<code>public TableViewSource(UITableView tableView, List<ItemHolder> sections) : base(tableView) {
    tableView.RegisterClassForCellReuse(typeof(MyCell), "MyCellId");
    [Registering further types here]
}
</code>```

To handle sections I've created an ItemHolder that defines the items in the section, and section header/footer. That part works just fine.

In GetOrCreateCellFor, I use the default DequeueReusableCell based on the given item's type. However if I register the cell as above, an empty cell is drawn.

My cell uses the XIB+Backing class (based on MvxTableViewCell) way, and in theory should work fine. If I use the Nib property of it, and use RegisterNibForCellReuse, the content gets drawn (however row heights are wrong, and binding does not happen since it is defined in the backing class).

The class looks like this:

```<code>public partial class MyCell : MvxTableViewCell
{
    public static readonly NSString Key = new NSString("MyCell");
    public static readonly UINib Nib = UINib.FromName("MyCell", NSBundle.MainBundle);

    protected MyCell(IntPtr handle) : base(handle)
    {
        this.DelayBind(() =>
        {
            var binding = this.CreateBindingSet<MyCell, object>();
            binding.Bind(this.TextView.Text).To(vm => vm.GetType().Name).WithConversion(new StringFormatConverter(), "Unknown cell type: {0}");
            binding.Apply();
        });
    }

    public static MyCell Create()
    {
        return (MyCell)Nib.Instantiate(null, null)[0];
    }
}
</code>```

In the XIB I have a UILabelView set up with AutoLayout, that has an Outlet called TextView.

So basically if I add it through the class itself, it does not work at all. If I use the Nib, then layout works, but there are no bindings, datacontext, etc., technically my logic is gone.

Am I doing something wrong here, or this isn't even supposed to work?

答:
One thing that immediately sticks out is the way your binding is defined. You don't need to Bind TextView.Text, you just pass in the TextView:

```<code>binding.Bind(TextView).To(vm => vm.GetType().Name).WithConversion(new StringFormatConverter(), "Unknown cell type: {0}");
</code>```

That fix might just get everything working for you. Otherwise, this is what works for me in MvvmCross for cell layouts defined in XIB files:

1.) I use RegisterNibForCellReuse to register my cells.

2.) Instead of using  this.DelayBind(() => in the constructor. I do my bindings in the AwakeFromNib override:

```<code>public override void AwakeFromNib()
{
    base.AwakeFromNib();

    var binding = this.CreateBindingSet<MyCell, MyCellViewModel>();
    binding.Bind(TextView).To(vm => vm.GetType().Name).WithConversion(new StringFormatConverter(), "Unknown cell type: {0}");
    binding.Apply();
}
</code>```

Title: MvxTableViewCell loads an empty view

Body:
I needed a custom iOS TableView with different cells depending on the item type. It seemed easy, just define the layouts in the TableViewSource constructor, that is a child of MvxTableViewSource. Registration happens like this:

public TableViewSource(UITableView tableView, List<ItemHolder> sections) : base(tableView) {
    tableView.RegisterClassForCellReuse(typeof(MyCell), "MyCellId");
    [Registering further types here]
}

To handle sections I've created an ItemHolder that defines the items in the section, and section header/footer. That part works just fine.

In GetOrCreateCellFor, I use the default DequeueReusableCell based on the given item's type. However if I register the cell as above, an empty cell is drawn.

My cell uses the XIB+Backing class (based on MvxTableViewCell) way, and in theory should work fine. If I use the Nib property of it, and use RegisterNibForCellReuse, the content gets drawn (however row heights are wrong, and binding does not happen since it is defined in the backing class).

The class looks like this:

public partial class MyCell : MvxTableViewCell
{
    public static readonly NSString Key = new NSString("MyCell");
    public static readonly UINib Nib = UINib.FromName("MyCell", NSBundle.MainBundle);

    protected MyCell(IntPtr handle) : base(handle)
    {
        this.DelayBind(() =>
        {
            var binding = this.CreateBindingSet<MyCell, object>();
            binding.Bind(this.TextView.Text).To(vm => vm.GetType().Name).WithConversion(new StringFormatConverter(), "Unknown cell type: {0}");
            binding.Apply();
        });
    }

    public static MyCell Create()
    {
        return (MyCell)Nib.Instantiate(null, null)[0];
    }
}

In the XIB I have a UILabelView set up with AutoLayout, that has an Outlet called TextView.

So basically if I add it through the class itself, it does not work at all. If I use the Nib, then layout works, but there are no bindings, datacontext, etc., technically my logic is gone.

Am I doing something wrong here, or this isn't even supposed to work?

Body:
One thing that immediately sticks out is the way your binding is defined. You don't need to Bind TextView.Text, you just pass in the TextView:

binding.Bind(TextView).To(vm => vm.GetType().Name).WithConversion(new StringFormatConverter(), "Unknown cell type: {0}");

That fix might just get everything working for you. Otherwise, this is what works for me in MvvmCross for cell layouts defined in XIB files:

1.) I use RegisterNibForCellReuse to register my cells.

2.) Instead of using  this.DelayBind(() => in the constructor. I do my bindings in the AwakeFromNib override:

public override void AwakeFromNib()
{
    base.AwakeFromNib();

    var binding = this.CreateBindingSet<MyCell, MyCellViewModel>();
    binding.Bind(TextView).To(vm => vm.GetType().Name).WithConversion(new StringFormatConverter(), "Unknown cell type: {0}");
    binding.Apply();
}


问:
Doctrine Join DQL
I's like to do a join between 2 tables on a specific ID. At the moment, I have this DQL:

```<code>$q = Doctrine_Query::create()
         ->select('e.*, i.itemName, i.itemtypeId')
         ->from('Model_EventItem e')
         ->leftJoin('Model_Item i ON e.itemId = i.itemId')
         ->where('e.eventitemId = ?', $event->eventId)
         ->orderBy('i.itemName ASC');
</code>```

The result is empty, although my eventId has a value ... Can you help me please? I there somewhere a tutorial on DQL-joins? I don't get it right with the help of the Doctrine documentation.

Thanks!

PS I have doctrine working in combination with Zend Framework.

答:
you should change the name in the left join from Model_EventItem to e

```<code>$q = Doctrine_Query::create()
     ->select('e.*, i.itemName, i.itemtypeId')
     ->from('Model_EventItem e')
     ->leftJoin('Model_EventItem.Model_Item i')
     ->where('e.eventitemId = ?', $event->eventId)
     ->orderBy('i.itemName ASC');
</code>```

Title: Doctrine Join DQL

Body:
I's like to do a join between 2 tables on a specific ID. At the moment, I have this DQL:

$q = Doctrine_Query::create()
         ->select('e.*, i.itemName, i.itemtypeId')
         ->from('Model_EventItem e')
         ->leftJoin('Model_Item i ON e.itemId = i.itemId')
         ->where('e.eventitemId = ?', $event->eventId)
         ->orderBy('i.itemName ASC');

The result is empty, although my eventId has a value ... Can you help me please? I there somewhere a tutorial on DQL-joins? I don't get it right with the help of the Doctrine documentation.

Thanks!

PS I have doctrine working in combination with Zend Framework.

Body:
you should change the name in the left join from Model_EventItem to e

$q = Doctrine_Query::create()
     ->select('e.*, i.itemName, i.itemtypeId')
     ->from('Model_EventItem e')
     ->leftJoin('Model_EventItem.Model_Item i')
     ->where('e.eventitemId = ?', $event->eventId)
     ->orderBy('i.itemName ASC');


问:
Version conflict between angular_components, rpc and sqljocky
Is it possible to use angular_components together with rpc and sqljocky packages in Dart? I have a package version conflict and cannot find my way out of it.

I am using Dart VM version: 1.23.0 (Fri Apr 21 03:13:00 2017) on "windows_x64"
. My pubspec.yaml for which I can get all dependencies is

```<code>name: Project
description: Some description
version: 0.0.1
author: me

environment:
  sdk: '>=1.20.1 <2.0.0'

dependencies:
  angular2: ^3.0.0
  ng_bootstrap: ">=0.5.1"
  angular_components: ">=0.5.0"
  plotly: any
  _discoveryapis_commons: ^0.1.0
  crypto: ^2.0.0
  http: ^0.11.1
  http_server: ^0.9.5+1
  logging_handlers: ^0.8.0
#  rpc: ">=0.5.0"
  csv: "^3.1.2"
#  sqljocky: '>=0.14.1'
  test: '>=0.12.20'

dev_dependencies:
  browser: ^0.10.0
  dart_to_js_script_rewriter: ^1.0.1

transformers:
- angular2:
    platform_directives:
    - 'package:angular2/common.dart#COMMON_DIRECTIVES'
    platform_pipes:
    - 'package:angular2/common.dart#COMMON_PIPES'
    entry_points: web/main.dart
- dart_to_js_script_rewriter
</code>```

However, as soon as I reintroduce rpc or sqljocky (i.e. remove the comment sign in front of them) and run pub get, I get either an error

```<code>Package dart_style has no versions that match >=0.2.10 <2.0.0 derived from:
- angular2 3.1.0-beta depends on version >=0.1.8 <2.0.0
- code_builder 1.0.3 depends on version >=0.2.10 <2.0.0
</code>```

(for sqljocky) or pub get hangs indefinitely with messages like

```<code>[...]
inconsistent constraints on quiver:
   uri 0.9.3 from hosted -> quiver >=0.17.0 <0.19.0 from hosted (quiver)
   angular2 3.1.0 from hosted -> quiver >=0.21.4 <0.26.0 from hosted (quiver)
   angular_components 0.5.1 from hosted -> quiver >=0.22.0 <0.26.0 from hosted (quiver)
 version 0.9.2 of uri doesn't match >=0.9.3 <0.12.0:
   rpc 0.5.6+3 from hosted -> uri >=0.9.3 <0.12.0 from hosted (uri)
 version 0.9.1 of uri doesn't match >=0.9.3 <0.12.0:
   rpc 0.5.6+3 from hosted -> uri >=0.9.3 <0.12.0 from hosted (uri)
[...]
</code>```

(for rpc, message edited for legibility). Any suggestions?

答:
Here's your problem: https://output.jsbin.com/varenekizi

rpc -> uri -> quiver <0.22.0

You need a more recent pkg/quiver for angular_compenents.

Fix in pubspec.yaml

```<code>dependency_overrides:
  quiver: 0.25.0
</code>```

Body:
Is it possible to use angular_components together with rpc and sqljocky packages in Dart? I have a package version conflict and cannot find my way out of it.

I am using Dart VM version: 1.23.0 (Fri Apr 21 03:13:00 2017) on "windows_x64"
. My pubspec.yaml for which I can get all dependencies is

name: Project
description: Some description
version: 0.0.1
author: me

environment:
  sdk: '>=1.20.1 <2.0.0'

dependencies:
  angular2: ^3.0.0
  ng_bootstrap: ">=0.5.1"
  angular_components: ">=0.5.0"
  plotly: any
  _discoveryapis_commons: ^0.1.0
  crypto: ^2.0.0
  http: ^0.11.1
  http_server: ^0.9.5+1
  logging_handlers: ^0.8.0
#  rpc: ">=0.5.0"
  csv: "^3.1.2"
#  sqljocky: '>=0.14.1'
  test: '>=0.12.20'

dev_dependencies:
  browser: ^0.10.0
  dart_to_js_script_rewriter: ^1.0.1

transformers:
- angular2:
    platform_directives:
    - 'package:angular2/common.dart#COMMON_DIRECTIVES'
    platform_pipes:
    - 'package:angular2/common.dart#COMMON_PIPES'
    entry_points: web/main.dart
- dart_to_js_script_rewriter

However, as soon as I reintroduce rpc or sqljocky (i.e. remove the comment sign in front of them) and run pub get, I get either an error

Package dart_style has no versions that match >=0.2.10 <2.0.0 derived from:
- angular2 3.1.0-beta depends on version >=0.1.8 <2.0.0
- code_builder 1.0.3 depends on version >=0.2.10 <2.0.0

(for sqljocky) or pub get hangs indefinitely with messages like

[...]
inconsistent constraints on quiver:
   uri 0.9.3 from hosted -> quiver >=0.17.0 <0.19.0 from hosted (quiver)
   angular2 3.1.0 from hosted -> quiver >=0.21.4 <0.26.0 from hosted (quiver)
   angular_components 0.5.1 from hosted -> quiver >=0.22.0 <0.26.0 from hosted (quiver)
 version 0.9.2 of uri doesn't match >=0.9.3 <0.12.0:
   rpc 0.5.6+3 from hosted -> uri >=0.9.3 <0.12.0 from hosted (uri)
 version 0.9.1 of uri doesn't match >=0.9.3 <0.12.0:
   rpc 0.5.6+3 from hosted -> uri >=0.9.3 <0.12.0 from hosted (uri)
[...]

(for rpc, message edited for legibility). Any suggestions?

Body:
Here's your problem: https://output.jsbin.com/varenekizi

rpc -> uri -> quiver <0.22.0

You need a more recent pkg/quiver for angular_compenents.

Fix in pubspec.yaml

dependency_overrides:
  quiver: 0.25.0


问:
Delete None in python list
Q1.

I want to get output as:

```<code>[Randy, Shaw]
</code>```

Output Looks like

```<code>['Randy', 'None', 'None', 'Shaw', 'None', 'None']
</code>```

But it is not removing 'None' values.

Here is my code..

```<code>from openpyxl import load_workbook
workbook = load_workbook('C:/Users/Desktop/test.xlsx')
print(workbook.get_sheet_names())

sheet=workbook.get_sheet_by_name('marks')

iterheaders = iter(sheet[1])
headers = [str(cell.value) for cell in iterheaders if cell is not None and cell != '']

Keyword_list = list(filter(None, headers))
</code>```

I even tried the following but it didn't work either:

```<code>Keyword_list = [i for i in headers if (None) != len(i)]
</code>```

Q2. In the same code what if I  want to get the sheet by its index rather than by its name in openpyxl. How do I do that?

答:
You can filter like so:

```<code>s = ['Randy', 'None', 'None', 'Shaw', 'None', 'None']

s = [i for i in s if i != "None"]
</code>```

Keep in mind that in your list you have the string "None", not the object None

For Q2:

```<code>workbook = load_workbook('C:/Users/Desktop/test.xlsx')

sheet = wworkbook.worksheets[0] #here, either loop over or access by whatever index you want.
</code>```

Title: Delete None in python list

Body:
Q1.

I want to get output as:

[Randy, Shaw]

Output Looks like

['Randy', 'None', 'None', 'Shaw', 'None', 'None']

But it is not removing 'None' values.

Here is my code..

from openpyxl import load_workbook
workbook = load_workbook('C:/Users/Desktop/test.xlsx')
print(workbook.get_sheet_names())

sheet=workbook.get_sheet_by_name('marks')

iterheaders = iter(sheet[1])
headers = [str(cell.value) for cell in iterheaders if cell is not None and cell != '']

Keyword_list = list(filter(None, headers))

I even tried the following but it didn't work either:

Keyword_list = [i for i in headers if (None) != len(i)]

Q2. In the same code what if I  want to get the sheet by its index rather than by its name in openpyxl. How do I do that?

Body:
You can filter like so:

s = ['Randy', 'None', 'None', 'Shaw', 'None', 'None']

s = [i for i in s if i != "None"]

Keep in mind that in your list you have the string "None", not the object None

For Q2:

workbook = load_workbook('C:/Users/Desktop/test.xlsx')

sheet = wworkbook.worksheets[0] #here, either loop over or access by whatever index you want.


问:
How to prevent absolutely positioned child to being cropped by overflow hidden div?
I want to be able to show all the contents of the divBox, but it has to be inside divBtoConteudo1_2, as I have to make a reference to its position, in order to determine the right placement. The problem is the top layer, which is set to overflow: hidden, and it's not allowing to display the content.

      Box images.

```

I've researched a bit for this solution, but couldn't find anything that would work. And in some posts, it said even that it couldn't be done.

Is there any solution for this, even if I have to use some jQuery? It would be great if I only had to do some changes on the divBox, in order for it to work.

答:
try setting id="divBox" inline style z-index: 1000

I ran into this a lot in my projects

Body:
I want to be able to show all the contents of the divBox, but it has to be inside divBtoConteudo1_2, as I have to make a reference to its position, in order to determine the right placement. The problem is the top layer, which is set to overflow: hidden, and it's not allowing to display the content.

      Box images.

I've researched a bit for this solution, but couldn't find anything that would work. And in some posts, it said even that it couldn't be done.

Is there any solution for this, even if I have to use some jQuery? It would be great if I only had to do some changes on the divBox, in order for it to work.


问:
remove the first html tag in a string
i have this text

```<code><?php
   $example1 = '<b class="counter">1</b> This is a computer';
   $example2 = '<b class="counter">5</b> i have a laptop';
   $example3 = '<b class="counter">1</b> i need a smartphone';
   $example4 = 'i need a car'; // does not have <b> tag
?>
</code>```

i'm looking for a php function to remove a part of the string, starting from  to , so the results should be like :

```<code>$example1_result = 'This is a computer';
$example2_result = 'i have a laptop';
$example3_result = 'i need a smartphone';
$example4_result = 'i need a car';
</code>```

答: If you need the result after  you can use substr($example, strpos($example, '')) where $example is 1 This is a computer

Title: remove the first html tag in a string

Body:
i have this text

<?php
   $example1 = '1 This is a computer';
   $example2 = '5 i have a laptop';
   $example3 = '1 i need a smartphone';
   $example4 = 'i need a car'; // does not have  tag
?>

i'm looking for a php function to remove a part of the string, starting from  to , so the results should be like :

$example1_result = 'This is a computer';
$example2_result = 'i have a laptop';
$example3_result = 'i need a smartphone';
$example4_result = 'i need a car';

Body: If you need the result after  you can use substr($example, strpos($example, '</b>')) where $example is <b class="counter">1</b> This is a computer


问:
stanford corenlp Sentiment Analysis in Scala Error
When I am trying to run the below code for Sentiment Analysis on Spark Scala, I am getting the below error:</p>

```<code>import org.apache.spark.sql.functions._
import com.databricks.spark.corenlp.functions._
import sqlContext.implicits._
val input = Seq((1, "<xml>Stanford University is located in California.
It is a great university.</xml>")).toDF("id", "text")
val output=input.select(cleanxml('text).as('doc))
.select(explode(ssplit('doc)).as('sen)).select('sen,
tokenize('sen).as('words), ner('sen).as('nerTags),
sentiment('sen).as('sentiment))
output.show(truncate = false)
Error :
The val output is throwing the below error:
java.lang.NoSuchMethodError:
scala.reflect.api.JavaUniverse.runtimeMirror(Ljava/lang/ClassLoader;)
Lscala/reflect/api/JavaMirrors$JavaMirror;
at com.databricks.spark.corenlp.functions$.cleanxml(functions.scala:54)
... 54 elided
</code>```

答:
It seems someone else has had this problem and fixed it.

See here: https://github.com/databricks/spark-corenlp/issues/25 and try following the instructions.

ContentLicense: CC BY-SA 4.0

Body:
When I am trying to run the below code for Sentiment Analysis on Spark Scala, I am getting the below error:

import org.apache.spark.sql.functions._
import com.databricks.spark.corenlp.functions._
import sqlContext.implicits._
val input = Seq((1, "<xml>Stanford University is located in California.
It is a great university.</xml>")).toDF("id", "text")
val output=input.select(cleanxml('text).as('doc))
.select(explode(ssplit('doc)).as('sen)).select('sen,
tokenize('sen).as('words), ner('sen).as('nerTags),
sentiment('sen).as('sentiment))
output.show(truncate = false)
Error :
The val output is throwing the below error:
java.lang.NoSuchMethodError:
scala.reflect.api.JavaUniverse.runtimeMirror(Ljava/lang/ClassLoader;)
Lscala/reflect/api/JavaMirrors$JavaMirror;
at com.databricks.spark.corenlp.functions$.cleanxml(functions.scala:54)
... 54 elided


答:
```<code>preg_replace("(<([a-z]+)>.*?</\\1>)is","",$example1);
</code>```

use this as you want to remove the content inside the  tags also strip_tags() will keep the content inside the html tags

Title: remove the first html tag in a string

Body:
preg_replace("(<([a-z]+)>.*?</\\1>)is","",$example1);

use this as you want to remove the content inside the <b> tags also strip_tags() will keep the content inside the html tags


问:
Left join but take random values
Just learning SQL. How do I take random samples after joining two tables? Thanks a lot.</p>

```<code>select  *
from t1
left join t2  on t1.ID = t2.ID
</code>```

答:
Just add ORDER BY rand() and LIMIT with sample size (for example 5):

```<code>select  *
from t1
left join t2  on t1.ID = t2.ID
ORDER BY rand()
LIMIT 5
</code>```

Title: Left join but take random values

Body:
Just learning SQL. How do I take random samples after joining two tables? Thanks a lot.

select  *
from t1
left join t2  on t1.ID = t2.ID

Body:
Just add ORDER BY rand() and LIMIT with sample size (for example 5):

select  *
from t1
left join t2  on t1.ID = t2.ID
ORDER BY rand()
LIMIT 5


问:
TableAdapter with multiple "LIKE" constraints
I'm using an Access database in my VB program and sorting it if a field has a value.

How would I add multiple conditions? Like if two values exist then show the results.

This is what I have now:

```<code>FROM    Orders
WHERE    ([Level] LIKE 'DD')
</code>```

How would I add ([NAME] Like 'Smith') to the constraints as well?

答:
You could even be more specific with your conditions and even combine a couple of them:

```<code>''' I added wildcards for the example
"SELECT * FROM Orders WHERE ([Level] LIKE '%DD%' AND ([NAME] LIKE '%Smith%' OR [NAME] LIKE '%Wilson%')) " & _
"OR ([Level] LIKE '%BB%' AND ([NAME] LIKE '%Sandy%' OR [NAME] LIKE '%Willy%'))
</code>```

This Query would return results where [Level] contains DD and [NAME] contains either Smith or Wilson.  It will also return results where [Level] contains BB and [NAME] contains either Sandy or Willy.  The Possibilities are endless depending on your conditions.

Just FYI.  "John" and "john" are different.  Incorporate something like this into your query

```<code>SELECT * FROM TABLE_NAME WHERE LCASE(field1) = LCASE(input)
</code>```

MS Access: LCase Function

It will make your search more efficient.

Body:
I'm using an Access database in my VB program and sorting it if a field has a value.

How would I add multiple conditions? Like if two values exist then show the results.

This is what I have now:

FROM    Orders
WHERE    ([Level] LIKE 'DD')

How would I add ([NAME] Like 'Smith') to the constraints as well?

Body:
You could even be more specific with your conditions and even combine a couple of them:

''' I added wildcards for the example
"SELECT * FROM Orders WHERE ([Level] LIKE '%DD%' AND ([NAME] LIKE '%Smith%' OR [NAME] LIKE '%Wilson%')) " & _
"OR ([Level] LIKE '%BB%' AND ([NAME] LIKE '%Sandy%' OR [NAME] LIKE '%Willy%'))

This Query would return results where [Level] contains DD and [NAME] contains either Smith or Wilson.  It will also return results where [Level] contains BB and [NAME] contains either Sandy or Willy.  The Possibilities are endless depending on your conditions.

Just FYI.  "John" and "john" are different.  Incorporate something like this into your query

SELECT * FROM TABLE_NAME WHERE LCASE(field1) = LCASE(input)

MS Access: LCase Function

It will make your search more efficient.


问:
Insert a newline character into a categorical axis factor label in BokehJS
I have a BokehJS plot with a categorical x-axis with factors that have strings that are very long. The label is being cut off by the edge of the graph and I would like to be able to insert a newline character either manually or automatically to produce a short length string (since it is now taller but narrower with a new line in the middle). I have tried the following code but it does not seem to create a change in the appearance.</p>

```<code>p.x_range.attributes['factors'][0] = 'Some very long text string\nthat has now been cut'
</code>```

答:
Until Bokeh adds either CSS rendering for xaxis ticks or add support for new line characters. Here's a workaround that can do what you are asking for, but it isn't perfect.

Instead of using a factor range, we can plot the data like normal using a placeholder x value. Then, we can place Labels under the y_axis at those placeholder positions which can then be rendered by css which will correctly print the newline.

Here's a working example using the Bokeh server.

main.py

```<code>from bokeh.plotting import ColumnDataSource, figure
from bokeh.models import LabelSet, FixedTicker
from bokeh.io import curdoc, show

factors = ["Some very long text string\nthat has now been cut\na",
           "Some very long text string\nthat has now been cut\nb"]
y = [50, 40]

# arbitrary placeholders which depends on the length and number of strings
x = [0, 2]
x_label = [0.65, 2.65]  # This is offset is based on the length of the string
y_label = [-2, -2]  # offset under the plot

source = ColumnDataSource(
    data=dict(factors=factors, x=x, y=y, x_label=x_label, y_label=y_label))

p = figure(x_range=(-1, 3), y_range=(0, 52))

p.circle(x='x', y='y', size=15, fill_color="orange", source=source)
p.xaxis.ticker = FixedTicker(ticks=x)

p.xaxis.major_label_text_font_size = '0pt'  # turn off x-axis tick labels
# p.xaxis.major_tick_line_color = None  # turn off x-axis major ticks
p.xaxis.minor_tick_line_color = None  # turn off x-axis minor ticks

labels = LabelSet(x='x_label', y='y_label', text='factors', source=source,
                  level='overlay', render_mode='css', text_align='center')

p.add_layout(labels)

curdoc().add_root(p)
</code>```

styles.css

```<code>.bk-annotation-child {
    white-space: pre-wrap;
    text-align: center;
}
</code>```

The main disadvantage of this method is that the x_labels must be manually offset on the x axis from our placeholder x values. This is because the built-in bokeh centering called from the LabelSet is calculated on the full length string and not the not the longest sub string between \n. I'm sure you could tinker with this answer and programmatically determine the correct offset for an arbitrary string instead of eyeballing it as I did.

Body:
I have a BokehJS plot with a categorical x-axis with factors that have strings that are very long. The label is being cut off by the edge of the graph and I would like to be able to insert a newline character either manually or automatically to produce a short length string (since it is now taller but narrower with a new line in the middle). I have tried the following code but it does not seem to create a change in the appearance.

p.x_range.attributes['factors'][0] = 'Some very long text string\nthat has now been cut'

Body:
Until Bokeh adds either CSS rendering for xaxis ticks or add support for new line characters. Here's a workaround that can do what you are asking for, but it isn't perfect.

Instead of using a factor range, we can plot the data like normal using a placeholder x value. Then, we can place Labels under the y_axis at those placeholder positions which can then be rendered by css which will correctly print the newline.

Here's a working example using the Bokeh server.

main.py

from bokeh.plotting import ColumnDataSource, figure
from bokeh.models import LabelSet, FixedTicker
from bokeh.io import curdoc, show

factors = ["Some very long text string\nthat has now been cut\na",
           "Some very long text string\nthat has now been cut\nb"]
y = [50, 40]

# arbitrary placeholders which depends on the length and number of strings
x = [0, 2]
x_label = [0.65, 2.65]  # This is offset is based on the length of the string
y_label = [-2, -2]  # offset under the plot

source = ColumnDataSource(
    data=dict(factors=factors, x=x, y=y, x_label=x_label, y_label=y_label))

p = figure(x_range=(-1, 3), y_range=(0, 52))

p.circle(x='x', y='y', size=15, fill_color="orange", source=source)
p.xaxis.ticker = FixedTicker(ticks=x)

p.xaxis.major_label_text_font_size = '0pt'  # turn off x-axis tick labels
# p.xaxis.major_tick_line_color = None  # turn off x-axis major ticks
p.xaxis.minor_tick_line_color = None  # turn off x-axis minor ticks

labels = LabelSet(x='x_label', y='y_label', text='factors', source=source,
                  level='overlay', render_mode='css', text_align='center')

p.add_layout(labels)

curdoc().add_root(p)

styles.css

.bk-annotation-child {
    white-space: pre-wrap;
    text-align: center;
}

The main disadvantage of this method is that the x_labels must be manually offset on the x axis from our placeholder x values. This is because the built-in bokeh centering called from the LabelSet is calculated on the full length string and not the not the longest sub string between \n. I'm sure you could tinker with this answer and programmatically determine the correct offset for an arbitrary string instead of eyeballing it as I did.


答:
Your none values are not literal None type values. Their strings. Therefore, you need to test them against strings. eg:

```<code>>>> lst = ['Randy', 'None', 'None', 'Shaw', 'None', 'None']
>>> [el for el in lst if el != 'None']
['Randy', 'Shaw']
>>>
</code>```

Title: Delete None in python list

Body:
Your none values are not literal None type values. Their strings. Therefore, you need to test them against strings. eg:

>>> lst = ['Randy', 'None', 'None', 'Shaw', 'None', 'None']
>>> [el for el in lst if el != 'None']
['Randy', 'Shaw']
>>>


问:
Sending IBM Lotus Notes email using excel VBA sends from wrong email address
I currently have two Lotus Notes databases, each with their own email addresses associated with them. As expected, when I send an email through the first database to my gmail account, it shows up as "From: notesAccount1@db1.com" and when I send using the second database, the message shows up as "From: notesAccount2@db2.com" in my gmail.

I have working code that opens up the second database, searches the inbox for an email containing a certain keyword, and extracts an email address from that email. It then creates a new document in that second database, inserts the recipients name, subject, body, etc., sends the email, and saves it to my sent folder. Everything works smoothly up to this point.

However, when I send an email from the second database to my gmail account using this VBA method, the email shows up in my gmail as "From: notesAccount1@db1.com" - the email associated with the first database.

I can't figure out why this is happening. Pretty limited knowledge of the interactions between VBA and Lotus Notes, and Lotus Notes servers/databases in general. The first database is technically my default one that only I have access to and the second database was added later and multiple people have access to it. I don't know if that's relevant.

Would appreciate any help! Thanks.

Note: This code was copied and adapted from several sources, including some on SO, IBM and other Notes sources, and anything else Google threw my way, including
http://www.fabalou.com/vbandvba/lotusnotesmail.asp

http://www-01.ibm.com/support/docview.wss?uid=swg21178583

Code: (This will have to be adapted as I have taken out server names and mail file names)

```<code>Sub ReadNotesEmail()

Dim sess As Object
Dim db As Object
Dim folder As Object
Dim docNext As Object
Dim memoSenders As Variant
Dim newEmail As Object
Dim view As Object
Dim entry As Object
Dim entries As Object
Dim templateEmail As Object

Dim mailServer As String
Dim mailFile As String
Dim folderName As String
Dim todayDate As String
Dim memoBody As String
Dim senderEmail As String

Dim emailStartPos As Integer
Dim emailEndPos As Integer

'This program will search a particular folder in a Notes database that I designate.
'It will search that folder for emails that contain certain key words. Once it finds
'an email that fits, it will grab the sender's email address (written in the body, not
'in the 'from') and send them an email.

'Name of folder to search for emails
folderName = "($Inbox)"

'Create a Lotus Notes session and open it (will require password)
Set sess = CreateObject("Lotus.NotesSession")
sess.Initialize ("")

'Set the mail server, mail file, and database. This will be the tricky part as I need this to
'look at the second mail server as opposed to the default mail server of jdyagoda
Set db = sess.GETDATABASE("***name of second Notes server***", "***name of second mail file***")

'Open the mail database in notes
If Not db.IsOpen = True Then
    Call db.Open
End If
Set folder = db.GetView(folderName)

'Now look through the emails one at a time with a loop that ends when no emails are left.
'If an email contains the key word, look for the email address of the person who submitted
'the contact-us form. It follows the string "Email:" and preceeds
'the string "Phone:".
Set doc = folder.GetFirstDocument
Do Until doc Is Nothing
    Set docNext = folder.GETNEXTDOCUMENT(doc)
    memoBody = LCase(doc.GetItemValue("body")(0))
    If (memoBody Like "*") Then 'This is where you designate the keyword

        'Here's where you extract the email address - taken out for the purpose of this SO question
        'senderEmail = testName@test.com

        'Now create a new email to the intended recipient

        Set newEmail = db.CREATEDOCUMENT
        Call newEmail.ReplaceItemValue("Form", "Memo")
        Call newEmail.ReplaceItemValue("SendTo", senderEmail)
        Call newEmail.ReplaceItemValue("Subject", "Thank you for your email")
        Call newEmail.ReplaceItemValue("body", "Test Body 1. This is a test.")
        newEmail.SAVEMESSAGEONSEND = True

        'Send the new email

        Call newEmail.ReplaceItemValue("PostedDate", Now()) 'Gets the mail to appeaer in the sent items folder
        Call newEmail.SEND(False)

    End If
    Set doc = docNext
Loop

End Sub
</code>```

答:
Notes will normally send the mail using the email address for the ID you use to login. So if you login using notesAccount1/Domain, then all emails will be coming from notesAccount1@example.com.
If you want to fake the sender, you need to use an undocumented method: inject the email directly into mail.box.
You should not attempt to do this unless you really know what you are doing.

I have posted code on my blog for a mail notification class, it supports this work-around to set the sender on outgoing emails. You can find the latest code at http://blog.texasswede.com/updated-mailnotification-class-now-with-html-email-support-and-web-links/

Body:
I currently have two Lotus Notes databases, each with their own email addresses associated with them. As expected, when I send an email through the first database to my gmail account, it shows up as "From: notesAccount1@db1.com" and when I send using the second database, the message shows up as "From: notesAccount2@db2.com" in my gmail.

I have working code that opens up the second database, searches the inbox for an email containing a certain keyword, and extracts an email address from that email. It then creates a new document in that second database, inserts the recipients name, subject, body, etc., sends the email, and saves it to my sent folder. Everything works smoothly up to this point.

However, when I send an email from the second database to my gmail account using this VBA method, the email shows up in my gmail as "From: notesAccount1@db1.com" - the email associated with the first database.

I can't figure out why this is happening. Pretty limited knowledge of the interactions between VBA and Lotus Notes, and Lotus Notes servers/databases in general. The first database is technically my default one that only I have access to and the second database was added later and multiple people have access to it. I don't know if that's relevant.

Would appreciate any help! Thanks.

Note: This code was copied and adapted from several sources, including some on SO, IBM and other Notes sources, and anything else Google threw my way, including
http://www.fabalou.com/vbandvba/lotusnotesmail.asp

http://www-01.ibm.com/support/docview.wss?uid=swg21178583

Code: (This will have to be adapted as I have taken out server names and mail file names)

Sub ReadNotesEmail()

Dim sess As Object
Dim db As Object
Dim folder As Object
Dim docNext As Object
Dim memoSenders As Variant
Dim newEmail As Object
Dim view As Object
Dim entry As Object
Dim entries As Object
Dim templateEmail As Object

Dim mailServer As String
Dim mailFile As String
Dim folderName As String
Dim todayDate As String
Dim memoBody As String
Dim senderEmail As String

Dim emailStartPos As Integer
Dim emailEndPos As Integer

'This program will search a particular folder in a Notes database that I designate.
'It will search that folder for emails that contain certain key words. Once it finds
'an email that fits, it will grab the sender's email address (written in the body, not
'in the 'from') and send them an email.

'Name of folder to search for emails
folderName = "($Inbox)"

'Create a Lotus Notes session and open it (will require password)
Set sess = CreateObject("Lotus.NotesSession")
sess.Initialize ("")

'Set the mail server, mail file, and database. This will be the tricky part as I need this to
'look at the second mail server as opposed to the default mail server of jdyagoda
Set db = sess.GETDATABASE("***name of second Notes server***", "***name of second mail file***")

'Open the mail database in notes
If Not db.IsOpen = True Then
    Call db.Open
End If
Set folder = db.GetView(folderName)

'Now look through the emails one at a time with a loop that ends when no emails are left.
'If an email contains the key word, look for the email address of the person who submitted
'the contact-us form. It follows the string "Email:" and preceeds
'the string "Phone:".
Set doc = folder.GetFirstDocument
Do Until doc Is Nothing
    Set docNext = folder.GETNEXTDOCUMENT(doc)
    memoBody = LCase(doc.GetItemValue("body")(0))
    If (memoBody Like "*") Then 'This is where you designate the keyword

        'Here's where you extract the email address - taken out for the purpose of this SO question
        'senderEmail = testName@test.com

        'Now create a new email to the intended recipient

        Set newEmail = db.CREATEDOCUMENT
        Call newEmail.ReplaceItemValue("Form", "Memo")
        Call newEmail.ReplaceItemValue("SendTo", senderEmail)
        Call newEmail.ReplaceItemValue("Subject", "Thank you for your email")
        Call newEmail.ReplaceItemValue("body", "Test Body 1. This is a test.")
        newEmail.SAVEMESSAGEONSEND = True

        'Send the new email

        Call newEmail.ReplaceItemValue("PostedDate", Now()) 'Gets the mail to appeaer in the sent items folder
        Call newEmail.SEND(False)

    End If
    Set doc = docNext
Loop

End Sub


问:
Count and group by query for counting rows in database table based on 3 to 4 conditions
I am running a market survey and all the survey data is saved in the database. I need a query for counting the number of rows in which option "1" is selected for question "1", option "2" for question "1" and so on for all questions and options… I need to specify few conditions here, I have to match distinct ID's of 3 tables and display the result for each particular ID.</p>

答:
The basis for a query would be something like this:

```<code>

SELECT q.question, a.answer, COUNT(a.answer)
  FROM questions q
  LEFT JOIN answers a ON (q.id = a.question_id)
 GROUP BY q.id, a.id
 ORDER BY q.id, a.id

</code>```

You could add the necessary conditions in a WHERE clause.

OwnerDisplayName: Jyotsna

LastEditorDisplayName: Spoike

Body:
The basis for a query would be something like this:

SELECT q.question, a.answer, COUNT(a.answer)
  FROM questions q
  LEFT JOIN answers a ON (q.id = a.question_id)
 GROUP BY q.id, a.id
 ORDER BY q.id, a.id

You could add the necessary conditions in a WHERE clause.

OwnerDisplayName: wvanbergen

LastEditorDisplayName: wvanbergen


问:
CloudKit - partialFailure and limitExceeded
Summary

In CloudKit would like to know all the possible CKError.Code possible for a .partialFailure.

Presently I am only handling the following CKError.Code for a partialFailure.

Assumptions:

.serverRecordChanged  //Only applicable while saving records

.zoneNotFound //Only applicable while fetching zones

.unknownItem  //Only applicable while fetching items

.batchRequestFailed //Only applicable while saving records in custom zone

Technically partialFailure can throw any CKError, but logically partialFailure is a failure at the item level and not at the operation level so partialFailure would not contain operation level errors such as networkUnavailable / badContainer / badDatabase.

Please refer to see how partialFailure is handled -  https://developer.apple.com/library/content/samplecode/CloudKitShare/Introduction/Intro.html (Search for handlePartialError) -

Questions:

For partialFailure, are the above stated the only possible error
codes ?

Are the errors serverRecordChanged, zoneNotFound,
unknownItem only possible as part of partialFailure error ? (Would
the error returned by the completion handler not directly contain
serverRecordChanged, zoneNotFound, unknownItem but only
partialFailure error may contain them ?)

Are my comments regarding
when each of the above error correct ? (Only applicable while...)

Is limitExceeded error thrown for CKFetch operations and CKModify operations or is it only
applicable for CKModify operations ?

答:
Partial Failure means that some of the CKRecords involved in an operations has failed, and maybe others finished without problem. Error could be one from the CKError structure

No. Those errors could happend in a CKDatabase.save ot CKDatadabe fetch operation.

+- ;-)

limitExceeded could happend on save or modify. For Fetching It's iCloud server which informs clients (you) when are more records waiting to be fetched. For example, the CKFetchNotificationChangesOperation has the property moreComing which indicates that you need to make another fetch operation.


问:
java.lang.RuntimeException: Failed to init Cipher using FingerPrint
I am using fingerprint sdk and it always crash on it.

```<code>java.lang.RuntimeException: Failed to init Cipher
at com.example.ammar.fingerbyitself.MainActivity.initCipher(MainActivity.java:160)
at com.example.ammar.fingerbyitself.MainActivity.access$000(MainActivity.java:55)
at com.example.ammar.fingerbyitself.MainActivity$1.onClick(MainActivity.java:109)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10814)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.security.InvalidKeyException: Only SecretKey is supported
at com.android.org.conscrypt.OpenSSLCipher.checkAndSetEncodedKey(OpenSSLCipher.java:435)
at com.android.org.conscrypt.OpenSSLCipher.engineInit(OpenSSLCipher.java:260)
at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:612)
at javax.crypto.Cipher.tryCombinations(Cipher.java:532)
at javax.crypto.Cipher.getSpi(Cipher.java:437)
at javax.crypto.Cipher.init(Cipher.java:815)
at javax.crypto.Cipher.init(Cipher.java:774)
at com.example.ammar.fingerbyitself.MainActivity.initCipher(MainActivity.java:153)
at com.example.ammar.fingerbyitself.MainActivity.access$000(MainActivity.java:55)
at com.example.ammar.fingerbyitself.MainActivity$1.onClick(MainActivity.java:109)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10814)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
</code>```

When I call CIPHERinit()

```<code>private boolean initCipher() {
        try {
//            KeyStore mKeyStore = KeyStore.getInstance("AndroidKeyStore");
            mKeyStore.load(null);
            SecretKey key = (SecretKey) mKeyStore.getKey(KEY_NAME, null);
            mCipher.init(Cipher.ENCRYPT_MODE, key);
            return true;
        } catch (KeyPermanentlyInvalidatedException e) {
            return false;
        } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException
                | NoSuchAlgorithmException | InvalidKeyException e) {

            throw new RuntimeException("Failed to init Cipher", e);
        }
    }
</code>```

Why it crashes is not clear, even the same code is working downloaded from GitHub.

答:
I was getting this error when the SecretKey I was passing to the init function was actually null.

That said, I made a library for fingerprint authentication. You may want to give it a shot :

```<code>FingerprintDialog.initialize(this)
    .title(R.string.title)
    .message(R.string.message)
    .callback(new FingerprintDialogCallback() {
        @Override public void onAuthenticationSucceeded() {}
        @Override public void onAuthenticationCancel() {}
    })
    .show();
</code>```

Fingerprint Library

You can choose to use CryptoObject or not.

Body:
I am using fingerprint sdk and it always crash on it.

java.lang.RuntimeException: Failed to init Cipher
at com.example.ammar.fingerbyitself.MainActivity.initCipher(MainActivity.java:160)
at com.example.ammar.fingerbyitself.MainActivity.access$000(MainActivity.java:55)
at com.example.ammar.fingerbyitself.MainActivity$1.onClick(MainActivity.java:109)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10814)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.security.InvalidKeyException: Only SecretKey is supported
at com.android.org.conscrypt.OpenSSLCipher.checkAndSetEncodedKey(OpenSSLCipher.java:435)
at com.android.org.conscrypt.OpenSSLCipher.engineInit(OpenSSLCipher.java:260)
at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:612)
at javax.crypto.Cipher.tryCombinations(Cipher.java:532)
at javax.crypto.Cipher.getSpi(Cipher.java:437)
at javax.crypto.Cipher.init(Cipher.java:815)
at javax.crypto.Cipher.init(Cipher.java:774)
at com.example.ammar.fingerbyitself.MainActivity.initCipher(MainActivity.java:153)
at com.example.ammar.fingerbyitself.MainActivity.access$000(MainActivity.java:55)
at com.example.ammar.fingerbyitself.MainActivity$1.onClick(MainActivity.java:109)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10814)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)

When I call CIPHERinit()

private boolean initCipher() {
        try {
//            KeyStore mKeyStore = KeyStore.getInstance("AndroidKeyStore");
            mKeyStore.load(null);
            SecretKey key = (SecretKey) mKeyStore.getKey(KEY_NAME, null);
            mCipher.init(Cipher.ENCRYPT_MODE, key);
            return true;
        } catch (KeyPermanentlyInvalidatedException e) {
            return false;
        } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException
                | NoSuchAlgorithmException | InvalidKeyException e) {

            throw new RuntimeException("Failed to init Cipher", e);
        }
    }

Why it crashes is not clear, even the same code is working downloaded from GitHub.

Body:
I was getting this error when the SecretKey I was passing to the init function was actually null.

That said, I made a library for fingerprint authentication. You may want to give it a shot :

FingerprintDialog.initialize(this)
    .title(R.string.title)
    .message(R.string.message)
    .callback(new FingerprintDialogCallback() {
        @Override public void onAuthenticationSucceeded() {}
        @Override public void onAuthenticationCancel() {}
    })
    .show();

Fingerprint Library

You can choose to use CryptoObject or not.


问:
How to fake macports into using my build script for ffmpeg?
I have my own bash script to configure ffmpeg which successfully updates my git repo, builds, tests and installs everything correctly.

Basically I want to bypass macports env and configuration but recognize my build but only for ffmpeg, I don't want macports to look in /usr/local or another location, I want it installed in /opt/local

So it probably boils down to, how to completely disable all the macports env and just launch a subshell with my script?

Created tarball, checksums, etc

```<code>PortSystem          1.0
PortGroup           muniversal 1.0
name                ffmpeg
epoch               1
version             9.9.9
revision            9
license             LGPL-2.1+
categories          multimedia
maintainers         nomaintainer
platforms           darwin
homepage            http://www.ffmpeg.org/
master_sites       file:///Volumes/Apps_Media/my_repo
use_zip              yes
checksums {they work}
depends_build       port:pkgconfig \
                    port:gmake \
                    port:texinfo
use_configure    no
build.cmd           $HOME/bin/configFFMPEG
</code>```

macports chokes on these lines in ffmpeg's configure

```<code>FFmpeg/configure: line 3596: ffbuild/config.log: Operation not permitted
FFmpeg/configure: line 3597: ffbuild/config.log: Operation not permitted

echo "# $0 $FFMPEG_CONFIGURATION" > $logfile
set >> $logfile
</code>```

答:
MacPorts runs builds as the macports user, not yoru normal user or root. Make sure that user can both read your script and write to the locations where your script is trying to write.

Even though you invoke MacPorts with superuser privileges, it will not use these privileges while building software.

Body:
I have my own bash script to configure ffmpeg which successfully updates my git repo, builds, tests and installs everything correctly.

Basically I want to bypass macports env and configuration but recognize my build but only for ffmpeg, I don't want macports to look in /usr/local or another location, I want it installed in /opt/local

So it probably boils down to, how to completely disable all the macports env and just launch a subshell with my script?

Created tarball, checksums, etc

PortSystem          1.0
PortGroup           muniversal 1.0
name                ffmpeg
epoch               1
version             9.9.9
revision            9
license             LGPL-2.1+
categories          multimedia
maintainers         nomaintainer
platforms           darwin
homepage            http://www.ffmpeg.org/
master_sites       file:///Volumes/Apps_Media/my_repo
use_zip              yes
checksums {they work}
depends_build       port:pkgconfig \
                    port:gmake \
                    port:texinfo
use_configure    no
build.cmd           $HOME/bin/configFFMPEG

macports chokes on these lines in ffmpeg's configure

FFmpeg/configure: line 3596: ffbuild/config.log: Operation not permitted
FFmpeg/configure: line 3597: ffbuild/config.log: Operation not permitted

echo "# $0 $FFMPEG_CONFIGURATION" > $logfile
set >> $logfile


问:
Get most recent data point from HKSampleQuery
I am having trouble getting the latest datapoint for weight using an HKSampleQuery. I have the app permissions set correctly, but HKQuantityTypeIdentifier.bodyMass is not returning the most recent data entry from the Health app.

How am I supposed to grab the latest datapoint for body mass using an HKSampleQuery?

The reason I think this is because the 0.0 I set for Weight is what is returning and I am getting no console output on readWeight

Edit 1

My code including the debugging process is as follows.

```<code>public func readWeight(result: @escaping (Double) -> Void) {
    if (debug){print("Weight")}
    let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)

    let weightQuery = HKSampleQuery(sampleType: quantityType!, predicate: nil, limit: 1, sortDescriptors: nil) {

        query, results, error in

        if (error != nil) {
            if (self.debug){print(error!)}
            result(166.2) //Set as average weight for American
            return
        }

        guard let results = results else {
            if (self.debug){print("No results of query")}
            result(166.2)
            return
        }

        if (results.count == 0) {
            if (self.debug){print("Zero samples")}
            result(166.2)
            return
        }

        guard let bodymass = results.first as? HKQuantitySample else {
            if (self.debug){print("Type problem with weight")}
            result(166.2)
            return
        }

        if (self.debug){print("Weight" + String(bodymass.quantity.doubleValue(for: HKUnit.pound())))}

        if (bodymass.quantity.doubleValue(for: HKUnit.pound()) != 0.0) {
            result(bodymass.quantity.doubleValue(for: HKUnit.pound()))
        } else {
            result(166.2)
        }
    }

    healthKitStore.execute(weightQuery)
}
</code>```

The function is used like this:

```<code>var Weight = 0.0 //The probable reason that it returns 0.0
readWeight() { weight in
    Weight = weight
}
</code>```

Edit 2

Permission Code:

```<code>    let healthKitTypesToRead : Set<HKQuantityType> = [
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryWater)!,
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!,
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.appleExerciseTime)!
    ]

    let healthKitTypesToWrite: Set<HKQuantityType> = [
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryWater)!
    ]

    if (!HKHealthStore.isHealthDataAvailable()) {
        if (self.debug){print("Error: HealthKit is not available in this Device")}
        return
    }

    healthKitStore.requestAuthorization(toShare: healthKitTypesToWrite, read: healthKitTypesToRead) { (success, error) -> Void in
        if (success) {
            DispatchQueue.main.async() {
                self.pointView.text = String(self.currentPoints())
            }
        }

        if ((error) != nil) {
            if (self.debug){print(error!)}
            return
        }
</code>```

答:
As explained in the HealthKit documentation (which I strongly urge you to read in its entirety), an HKSampleQuery makes no guarantees about the samples it returns or the order in which it returns them unless you specify how the samples should be returned.

For your case, returning the most recent data point can be done in a number of ways. Take a look at HKSampleQuery and the following method:

```<code>init(sampleType:predicate:limit:sortDescriptors:resultsHandler:)
</code>```

You can provide a sort order for the returned samples, or limit the number of samples returned.

-- HKSampleQuery Documentation

In your code, you have appropriately limited the query so that it only returns one sample. This is correct and avoids unnecessary overhead in your use case. However, your code specifies nil for the sortDescriptors parameter. This means that the query can return samples in whatever order it pleases (thus, the single sample being returned to you is usually not what you're looking for).

An array of sort descriptors that specify the order of the results returned by this query. Pass nil if you don’t need the results in a specific order.

Note

  HealthKit defines a number of sort identifiers (for example,
  HKSampleSortIdentifierStartDateand HKWorkoutSortIdentifierDuration). Use the sort descriptors you create with these identifiers only in queries. You cannot use them to perform an in-memory sort of an array of samples.

-- HKSampleQuery.init(...) Documentation

So, the solution then, is to simply provide a sort descriptor that asks the HKSampleQuery to order samples by date in descending order (meaning the most recent one will be first in a list).

I hope that the answer above is more helpful than a simple copy/paste of the code you need to fix the issue. Even so, the code to provide the correct sample for this specific use case is below:

```<code>// Create an NSSortDescriptor
let sort = [
    // We want descending order to get the most recent date FIRST
     NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
]

let weightQuery = HKSampleQuery(sampleType: quantityType!, predicate: nil, limit: 1, sortDescriptors: sort) {
    // Handle errors and returned samples...
}
</code>```

Body:
I am having trouble getting the latest datapoint for weight using an HKSampleQuery. I have the app permissions set correctly, but HKQuantityTypeIdentifier.bodyMass is not returning the most recent data entry from the Health app.

How am I supposed to grab the latest datapoint for body mass using an HKSampleQuery?

The reason I think this is because the 0.0 I set for Weight is what is returning and I am getting no console output on readWeight

Edit 1

My code including the debugging process is as follows.

public func readWeight(result: @escaping (Double) -> Void) {
    if (debug){print("Weight")}
    let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)

    let weightQuery = HKSampleQuery(sampleType: quantityType!, predicate: nil, limit: 1, sortDescriptors: nil) {

        query, results, error in

        if (error != nil) {
            if (self.debug){print(error!)}
            result(166.2) //Set as average weight for American
            return
        }

        guard let results = results else {
            if (self.debug){print("No results of query")}
            result(166.2)
            return
        }

        if (results.count == 0) {
            if (self.debug){print("Zero samples")}
            result(166.2)
            return
        }

        guard let bodymass = results.first as? HKQuantitySample else {
            if (self.debug){print("Type problem with weight")}
            result(166.2)
            return
        }

        if (self.debug){print("Weight" + String(bodymass.quantity.doubleValue(for: HKUnit.pound())))}

        if (bodymass.quantity.doubleValue(for: HKUnit.pound()) != 0.0) {
            result(bodymass.quantity.doubleValue(for: HKUnit.pound()))
        } else {
            result(166.2)
        }
    }

    healthKitStore.execute(weightQuery)
}

The function is used like this:

var Weight = 0.0 //The probable reason that it returns 0.0
readWeight() { weight in
    Weight = weight
}

Edit 2

Permission Code:

    let healthKitTypesToRead : Set<HKQuantityType> = [
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryWater)!,
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!,
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.appleExerciseTime)!
    ]

    let healthKitTypesToWrite: Set<HKQuantityType> = [
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryWater)!
    ]

    if (!HKHealthStore.isHealthDataAvailable()) {
        if (self.debug){print("Error: HealthKit is not available in this Device")}
        return
    }

    healthKitStore.requestAuthorization(toShare: healthKitTypesToWrite, read: healthKitTypesToRead) { (success, error) -> Void in
        if (success) {
            DispatchQueue.main.async() {
                self.pointView.text = String(self.currentPoints())
            }
        }

        if ((error) != nil) {
            if (self.debug){print(error!)}
            return
        }

Body:
As explained in the HealthKit documentation (which I strongly urge you to read in its entirety), an HKSampleQuery makes no guarantees about the samples it returns or the order in which it returns them unless you specify how the samples should be returned.

For your case, returning the most recent data point can be done in a number of ways. Take a look at HKSampleQuery and the following method:

init(sampleType:predicate:limit:sortDescriptors:resultsHandler:)

You can provide a sort order for the returned samples, or limit the number of samples returned.

-- HKSampleQuery Documentation

In your code, you have appropriately limited the query so that it only returns one sample. This is correct and avoids unnecessary overhead in your use case. However, your code specifies nil for the sortDescriptors parameter. This means that the query can return samples in whatever order it pleases (thus, the single sample being returned to you is usually not what you're looking for).

An array of sort descriptors that specify the order of the results returned by this query. Pass nil if you don’t need the results in a specific order.

Note

  HealthKit defines a number of sort identifiers (for example,
  HKSampleSortIdentifierStartDateand HKWorkoutSortIdentifierDuration). Use the sort descriptors you create with these identifiers only in queries. You cannot use them to perform an in-memory sort of an array of samples.

-- HKSampleQuery.init(...) Documentation

So, the solution then, is to simply provide a sort descriptor that asks the HKSampleQuery to order samples by date in descending order (meaning the most recent one will be first in a list).

I hope that the answer above is more helpful than a simple copy/paste of the code you need to fix the issue. Even so, the code to provide the correct sample for this specific use case is below:

// Create an NSSortDescriptor
let sort = [
    // We want descending order to get the most recent date FIRST
     NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
]

let weightQuery = HKSampleQuery(sampleType: quantityType!, predicate: nil, limit: 1, sortDescriptors: sort) {
    // Handle errors and returned samples...
}


问:
HTTP Location Header Rewrite - moving logic from IIS proxy to IBM datapower
We are moving Location Header Rewrite logic from IIS reverse proxy to IBM dataPower XI52.. I know we have header rewrite functionality on DP but I am not able to understand how we can implement below scenario on DP, can you please guide me? May I know what is R:1, R:2 and R:3 are referring here?
Location HeaderRewrite outgoing rule on IIS reverse proxy:

```<code><rule name="Change Location Header" enabled="true">
                <match serverVariable="RESPONSE_LOCATION" pattern="^http(s)?://([^/]+)/(.*)" />
                <conditions logicalGrouping="MatchAny" trackAllCaptures="true">
                    <add input="{RESPONSE_STATUS}" pattern="^301" />
                    <add input="{RESPONSE_STATUS}" pattern="^302" />
                </conditions>
                <action type="Rewrite" value="http{R:1}://{R:2}/{R:3}" />
            </rule>
</code>```

May I know how we can implement the same on DP ?

I tried using below xslt, but getting empty LocationHeader_output value, am doing something wrong here ?

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:dp="http://www.datapower.com/extensions"
xmlns:re="http://exslt.org/regular-expressions"
extension-element-prefixes="dp re"
exclude-result-prefixes="dp">
<xsl:template match="*">
    <xsl:choose>
        <xsl:when test="dp:responding()">
            <xsl:variable name="code">
                <xsl:choose>
                    <xsl:when test="dp:http-response-header('x-dp-response-code') != ''">
                        <xsl:value-of select="substring(dp:http-response-header('x-dp-response-code'), 1, 3)"/>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:value-of select="substring(dp:variable('var://service/error-headers'), 10, 3)" />
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:variable>
            <xsl:if test="$code = '301' or $code = '302'">
                <xsl:variable name="location" select="dp:http-response-header('Location')"/>

                <xsl:variable name="location_final">
                    <xsl:value-of select="re:replace($location, '^http(s)?://([^/]+)/(.*)', 'g', 'http{$1}://{$2}/{$3}')" />
                </xsl:variable>
                <dp:set-http-response-header name="'Location'" value="$location_final" />
            </xsl:if>
            <!-- the following prevent DataPower from overriding the response code coming back from Server-->
            <dp:set-response-header name="'x-dp-response-code'" value="'-1'"/>
        </xsl:when>
        <xsl:otherwise/>
    </xsl:choose>
</xsl:template>
</code>```

答:
It worked using below xslt in IBM DataPower

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:dp="http://www.datapower.com/extensions"
xmlns:re="http://exslt.org/regular-expressions"
extension-element-prefixes="dp re"
exclude-result-prefixes="dp">
<xsl:template match="/">
    <xsl:variable name="code">
        <xsl:choose>
            <xsl:when test="dp:http-response-header('x-dp-response-code') != ''">
                <xsl:value-of select="substring(dp:http-response-header('x-dp-response-code'), 1, 3)"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="substring(dp:variable('var://service/error-headers'), 10, 3)" />
            </xsl:otherwise>
        </xsl:choose>
    </xsl:variable>
    <xsl:message dp:priority="info">
  HTTP response Code:<xsl:value-of select="$code"/>
    </xsl:message>
    <xsl:if test="$code = '301' or $code = '302'">
        <xsl:variable name="location" select="dp:http-response-header('Location')"/>

        <xsl:variable name="location_final">
            <xsl:value-of select="re:replace($location, '^http(s)?://([^/]+)/(.*)', 'g', 'http$1://$2/$3')" />
        </xsl:variable>
        <dp:set-http-response-header name="'Location'" value="$location_final" />
        <xsl:message dp:priority="info">
  Response Location_beforeModify:<xsl:value-of select="$location"/>
  Response Location_AfterModify:<xsl:value-of select="$location_final"/>
<!--   Response test Regex:<xsl:value-of select="re:replace('https://demo.cloudimg.io/s/width/300/sample.li/boat.jpg', '^http(s)?://([^/]+)/(.*)', 'g', 'http$1://$2/$3')" />   -->
        </xsl:message>
    </xsl:if>
    <!-- the following prevent DataPower from overriding the response code coming back from Server-->
    <dp:set-response-header name="'x-dp-response-code'" value="'-1'"/>

</xsl:template>
</code>```

Body:
We are moving Location Header Rewrite logic from IIS reverse proxy to IBM dataPower XI52.. I know we have header rewrite functionality on DP but I am not able to understand how we can implement below scenario on DP, can you please guide me? May I know what is R:1, R:2 and R:3 are referring here?
Location HeaderRewrite outgoing rule on IIS reverse proxy:

<rule name="Change Location Header" enabled="true">
                <match serverVariable="RESPONSE_LOCATION" pattern="^http(s)?://([^/]+)/(.*)" />
                <conditions logicalGrouping="MatchAny" trackAllCaptures="true">
                    <add input="{RESPONSE_STATUS}" pattern="^301" />
                    <add input="{RESPONSE_STATUS}" pattern="^302" />
                </conditions>
                <action type="Rewrite" value="http{R:1}://{R:2}/{R:3}" />
            </rule>

May I know how we can implement the same on DP ?

I tried using below xslt, but getting empty LocationHeader_output value, am doing something wrong here ?

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:dp="http://www.datapower.com/extensions"
xmlns:re="http://exslt.org/regular-expressions"
extension-element-prefixes="dp re"
exclude-result-prefixes="dp">
<xsl:template match="*">
    <xsl:choose>
        <xsl:when test="dp:responding()">
            <xsl:variable name="code">
                <xsl:choose>
                    <xsl:when test="dp:http-response-header('x-dp-response-code') != ''">
                        <xsl:value-of select="substring(dp:http-response-header('x-dp-response-code'), 1, 3)"/>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:value-of select="substring(dp:variable('var://service/error-headers'), 10, 3)" />
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:variable>
            <xsl:if test="$code = '301' or $code = '302'">
                <xsl:variable name="location" select="dp:http-response-header('Location')"/>

                <xsl:variable name="location_final">
                    <xsl:value-of select="re:replace($location, '^http(s)?://([^/]+)/(.*)', 'g', 'http{$1}://{$2}/{$3}')" />
                </xsl:variable>
                <dp:set-http-response-header name="'Location'" value="$location_final" />
            </xsl:if>

            <dp:set-response-header name="'x-dp-response-code'" value="'-1'"/>
        </xsl:when>
        <xsl:otherwise/>
    </xsl:choose>
</xsl:template>

Body:
It worked using below xslt in IBM DataPower

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:dp="http://www.datapower.com/extensions"
xmlns:re="http://exslt.org/regular-expressions"
extension-element-prefixes="dp re"
exclude-result-prefixes="dp">
<xsl:template match="/">
    <xsl:variable name="code">
        <xsl:choose>
            <xsl:when test="dp:http-response-header('x-dp-response-code') != ''">
                <xsl:value-of select="substring(dp:http-response-header('x-dp-response-code'), 1, 3)"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="substring(dp:variable('var://service/error-headers'), 10, 3)" />
            </xsl:otherwise>
        </xsl:choose>
    </xsl:variable>
    <xsl:message dp:priority="info">
  HTTP response Code:<xsl:value-of select="$code"/>
    </xsl:message>
    <xsl:if test="$code = '301' or $code = '302'">
        <xsl:variable name="location" select="dp:http-response-header('Location')"/>

        <xsl:variable name="location_final">
            <xsl:value-of select="re:replace($location, '^http(s)?://([^/]+)/(.*)', 'g', 'http$1://$2/$3')" />
        </xsl:variable>
        <dp:set-http-response-header name="'Location'" value="$location_final" />
        <xsl:message dp:priority="info">
  Response Location_beforeModify:<xsl:value-of select="$location"/>
  Response Location_AfterModify:<xsl:value-of select="$location_final"/>
<!--   Response test Regex:<xsl:value-of select="re:replace('https://demo.cloudimg.io/s/width/300/sample.li/boat.jpg', '^http(s)?://([^/]+)/(.*)', 'g', 'http$1://$2/$3')" />   -->
        </xsl:message>
    </xsl:if>
    <!-- the following prevent DataPower from overriding the response code coming back from Server-->
    <dp:set-response-header name="'x-dp-response-code'" value="'-1'"/>

</xsl:template>


问:
ngIf Display Another DOM Element in Angular 2
Not sure if this is possible, but I am building a dynamic HTML table of products.  I am evaluating each product's "updatedDate" and determining if that date is less than the current date minus 7 days - todayMinusSeven days is a variable I am declaring in my TypeScript component file initializing it to the current date minus seven days:

```<code>this.todayMinusSeven = new Date();
this.todayMinusSeven.setDate(this.todayMinusSeven.getDate() - 7);
</code>```

I am trying to figure out how to display my div element of id "notice" from the *ngIf condition in the HTML table.  Essentially, if any product's updatedDate is less than the current date minus seven days, then display the "notice" div.  Here is my HTML:

```<code><div id="notice" class="err-notice">
    <img src="../error.svg" />
    There are products that have not been updated in the past seven days...please notify the support department for further information
</div>
<table>
    <thead>
        <th></th>
        <th>ID</th>
        <th>Name</th>
        <th>Updated On</th>
    </thead>
    <tbody>
        <tr *ngFor="let product of products?.results">
            <td>
                <ng-container *ngIf="product.updatedOn < todayMinusSeven"; else nonotice;">
                    <img src="../error.svg" />
                </ng-container>
                <ng-template #nonotice>
                    <img *ngIf="selected" src="../product-open.svg" />
                    <img *ngIf="!selected" src="../product.svg" />
                </ng-template>
            </td>
            <td>{{product.id}}</td>
            <td>{{product.name}}</td>
            <td>{{product.updatedOn}}</td>
        </tr>
    </tbody>
</table>
</code>```

Whether or I need to do this in the HTML or the component TypeScript file I am not sure, I am getting the list of products from an HTTP service class and subscribing it to an array of Product objects, so I would prefer not to have to traverse the array for this condition since it is already being traversed in the HTML markup.  Is this possible to do in HTML with Angular 2/4?

Thanks!

答: Add a utility method with name like isOutDated() to Typscript code supporting the page, that spins through the products and returns a boolean.  Add  *NgIf="isOutDated()" to the div with id notice</p>

Body:
Not sure if this is possible, but I am building a dynamic HTML table of products.  I am evaluating each product's "updatedDate" and determining if that date is less than the current date minus 7 days - todayMinusSeven days is a variable I am declaring in my TypeScript component file initializing it to the current date minus seven days:

this.todayMinusSeven = new Date();
this.todayMinusSeven.setDate(this.todayMinusSeven.getDate() - 7);

I am trying to figure out how to display my div element of id "notice" from the *ngIf condition in the HTML table.  Essentially, if any product's updatedDate is less than the current date minus seven days, then display the "notice" div.  Here is my HTML:

    There are products that have not been updated in the past seven days...please notify the support department for further information

        ID
        Name
        Updated On

                <ng-container *ngIf="product.updatedOn < todayMinusSeven"; else nonotice;">

                </ng-container>
                <ng-template #nonotice>

                </ng-template>

            {{product.id}}
            {{product.name}}
            {{product.updatedOn}}

Whether or I need to do this in the HTML or the component TypeScript file I am not sure, I am getting the list of products from an HTTP service class and subscribing it to an array of Product objects, so I would prefer not to have to traverse the array for this condition since it is already being traversed in the HTML markup.  Is this possible to do in HTML with Angular 2/4?

Thanks!


问:
Read once and then set to nil
I'd like to implement such property, that it's value is available for reading only one time, and then the property should be set to nil.

I've implemented it in such way:

```<code>private var _readOnce: String?

var readOnce: String? {
    get {
        let value = _readOnce
        _readOnce = nil
        return value
        }
    set {
        _readOnce = newValue
    }
}

readOnce = "Andrej"

print("read once = \(readOnce)")  // prints read once = Optional("Andrej")\n"
print("read once = \(readOnce)")  // prints read once = nil\n"
</code>```

But I'feel like using a separate property _readOnce is not the "swifty" / "most elegant" way to do it.

Does anyone know of a different way, that wouldn't require to use a separate property?

I can confirm that the above code works, it's only that I feel it could be more elegant with less lines to achieve the same behaviour.

答:
As far as I know it is not possible without a second variable. This is because computed properties do not store any data for the variable they represent:

In addition to stored properties, classes, structures, and
  enumerations can define computed properties, which do not actually
  store a value.

For non-computed properties, the only observers you can have are based upon the setting of the variable, not the getting (i.e. willSet and didSet)

Hope that helps!

EDIT:
It can be done with closures and property observers if you're careful:
This requires no other variables (instead the value is captured by the closure), but it is rather unclear — I wouldn't recommend it.

```<code>var readOnce: () -> String? = {nil} {
    didSet{
        readOnce = { [weak self, readOnce] in
            self?.readOnce = {nil}
            return readOnce()
        }
    }
}

readOnce()        // returns nil
readOnce = {"Hi"}
readOnce()        // returns optional wrapped "Hi"
readOnce()        // returns nil
</code>```

A more 'Swifty' answer for you :D

Title: Read once and then set to nil

Body:
I'd like to implement such property, that it's value is available for reading only one time, and then the property should be set to nil.

I've implemented it in such way:

private var _readOnce: String?

var readOnce: String? {
    get {
        let value = _readOnce
        _readOnce = nil
        return value
        }
    set {
        _readOnce = newValue
    }
}

readOnce = "Andrej"

print("read once = \(readOnce)")  // prints read once = Optional("Andrej")\n"
print("read once = \(readOnce)")  // prints read once = nil\n"

But I'feel like using a separate property _readOnce is not the "swifty" / "most elegant" way to do it.

Does anyone know of a different way, that wouldn't require to use a separate property?

I can confirm that the above code works, it's only that I feel it could be more elegant with less lines to achieve the same behaviour.

Body:
As far as I know it is not possible without a second variable. This is because computed properties do not store any data for the variable they represent:

In addition to stored properties, classes, structures, and
  enumerations can define computed properties, which do not actually
  store a value.

For non-computed properties, the only observers you can have are based upon the setting of the variable, not the getting (i.e. willSet and didSet)

Hope that helps!

EDIT:
It can be done with closures and property observers if you're careful:
This requires no other variables (instead the value is captured by the closure), but it is rather unclear — I wouldn't recommend it.

var readOnce: () -> String? = {nil} {
    didSet{
        readOnce = { [weak self, readOnce] in
            self?.readOnce = {nil}
            return readOnce()
        }
    }
}

readOnce()        // returns nil
readOnce = {"Hi"}
readOnce()        // returns optional wrapped "Hi"
readOnce()        // returns nil

A more 'Swifty' answer for you :D


问:
Python two variables one input
I want to save an user input directly into two variables like: </p>

```<code>n,k = input("Geben Sie eine Zahl ein: " )

print(n)
print(k)
</code>```

<p>n and k should print the same value. </p>

答:
You can do this with a double assignment:

```<code>n = k = input("Geben Sie eine Zahl ein: " )
</code>```

Your n,k = ... however is iterable unpacking: only if the user would enter two characters, this would not error: in that case the first character would be assigned to n, and the second character to k. So if you would have written fo, then n would have value 'f' and k would have value 'o'. But for all other cases, this would fail.

Be careful however with mutable objects: if you write:

```<code>a = b = [1,4,2,5]
</code>```

Then both variables refer to the same list object. Only one list is constructed. And if you modify the list through a, then you will see the difference through b as well.

Title: Python two variables one input

Body:
I want to save an user input directly into two variables like:

n,k = input("Geben Sie eine Zahl ein: " )

print(n)
print(k)

n and k should print the same value.

Body:
You can do this with a double assignment:

n = k = input("Geben Sie eine Zahl ein: " )

Your n,k = ... however is iterable unpacking: only if the user would enter two characters, this would not error: in that case the first character would be assigned to n, and the second character to k. So if you would have written fo, then n would have value 'f' and k would have value 'o'. But for all other cases, this would fail.

Be careful however with mutable objects: if you write:

a = b = [1,4,2,5]

Then both variables refer to the same list object. Only one list is constructed. And if you modify the list through a, then you will see the difference through b as well.


问:
Linking OpenBLAS with Qt Creator project
I am using Qt Creator for development. I want to use Armadillo linear algebra library. Therefore I used following code in my pro file:

```<code>INCLUDEPATH += C:\armadillo-7.950.1\include

LIBS += \
    -LC:\armadillo-7.950.1\examples\lib_win64 \
    -llapack_win64_MT \
    -lblas_win64_MT
</code>```

It was all good and the project compiled and linked properly. Next task was to replace LAPACK and BLAS with OpenBLAS. So the pro file was changed as following:

```<code>INCLUDEPATH += C:\armadillo-7.950.1\include \
           C:\OpenBLAS-v0.2.19-Win64-int32\include

LIBS += \
    -LC:\OpenBLAS-v0.2.19-Win64-int32\lib \
    -llibopenblas
</code>```

Now I receive the error: LNK1104: cannot open file 'libopenblas.lib'. I have downloaded windows binary of OpenBLAS. The installed folder structure is as given in the image: installed OpenBLAS folder

Please let me know what is going wrong?

Thanks.

答:
I'm not familiar with OpenBLAS, but your configuration looks correct.
On Windows, or at least with MSVC, you need a .lib file to link to, in addition to the DLL file for runtime. Instead it looks like OpenBLAS installs a mysterious .dll.a file.  Sounds like it should be the same thing:
https://github.com/xianyi/OpenBLAS/wiki/How-to-use-OpenBLAS-in-Microsoft-Visual-Studio
Possibly renaming it would do the trick, but you might need to rebuild from source to get the file.</p>

Body:
I am using Qt Creator for development. I want to use Armadillo linear algebra library. Therefore I used following code in my pro file:

INCLUDEPATH += C:\armadillo-7.950.1\include

LIBS += \
    -LC:\armadillo-7.950.1\examples\lib_win64 \
    -llapack_win64_MT \
    -lblas_win64_MT

It was all good and the project compiled and linked properly. Next task was to replace LAPACK and BLAS with OpenBLAS. So the pro file was changed as following:

INCLUDEPATH += C:\armadillo-7.950.1\include \
           C:\OpenBLAS-v0.2.19-Win64-int32\include

LIBS += \
    -LC:\OpenBLAS-v0.2.19-Win64-int32\lib \
    -llibopenblas

Now I receive the error: LNK1104: cannot open file 'libopenblas.lib'. I have downloaded windows binary of OpenBLAS. The installed folder structure is as given in the image: installed OpenBLAS folder

Please let me know what is going wrong?

Thanks.


问:
Magento 2: How to call js Function that is in my Require.js file from phtml file
My main issue here is when using require.js my function is no longer Global. So when I call it from my phtml file it is not being found. Any idea what the correct way to make a function inside my js file global? I've tried multiple methods/answers I found online but nothing seems to be working out. Any suggestions?

Here is my js file

```<code>define([
  'jquery'
], function ($) {

  return function (config) {
    console.log(config);
  }

  function initMap() {
    console.log('initMap is being called');
  }
});
</code>```

My requirejs-config.js file:

```<code>var config = {
    map: {
        '*': {
            'gslMap': ['Gauge_StoreLocator/js/app']
        }
    }
};
</code>```

My phtml file: The callback function "initMap" is being called at end

```<code><script async defer src="https://maps.googleapis.com/maps/api/js?key=<?php echo $this->getGoogleApi(); ?>&callback=initMap">
</code>```

答:
If you must make your initMap function global, you can do it by deliberately leaking it into the global space:

```<code>define([
  'jquery'
], function ($) {

  return function (config) {
    console.log(config);
  }

  function initMap() {
    console.log('initMap is being called');
  }

  // Deliberately leak initMap into the global space.
  window.initMap = initMap;
});
</code>```

Note, however that RequireJS is always operating asynchronously when used in the browser. So if you just plop your script tag somewhere and hope for the best, you're going to run into trouble. If it is added dynamically by code that loads you module with initMap first, then you'll be fine.

Note that map does not take arrays. paths on the other hand does accept arrays as values but I'm not seeing the point of an array of just one element. (Arrays are meant to provide fallbacks.) The reason RequireJS does not fail loudly due to the array you give in your map is that in JavaScript ["foo"].toString() === "foo" and there is an implicit call to .toString() in the code that processes the values of map so RequireJS sees your array in the same way as if you had just put the single string it contains instead of the array. If you try with an array of more than one element, you'll get into trouble.

Body:
My main issue here is when using require.js my function is no longer Global. So when I call it from my phtml file it is not being found. Any idea what the correct way to make a function inside my js file global? I've tried multiple methods/answers I found online but nothing seems to be working out. Any suggestions?

Here is my js file

define([
  'jquery'
], function ($) {

  return function (config) {
    console.log(config);
  }

  function initMap() {
    console.log('initMap is being called');
  }
});

My requirejs-config.js file:

var config = {
    map: {
        '*': {
            'gslMap': ['Gauge_StoreLocator/js/app']
        }
    }
};

My phtml file: The callback function "initMap" is being called at end

Body:
If you must make your initMap function global, you can do it by deliberately leaking it into the global space:

define([
  'jquery'
], function ($) {

  return function (config) {
    console.log(config);
  }

  function initMap() {
    console.log('initMap is being called');
  }

  // Deliberately leak initMap into the global space.
  window.initMap = initMap;
});

Note, however that RequireJS is always operating asynchronously when used in the browser. So if you just plop your script tag somewhere and hope for the best, you're going to run into trouble. If it is added dynamically by code that loads you module with initMap first, then you'll be fine.

Note that map does not take arrays. paths on the other hand does accept arrays as values but I'm not seeing the point of an array of just one element. (Arrays are meant to provide fallbacks.) The reason RequireJS does not fail loudly due to the array you give in your map is that in JavaScript ["foo"].toString() === "foo" and there is an implicit call to .toString() in the code that processes the values of map so RequireJS sees your array in the same way as if you had just put the single string it contains instead of the array. If you try with an array of more than one element, you'll get into trouble.