问:
Hide Column if Total in the footer of that column is 0
I have a table called mtable and it has 28 columns and also I have a checkbox my questions is this.

How to hide columns if the total of that columns is zero(0)? You know, the footerCallback this is my sample code for testing

```<code>$('input:checkbox').change(function () {
  var expgltable =  $('#mtable').DataTable()
  var column = expgltable.column(2);
  var api = this.api();

  var test = $(api.column(28).footer());
  if (test == 0) {
    column.visible( ! column.visible() );
  }
});
</code>```

trying yo hide the column 28 if it is zero total in footer but seems not working for me.

My target here is This

```<code>/* On checkbox event */
if (checkbox is checked) {
  /* Hide all columns that has 0 total on footers */
} else {
  /* Put it all back */
}
</code>```

TYSM

答:
please see if this helps</p>

```<code>$('#mtable').DataTable( {
    footerCallback: function ( row, data, start, end, display ) {
        var sumofSalary = api
            .column(28)
            .data()
            .reduce( function (a, b) {
                return intVal(a) + intVal(b);
            } );
    });
});

if(sumofSalary == 0) {
    // logic for column hide;
}
</code>```

Body:
I have a table called mtable and it has 28 columns and also I have a checkbox my questions is this.

How to hide columns if the total of that columns is zero(0)? You know, the footerCallback this is my sample code for testing

$('input:checkbox').change(function () {
  var expgltable =  $('#mtable').DataTable()
  var column = expgltable.column(2);
  var api = this.api();

  var test = $(api.column(28).footer());
  if (test == 0) {
    column.visible( ! column.visible() );
  }
});

trying yo hide the column 28 if it is zero total in footer but seems not working for me.

My target here is This

/* On checkbox event */
if (checkbox is checked) {
  /* Hide all columns that has 0 total on footers */
} else {
  /* Put it all back */
}

TYSM

Body:
please see if this helps

$('#mtable').DataTable( {
    footerCallback: function ( row, data, start, end, display ) {
        var sumofSalary = api
            .column(28)
            .data()
            .reduce( function (a, b) {
                return intVal(a) + intVal(b);
            } );
    });
});

if(sumofSalary == 0) {
    // logic for column hide;
}


来源: stackexchange

问:
How can I put a link on the right side?
Here is my code:

a{
    display: block;
    border: 3px solid #ffcb08;
    border-radius: 100px;
    text-align: center;
    color: #222;
    text-decoration: none;
    font-weight: 300;
    font-size: 20px;
    padding: 10px;
    box-sizing: border-box;
    margin-top: 15px;
    transition: all .3s;
    -webkit-transition: all .3s;
    -moz-transition: all .3s;
    width: 160px;
    float: right;
}

p{
    border: 1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
Download
</p></code>```

All I'm trying to do is putting that button on the right side without setting position: absolute; to it. How can I do that?

答:
Add this to your css

```<code>display: block;
float: right;
</code>```

a{
    display: block;
    border: 3px solid #ffcb08;
    border-radius: 100px;
    text-align: center;
    color: #222;
    text-decoration: none;
    font-weight: 300;
    font-size: 20px;
    padding: 10px;
    box-sizing: border-box;
    margin-top: 15px;
    transition: all .3s;
    -webkit-transition: all .3s;
    -moz-transition: all .3s;
    width: 160px;

   display: block;
   float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><text>
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
Download
</text></code>```

ContentLicense: CC BY-SA 3.0

Title: How can I put a link on the right side?

Body:
Here is my code:

a{
    display: block;
    border: 3px solid #ffcb08;
    border-radius: 100px;
    text-align: center;
    color: #222;
    text-decoration: none;
    font-weight: 300;
    font-size: 20px;
    padding: 10px;
    box-sizing: border-box;
    margin-top: 15px;
    transition: all .3s;
    -webkit-transition: all .3s;
    -moz-transition: all .3s;
    width: 160px;
    float: right;
}

p{
    border: 1px solid;
}

some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
Download

All I'm trying to do is putting that button on the right side without setting position: absolute; to it. How can I do that?

Body:
Add this to your css

display: block;
float: right;

a{
    display: block;
    border: 3px solid #ffcb08;
    border-radius: 100px;
    text-align: center;
    color: #222;
    text-decoration: none;
    font-weight: 300;
    font-size: 20px;
    padding: 10px;
    box-sizing: border-box;
    margin-top: 15px;
    transition: all .3s;
    -webkit-transition: all .3s;
    -moz-transition: all .3s;
    width: 160px;

   display: block;
   float: right;
}

<text>
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
<a href="#">Download</a>
</text>


问:
Elasticsearch tutorial OR search (combining must and should)
to get started with elasticsearch and kibana I tried the tutorial. But now I get an error I can't solve on my own.

It's pretty smiliar to this one: elasticsearch bool query combine must with OR

But the solution from Daniel Fackrell doesn't work for me, I am clearly missing something. My Code:

```<code>POST shakespeare/scene/_search/
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "play_name": "Antony"
          },
          "bool": {
            "should": [
              {
                "match": {
                  "speaker": "Demetrius"
                }
              },
              {
                "match": {
                  "speaker": "Antony"
                }
              }
            ]
          }
        }
      ]
    }
  }
}
</code>```

But then I get the following error: "[match] malformed query, expected [END_OBJECT] but found [FIELD_NAME]"

After searching and looking around for a few hours I hope someone can help me.

I'm using version 5.6.4.

Thanks in advance!

Kind regards
Greg

答:
I think you missed a bracket. Check the query below.</p>

```<code>POST shakespeare/scene/_search/
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "play_name": "Antony"
          }
        },
        {
          "bool": {
            "should": [
              {
                "match": {
                  "speaker": "Demetrius"
                }
              },
              {
                "match": {
                  "speaker": "Antony"
                }
              }
            ]
          }
        }
      ]
    }
  }
}
</code>```

Body:
to get started with elasticsearch and kibana I tried the tutorial. But now I get an error I can't solve on my own.

It's pretty smiliar to this one: elasticsearch bool query combine must with OR

But the solution from Daniel Fackrell doesn't work for me, I am clearly missing something. My Code:

POST shakespeare/scene/_search/
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "play_name": "Antony"
          },
          "bool": {
            "should": [
              {
                "match": {
                  "speaker": "Demetrius"
                }
              },
              {
                "match": {
                  "speaker": "Antony"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

But then I get the following error: "[match] malformed query, expected [END_OBJECT] but found [FIELD_NAME]"

After searching and looking around for a few hours I hope someone can help me.

I'm using version 5.6.4.

Thanks in advance!

Kind regards
Greg

Body:
I think you missed a bracket. Check the query below.

POST shakespeare/scene/_search/
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "play_name": "Antony"
          }
        },
        {
          "bool": {
            "should": [
              {
                "match": {
                  "speaker": "Demetrius"
                }
              },
              {
                "match": {
                  "speaker": "Antony"
                }
              }
            ]
          }
        }
      ]
    }
  }
}


问:
Azure Function Targeting .NET Standard Showing Warning
Just installed Visual Studio 15.5 Preview so that I can create an Azure Function targeting .NET Core. Without making any changes, I'm seeing a warning -- see below -- that reads:

Package Microsoft.AspNet.WebApi.Client 5.2.2 was restored using .NET
  Framework version 4.6.1 instead of the project target framework .NET
  Standard version 2.0. This package may not be fully compatible with
  your project.

Any idea how to fix this or do I ignore this warning? As I said, this is a brand new Azure Function project I created with no changes at all.

Here's what the warning looks like:

答:
You can pretty much ignore it, in this case.

Microsoft.AspNet.WebApi.Client targets "Portable Class Library (.NETFramework 4.5, Windows 0.0, WindowsPhone 8.0, WindowsPhone 8.1, WindowsPhoneApp 8.1)" (or net45+win8+win81 as it's the target framework moniker called), which means it's fully compatible with .NET Core and .NET Standard (>= 1.2).

The warning comes, because it do not target the netstandard1.x or netstandard2.x moniker specifically. It just tell you "this might not be compatible on .NET Core/.NET Standard".


答:
EDIT: add overflow: auto to the container.

a{
display: block;
border: 3px solid #ffcb08;
border-radius: 100px;
text-align: center;
color: #222;
text-decoration: none;
font-weight: 300;
font-size: 20px;
padding: 10px;
box-sizing: border-box;
margin-top: 15px;
transition: all .3s;
-webkit-transition: all .3s;
-moz-transition: all .3s;
width: 160px;

float: right;
}

div {
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<text>
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
Download
</text>
</div></code>```

Title: How can I put a link on the right side?

Body:
EDIT: add overflow: auto to the container.

a{
display: block;
border: 3px solid #ffcb08;
border-radius: 100px;
text-align: center;
color: #222;
text-decoration: none;
font-weight: 300;
font-size: 20px;
padding: 10px;
box-sizing: border-box;
margin-top: 15px;
transition: all .3s;
-webkit-transition: all .3s;
-moz-transition: all .3s;
width: 160px;

float: right;
}

div {
  overflow: auto;
}

<div>
<text>
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
<a href="#">Download</a>
</text>
</div>

ContentLicense: CC BY-SA 4.0


问:
Question on my Class implemention in C#
Currently i have a class which has only properties

```<code>class MyEntity
{
    public string FirstName { get; set; }
    public string LastName  { get; set; }
}
</code>```

In my other class, I use to set the values like

```<code>MyEntity objEnt = new MyEntity();
objEnt.FirstName="abc";
objEnt.LastName = "edf";
</code>```

The reason i have the class MyEntity with only properties is to ensure adherence.

Question here is, if this approach is correct? I can have multiple instances of MyEntity

Can i use Static Class for this? How can i use Generics in this?

BTW the implementation is in C#

Thanks in advance

Cheers,

Karthik

答:
You can't use a static class, as you have state. Static classes can only consist of static members.

It's hard to see how you'd use generics here

Personally I prefer types to be immutable where possible - for example by giving MyEntity a constructor with two parameters, and removing the public setters from the properties. (Whether you keep private setters which you just don't use outside the constructor, or move to "proper" readonly fields and readonly properties is another choice.) However this mutable type may be absolutely fine for you - it's impossible to say without knowing what you're trying to do.

Note that you can use object initializers to make your initialization simpler, while you're using the mutable type:

```<code>MyEntity objEnt = new MyEntity { FirstName = "abc", LastName = "edf" };
</code>```

(If you made the type immutable, you'd pass the values in the constructor. You could still use names via C# 4's "named arguments" feature, if you're using C# 4.)

ContentLicense: CC BY-SA 2.5

Title: Question on my Class implemention in C#

Body:
Currently i have a class which has only properties

class MyEntity
{
    public string FirstName { get; set; }
    public string LastName  { get; set; }
}

In my other class, I use to set the values like

MyEntity objEnt = new MyEntity();
objEnt.FirstName="abc";
objEnt.LastName = "edf";

The reason i have the class MyEntity with only properties is to ensure adherence.

Question here is, if this approach is correct? I can have multiple instances of MyEntity

Can i use Static Class for this? How can i use Generics in this?

BTW the implementation is in C#

Thanks in advance

Cheers,

Karthik

Body:
You can't use a static class, as you have state. Static classes can only consist of static members.

It's hard to see how you'd use generics here

Personally I prefer types to be immutable where possible - for example by giving MyEntity a constructor with two parameters, and removing the public setters from the properties. (Whether you keep private setters which you just don't use outside the constructor, or move to "proper" readonly fields and readonly properties is another choice.) However this mutable type may be absolutely fine for you - it's impossible to say without knowing what you're trying to do.

Note that you can use object initializers to make your initialization simpler, while you're using the mutable type:

MyEntity objEnt = new MyEntity { FirstName = "abc", LastName = "edf" };

(If you made the type immutable, you'd pass the values in the constructor. You could still use names via C# 4's "named arguments" feature, if you're using C# 4.)


问:
Grails 3 - documenting spring security rest's login api in swagger
I am developing demo REST Demo using Grails 3 with service Spring Security REST and Swagger Documentation. Following are the dependencies for spring security rest

org.grails.plugins:spring-security-rest:2.0.0.M2

org.grails.plugins:spring-security-rest-gorm:2.0.0.M2

where user has to login in order to to perform certain subset of operations. After adding Swagger Doc using following plugin and configuring to access all the expoosed APIs I am able to access all API's swagger doc with "localhost://applicationPath/api"

org.grails.plugins:swaggydoc-grails3:0.28.0

Unfortunately I don't have login endpoints listed among them. If I add my LoginController along with the apis endpoints controller than it is listing all the login apis but than access url becomes

APPLICATIONURL/api/v1/api/login

Which does not works well.

The problem is that part of that operations cannot be performed via Swagger UI built-in form (I find it really nice feature and would like make it work), because user is not logged in. Is there any solution to that problem? Can I define manually some endpoints in Swagger?

This is my sample code for registring any API with Swagger

```<code>@Api(
        value = 'Sample',
        description = 'Sample APIs.',
        position = 0,
        produces = 'application/json',
        consumes = 'application/json',
        basePath = 'v1',
        protocols = 'http, https',
        hidden = false
)
@Controller()
class SampleController {
@ApiOperation(
            value = 'Sample API',
            notes = '',
            response = Sample,
            responseContainer = 'Array',
            position = 0,
            httpMethod = 'GET',
            produces = 'application/json',
            consumes = 'application/json',
            protocols = 'http, https',
            hidden = false
    )
    @ApiImplicitParams([
            @ApiImplicitParam(name = 'max', value = 'Max records to return', defaultValue = '10', paramType = 'query', dataType = 'int', required = false, allowMultiple = false)
    ])
    @ApiResponses([
            @ApiResponse(code = 200, message = "", response = Sample),
    ])
    def sampleAPI() {
    }
}
</code>```

If Anybody can help on it, it would be great help.

答: I created an API which calls "api/login" to have authentication</p>

Body:
I am developing demo REST Demo using Grails 3 with service Spring Security REST and Swagger Documentation. Following are the dependencies for spring security rest

org.grails.plugins:spring-security-rest:2.0.0.M2

org.grails.plugins:spring-security-rest-gorm:2.0.0.M2

where user has to login in order to to perform certain subset of operations. After adding Swagger Doc using following plugin and configuring to access all the expoosed APIs I am able to access all API's swagger doc with "localhost://applicationPath/api"

org.grails.plugins:swaggydoc-grails3:0.28.0

Unfortunately I don't have login endpoints listed among them. If I add my LoginController along with the apis endpoints controller than it is listing all the login apis but than access url becomes

APPLICATIONURL/api/v1/api/login

Which does not works well.

The problem is that part of that operations cannot be performed via Swagger UI built-in form (I find it really nice feature and would like make it work), because user is not logged in. Is there any solution to that problem? Can I define manually some endpoints in Swagger?

This is my sample code for registring any API with Swagger

@Api(
        value = 'Sample',
        description = 'Sample APIs.',
        position = 0,
        produces = 'application/json',
        consumes = 'application/json',
        basePath = 'v1',
        protocols = 'http, https',
        hidden = false
)
@Controller()
class SampleController {
@ApiOperation(
            value = 'Sample API',
            notes = '',
            response = Sample,
            responseContainer = 'Array',
            position = 0,
            httpMethod = 'GET',
            produces = 'application/json',
            consumes = 'application/json',
            protocols = 'http, https',
            hidden = false
    )
    @ApiImplicitParams([
            @ApiImplicitParam(name = 'max', value = 'Max records to return', defaultValue = '10', paramType = 'query', dataType = 'int', required = false, allowMultiple = false)
    ])
    @ApiResponses([
            @ApiResponse(code = 200, message = "", response = Sample),
    ])
    def sampleAPI() {
    }
}

If Anybody can help on it, it would be great help.


问:
tensorflow, How to index the true value of a tensor?
I have a 1-d tensor like:

```<code>[false, false, true, false, true, false]
</code>```

How to find the index of all the true value?

My solution is:

Turn it to 1 and 0 value

Use argmax API to find one index and then set the one to false/0.

Use argmax again to find the next true/1 value

But this solution is not that good.

答:
```<code>In [1]: import tensorflow as tf

In [2]: a = tf.constant([False, False, True, True])

In [3]: a_n = [tf.cond(tf.equal(v, tf.constant(True)), lambda: tf.constant(k), lambda: tf.constant(-1)) for k, v in enumerate(tf.unstack(a))]

In [4]: sess = tf.Session()

In [5]: sess.run(a_n)
Out[5]: [-1, -1, 2, 3]
</code>```

Hope this helps...

Body:
I have a 1-d tensor like:

[false, false, true, false, true, false]

How to find the index of all the true value?

My solution is:

Turn it to 1 and 0 value

Use argmax API to find one index and then set the one to false/0.

Use argmax again to find the next true/1 value

But this solution is not that good.

Body:
In [1]: import tensorflow as tf

In [2]: a = tf.constant([False, False, True, True])

In [3]: a_n = [tf.cond(tf.equal(v, tf.constant(True)), lambda: tf.constant(k), lambda: tf.constant(-1)) for k, v in enumerate(tf.unstack(a))]

In [4]: sess = tf.Session()

In [5]: sess.run(a_n)
Out[5]: [-1, -1, 2, 3]

Hope this helps...


问:
Swift - How to dismiss all of view controllers to go back to root
I want a my app can go to a first view controller when every time users want it.

So I want to create a function to dismiss all the view controllers, regardless of whether it is pushed in navigation controllers or presented modally or opened anything methods.

I tried various ways, but I failed to dismiss all the view controllers certainly.
Is there an easy way?

答:
To achieve what you want, modify your navigation stack, then do popViewController.

```<code>let allControllers = NSMutableArray(array: navigationController!.viewControllers)
let vcCount = allControllers.count
for _ in 0 ..< vcCount - 2 {
    allControllers.removeObject(at: 1)
}
// now, allControllers[0] is root VC, allControllers[1] is presently displayed VC. write back to nav stack
navigationController!.setViewControllers(allControllers as [AnyObject] as! [UIViewController], animated: false)
// then pop root VC
navigationController!.popViewController(animated: true)
</code>```

See this for the way to further manipulate the navigation stack. If your topmost VC is modal, dismiss it first before the code above.

Body:
To achieve what you want, modify your navigation stack, then do popViewController.

let allControllers = NSMutableArray(array: navigationController!.viewControllers)
let vcCount = allControllers.count
for _ in 0 ..< vcCount - 2 {
    allControllers.removeObject(at: 1)
}
// now, allControllers[0] is root VC, allControllers[1] is presently displayed VC. write back to nav stack
navigationController!.setViewControllers(allControllers as [AnyObject] as! [UIViewController], animated: false)
// then pop root VC
navigationController!.popViewController(animated: true)

See this for the way to further manipulate the navigation stack. If your topmost VC is modal, dismiss it first before the code above.


问:
Matching the string after the last equation mark to key1 in a nested dictionary
I am trying to append directory name to filename for select filetypes and camera models based on a dictionary.

The files are stored in a directory with the following pattern. Directory names always end with = mark followed by key1:

```<code>0001=d5                             #d5 is an ID for the camera model
 DSCN001                            #dir name needs to be appended to filenames below
    [media files]
0002=blahblahblah=alpha9            #alpha9 is an ID for the camera model
  SONYDATA
    STREAM001                       #dir name needs to be appended to filenams below
      [media files]
</code>```

The code below recognized the last 2 characters of the directory that specifies the camera model and matches against key1 in the dictionary table. In case of alpha9 it does not work because alpha9 is longer than 2 characters.

Q: How can I  change the code, so instead it recognizes any string after the last equation = mark in the directory's name and matches that against key1?

Code:

```<code>config = {
    'd5': {},
    'alpha9': {},
}
config['d5']['append_dir_to_file'] = 1
config['d5']['append_dir_for'] = ('nef', 'NEF', 'jpg', 'JPG')
config['alpha9']['append_dir_to_file'] = 1
config['alpha9']['append_dir_for'] = ('mp4', 'MP4')

folder_keys = config.keys()
target = os.getcwd()

def sb_travel(dirs, flag=False, target=False, k=False):
    for p1 in dirs:
        if not flag and p1[-2:] in folder_keys:
            main =  next(os.walk("%s/%s"%(target,p1)))[1]
            sb_travel(main, True, "%s/%s"%(target,p1), p1[-2:])
        if flag:
            dirslist = next(os.walk("%s/%s"%(target,p1)))
            main =  dirslist[1]
            if config[k]['append_dir_to_file']:
                for f in dirslist[2]:
                    ext = f.split('.')[1] if len(f.split('.')) > 1 else False
                    if ext and ext in config[k]['append_dir_for']:
                        old_file = "%s/%s/%s"%(target,p1,f)
                        new_file = "%s/%s/%s_%s"% (target,p1,p1,f)
                        os.rename(old_file, new_file)
            sb_travel(main, True, "%s/%s"%(target,p1),k)
if not os.path.exists(target):
    print ("Invalid Directory Location")
main =  next(os.walk(target))[1]
sb_travel(main, False, target)
</code>```

答:
Simply p1.split('=')[-1] in folder_keys

This matches the whole string if there is no equation mark, so you might want to check that first with '=' in p1

edit: Given input dirs = ['0001=d5', '0002=alpha9'] my code:

```<code>for p1 in dirs:
    print(p1.split('=')[-1])
</code>```

gives output:

```<code>d5
alpha9
</code>```

Which is what you asked for originally. I won't help you debug your script.

Body:
I am trying to append directory name to filename for select filetypes and camera models based on a dictionary.

The files are stored in a directory with the following pattern. Directory names always end with = mark followed by key1:

0001=d5                             #d5 is an ID for the camera model
 DSCN001                            #dir name needs to be appended to filenames below
    [media files]
0002=blahblahblah=alpha9            #alpha9 is an ID for the camera model
  SONYDATA
    STREAM001                       #dir name needs to be appended to filenams below
      [media files]

The code below recognized the last 2 characters of the directory that specifies the camera model and matches against key1 in the dictionary table. In case of alpha9 it does not work because alpha9 is longer than 2 characters.

Q: How can I  change the code, so instead it recognizes any string after the last equation = mark in the directory's name and matches that against key1?

Code:

config = {
    'd5': {},
    'alpha9': {},
}
config['d5']['append_dir_to_file'] = 1
config['d5']['append_dir_for'] = ('nef', 'NEF', 'jpg', 'JPG')
config['alpha9']['append_dir_to_file'] = 1
config['alpha9']['append_dir_for'] = ('mp4', 'MP4')

folder_keys = config.keys()
target = os.getcwd()

def sb_travel(dirs, flag=False, target=False, k=False):
    for p1 in dirs:
        if not flag and p1[-2:] in folder_keys:
            main =  next(os.walk("%s/%s"%(target,p1)))[1]
            sb_travel(main, True, "%s/%s"%(target,p1), p1[-2:])
        if flag:
            dirslist = next(os.walk("%s/%s"%(target,p1)))
            main =  dirslist[1]
            if config[k]['append_dir_to_file']:
                for f in dirslist[2]:
                    ext = f.split('.')[1] if len(f.split('.')) > 1 else False
                    if ext and ext in config[k]['append_dir_for']:
                        old_file = "%s/%s/%s"%(target,p1,f)
                        new_file = "%s/%s/%s_%s"% (target,p1,p1,f)
                        os.rename(old_file, new_file)
            sb_travel(main, True, "%s/%s"%(target,p1),k)
if not os.path.exists(target):
    print ("Invalid Directory Location")
main =  next(os.walk(target))[1]
sb_travel(main, False, target)

Body:
Simply p1.split('=')[-1] in folder_keys

This matches the whole string if there is no equation mark, so you might want to check that first with '=' in p1

edit: Given input dirs = ['0001=d5', '0002=alpha9'] my code:

for p1 in dirs:
    print(p1.split('=')[-1])

gives output:

d5
alpha9

Which is what you asked for originally. I won't help you debug your script.


问:
Removing max and min elements of array from mean calculation
I am hoping to delete the highest number and the lowest number from the array 3*4. Let's say, the data looks like this:

```<code>a=np.array([[1,4,5,10],[2,6,5,0],[3,9,9,0]])
</code>```

so I expected to see the result like this:
    deleted_data=[4,5],[2,5],[3]

Could you advise me how to delete the max and min from each array?

to do so, I did like this (UPDATE):

```<code>#to find out the max / min values:
b = np.max(a,1) #max
c = np.min(a,1) #min

#creating dataset after deleting max & min
d=(a!=b[:,None]) & (a!=c[:,None])
f=[i[j] for i,j in zip(a, d)]

output: [array([8, 7, 7, 9, 9, 8]), array([8, 7, 8, 6, 8, 8]), array([9, 8, 9, 9, 8]), array([6, 7, 7, 6, 6, 7]), array([7, 7, 7, 7, 6])]
</code>```

Now I am not sure how to calculate the mean of the list objects?
I would like to calculate the mean of each array, so I have tried this:

```<code>mean1=f.mean(axis=0)
</code>```

but it did not work.

答:
As @hpaulj predicted, there is an array-only method.  And it's a doozy.  As a one-liner:

```<code>a[np.arange(a.shape[0])[:, None], np.sort(np.argpartition(a, (0,-1), axis = 1)[:, 1:-1], axis = 1)]
</code>```

Let's break that down:

```<code>y_ = np.argpartition(a, (0,-1), axis = 1)[:, 1:-1]
</code>```

argpartiton takes the index of the 0th (smallest) and -1th (largest) elements of each row and moves them to the first and last position repsectively.  [:,1:-1] indexes everything else.  Now argpartition can sometimes reorder the rest of the elements, so

```<code>y = np.sort(y_ , axis = 1)
</code>```

We sort the rest of the indices back to their orginal positions.  Now we have a y.shape -> (m, n-2) array of indices with the max and min removed, for your original (m, n) = a.shape array.

Now to use this, we need the row indicies as well.

```<code>x = np.arange(a.shape[0])[:, None]
</code>```

arange just gives the m row indices. To broadcast this x.shape -> (a.shape[0],) -> (m,) array to your index array, you need the [:, None] to make x.shape -> (m, 1).  Now the m lines up for broadcasting and you have your two sets of indices.

```<code>a[x, y]

array([[4, 5],
       [2, 5],
       [3, 9]])
</code>```

Body:
I am hoping to delete the highest number and the lowest number from the array 3*4. Let's say, the data looks like this:

a=np.array([[1,4,5,10],[2,6,5,0],[3,9,9,0]])

so I expected to see the result like this:
    deleted_data=[4,5],[2,5],[3]

Could you advise me how to delete the max and min from each array?

to do so, I did like this (UPDATE):

#to find out the max / min values:
b = np.max(a,1) #max
c = np.min(a,1) #min

#creating dataset after deleting max & min
d=(a!=b[:,None]) & (a!=c[:,None])
f=[i[j] for i,j in zip(a, d)]

output: [array([8, 7, 7, 9, 9, 8]), array([8, 7, 8, 6, 8, 8]), array([9, 8, 9, 9, 8]), array([6, 7, 7, 6, 6, 7]), array([7, 7, 7, 7, 6])]

Now I am not sure how to calculate the mean of the list objects?
I would like to calculate the mean of each array, so I have tried this:

mean1=f.mean(axis=0)

but it did not work.

Body:
As @hpaulj predicted, there is an array-only method.  And it's a doozy.  As a one-liner:

a[np.arange(a.shape[0])[:, None], np.sort(np.argpartition(a, (0,-1), axis = 1)[:, 1:-1], axis = 1)]

Let's break that down:

y_ = np.argpartition(a, (0,-1), axis = 1)[:, 1:-1]

argpartiton takes the index of the 0th (smallest) and -1th (largest) elements of each row and moves them to the first and last position repsectively.  [:,1:-1] indexes everything else.  Now argpartition can sometimes reorder the rest of the elements, so

y = np.sort(y_ , axis = 1)

We sort the rest of the indices back to their orginal positions.  Now we have a y.shape -> (m, n-2) array of indices with the max and min removed, for your original (m, n) = a.shape array.

Now to use this, we need the row indicies as well.

x = np.arange(a.shape[0])[:, None]

arange just gives the m row indices. To broadcast this x.shape -> (a.shape[0],) -> (m,) array to your index array, you need the [:, None] to make x.shape -> (m, 1).  Now the m lines up for broadcasting and you have your two sets of indices.

a[x, y]

array([[4, 5],
       [2, 5],
       [3, 9]])


问:
Background applied to the controller not getting applied to table view cells in storyboard swift
I have a storyboard consisting of a background image on top of which rests a table. My issue is that the background image gets applied to the table but not to the cells of the table, they still remain white.

What is it that I am doing wrong?
Please help

答:
You should do clear back ground color of your cell by below delegate method.</p>

```<code>func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell,
               forRowAt indexPath: IndexPath) {
    cell.backgroundColor = UIColor.clear
}
</code>```

Body:
You should do clear back ground color of your cell by below delegate method.

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell,
               forRowAt indexPath: IndexPath) {
    cell.backgroundColor = UIColor.clear
}


问:
compare strings in python with a text file
i have a text file with following data:
deric,
robert,
mathew,

Now, i want the user to input a string and then compare that string with the text file..

```<code> fo = open("d:\\ar.txt", "r")
 file_contents = fo.read()
 print('Enter your password.')
 typedPassword = input()
 for i in file_contents:
     if typedPassword == file_contents:
         print('Access granted')
     else:
         print('Access denied')
</code>```

However, this doesn't seem to work. any thoughts?

答:
You were checking if the inputted password maches the whole file...
This checks each line

```<code>username = input("Input your username")
password = input("Input your password")
correct = None
with open("d:\\ar.txt", "r") as file:
    for line in file:
        line = line.split(",")
        if username == line[0] and password == line[1]:
            correct = True
if correct:
    print("") # placeholder
    #(logged in code)
</code>```

for this to work your file should be of the fornat

username,password,

username,password,

username,password,

Body:
i have a text file with following data:
deric,
robert,
mathew,

Now, i want the user to input a string and then compare that string with the text file..

 fo = open("d:\\ar.txt", "r")
 file_contents = fo.read()
 print('Enter your password.')
 typedPassword = input()
 for i in file_contents:
     if typedPassword == file_contents:
         print('Access granted')
     else:
         print('Access denied')

However, this doesn't seem to work. any thoughts?

Body:
You were checking if the inputted password maches the whole file...
This checks each line

username = input("Input your username")
password = input("Input your password")
correct = None
with open("d:\\ar.txt", "r") as file:
    for line in file:
        line = line.split(",")
        if username == line[0] and password == line[1]:
            correct = True
if correct:
    print("") # placeholder
    #(logged in code)

for this to work your file should be of the fornat

username,password,

username,password,

username,password,


问:
How to pass an object to dynamic code in C#
im using System.CodeDom.Compiler to generate a dynamic code , i need to pass some objects to the functions in code , but when i pass objects they refer to my current name space ...

```<code>string code = @"
            using System;
            using " + type + @";
            namespace First
            {
                public class Program
                {
                    static " + type + ".Class1 " + type.ToLower() + " = (" + type + ".Class1)"+o + @";
                    public static bool check () {
                        if( " + exp
                        +
                        @")
                            return true;
                        else
                            return false;
                    }
                    public static void Main()
                    {
                    " +
                       "    Console.WriteLine(\"Hello, world!\");"
                      + @"
                    }
                }
            }
        ";
</code>```

and i get this error : The name 'MineRuleEngine'(my current name space) does not exist in the current context

答:
i pass the object directly to the method and invoke that by reflection

```<code>public static bool check (Object o) {
</code>```

and put the parameter "o" inside string , and remove static modifier

```<code>type + " " + type.ToLower() + " = " + "(" + type + ")o ;"
</code>```

Body:
im using System.CodeDom.Compiler to generate a dynamic code , i need to pass some objects to the functions in code , but when i pass objects they refer to my current name space ...

string code = @"
            using System;
            using " + type + @";
            namespace First
            {
                public class Program
                {
                    static " + type + ".Class1 " + type.ToLower() + " = (" + type + ".Class1)"+o + @";
                    public static bool check () {
                        if( " + exp
                        +
                        @")
                            return true;
                        else
                            return false;
                    }
                    public static void Main()
                    {
                    " +
                       "    Console.WriteLine(\"Hello, world!\");"
                      + @"
                    }
                }
            }
        ";

and i get this error : The name 'MineRuleEngine'(my current name space) does not exist in the current context

Body:
i pass the object directly to the method and invoke that by reflection

public static bool check (Object o) {

and put the parameter "o" inside string , and remove static modifier

type + " " + type.ToLower() + " = " + "(" + type + ")o ;"


答:
a{
    display: block;
    border: 3px solid #ffcb08;
    border-radius: 100px;
    text-align: center;
    color: #222;
    text-decoration: none;
    font-weight: 300;
    font-size: 20px;
    padding: 10px;
    box-sizing: border-box;
    margin-top: 15px;
    transition: all .3s;
    -webkit-transition: all .3s;
    -moz-transition: all .3s;
    width: 160px;
float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><text>
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
Download
</text></code>```

simply use: float: right;

Title: How can I put a link on the right side?

Body:
Here is my code:

a{
    display: block;
    border: 3px solid #ffcb08;
    border-radius: 100px;
    text-align: center;
    color: #222;
    text-decoration: none;
    font-weight: 300;
    font-size: 20px;
    padding: 10px;
    box-sizing: border-box;
    margin-top: 15px;
    transition: all .3s;
    -webkit-transition: all .3s;
    -moz-transition: all .3s;
    width: 160px;
    float: right;
}

p{
    border: 1px solid;
}

some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
Download

All I'm trying to do is putting that button on the right side without setting position: absolute; to it. How can I do that?

Body:
a{
    display: block;
    border: 3px solid #ffcb08;
    border-radius: 100px;
    text-align: center;
    color: #222;
    text-decoration: none;
    font-weight: 300;
    font-size: 20px;
    padding: 10px;
    box-sizing: border-box;
    margin-top: 15px;
    transition: all .3s;
    -webkit-transition: all .3s;
    -moz-transition: all .3s;
    width: 160px;
float: right;
}

<text>
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
<a href="#">Download</a>
</text>

simply use: float: right;


问:
How to install teletype package in Atom?
I want to install teletype package for atom for real-time collaboration

but package installer doesn't find this package to install. I would appreciate any help. Thank you.

答: It's likely that you don't have the correct version of Atom installed.  For teletype, you need at least version 1.22, and then follow the installation instructions here.</p>


问:
Jenkins: MSTest: Unable to specify mutiple test result files to be converted to JUnit XML format
While automating build process using Jenkins, we are using MSTest plugin to convert the generated *.trx files to JUnit xml format so that it can be shown in build report.
This plugin is working fine with a single file. eg: MyProject/TestResults.trx. (%WORKSPACE% is implicit as used by the plugin)

But now since we have multiple(2) test project for the same application.(integration & unit)
I want to combine both the test results and show the combined result.

For that I am trying the following Ant Fileset pattern.

```<code><fileset dir="C:\Program Files (x86)\Jenkins\workspace\JenkinsJobWorkSpaceDir\">
<filename name="*.trx" />
</fileset>
</code>```

But this is not working showing the following message:

[MSTEST-PLUGIN] No MSTest TRX test report files were found. Ignoring.

Here are my two files:
C:\Program Files (x86)\Jenkins\workspace\JenkinsJobWorkSpaceDir\TestResult1.trx
C:\Program Files (x86)\Jenkins\workspace\JenkinsJobWorkSpaceDir\TestResult2.trx

答:
As per instruction given under the text box for file in mstest plugin for jenkins:

it says Ant fileset pattern, which doesn't mean including that fileset tag instead use wildcard expression to include all the files in a folder.

Body:
While automating build process using Jenkins, we are using MSTest plugin to convert the generated *.trx files to JUnit xml format so that it can be shown in build report.
This plugin is working fine with a single file. eg: MyProject/TestResults.trx. (%WORKSPACE% is implicit as used by the plugin)

But now since we have multiple(2) test project for the same application.(integration & unit)
I want to combine both the test results and show the combined result.

For that I am trying the following Ant Fileset pattern.

<fileset dir="C:\Program Files (x86)\Jenkins\workspace\JenkinsJobWorkSpaceDir\">
<filename name="*.trx" />
</fileset>

But this is not working showing the following message:

[MSTEST-PLUGIN] No MSTest TRX test report files were found. Ignoring.

Here are my two files:
C:\Program Files (x86)\Jenkins\workspace\JenkinsJobWorkSpaceDir\TestResult1.trx
C:\Program Files (x86)\Jenkins\workspace\JenkinsJobWorkSpaceDir\TestResult2.trx


问:
SHA-256 Hash and base64 encoding
With the string "123456Adrian Wapcaplet" I need to

generate the SHA-256 hash

take the least significant 128 bits of the hash

represent these bits in base64 encoding

I need help with #1 and #3. Below is how I generate this in Linux

```<code>$ echo -n "123456Adrian Wapcaplet" | shasum -a 256 | cut -c33-64 | xxd -r -p | base64

jNWe9TyaqmgxG3N2fgl15w==
</code>```

答:
Install the pgcrypto extension:

```<code>create extension pgcrypto;
</code>```

Then you can use the digest function to do sha256. The rest of the functions you'll need are built in:

```<code>select encode(substring(digest('123456Adrian Wapcaplet', 'sha256') from 17), 'base64');
</code>```

Note that there's an implicit cast from text to bytea performed here when calling digest. It will use the default encoding for the database. To avoid problems due to environmental differences you can specify the encoding for the conversion:

```<code>digest(convert_to('123456Adrian Wapcaplet', 'utf8'), 'sha256')
</code>```

Title: SHA-256 Hash and base64 encoding

Body:
With the string "123456Adrian Wapcaplet" I need to

generate the SHA-256 hash

take the least significant 128 bits of the hash

represent these bits in base64 encoding

I need help with #1 and #3. Below is how I generate this in Linux

$ echo -n "123456Adrian Wapcaplet" | shasum -a 256 | cut -c33-64 | xxd -r -p | base64

jNWe9TyaqmgxG3N2fgl15w==

Body:
Install the pgcrypto extension:

create extension pgcrypto;

Then you can use the digest function to do sha256. The rest of the functions you'll need are built in:

select encode(substring(digest('123456Adrian Wapcaplet', 'sha256') from 17), 'base64');

Note that there's an implicit cast from text to bytea performed here when calling digest. It will use the default encoding for the database. To avoid problems due to environmental differences you can specify the encoding for the conversion:

digest(convert_to('123456Adrian Wapcaplet', 'utf8'), 'sha256')


答:
You can do it in multiple ways, here's the Flexbox way:

text {
  display: flex;
  flex-direction: column; /* vertical stacking */
  /* align-items: flex-end; affects all flex-items */
}

a {
  align-self: flex-end; /* affects only this flex-item */
  display: block;
  border: 3px solid #ffcb08;
  border-radius: 100px;
  text-align: center;
  color: #222;
  text-decoration: none;
  font-weight: 300;
  font-size: 20px;
  padding: 10px;
  box-sizing: border-box;
  margin-top: 15px;
  transition: all .3s;
  -webkit-transition: all .3s;
  -moz-transition: all .3s;
  width: 160px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><text>
  some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
  Download
</text></code>```

Title: How can I put a link on the right side?

Body:
You can do it in multiple ways, here's the Flexbox way:

text {
  display: flex;
  flex-direction: column; /* vertical stacking */
  /* align-items: flex-end; affects all flex-items */
}

a {
  align-self: flex-end; /* affects only this flex-item */
  display: block;
  border: 3px solid #ffcb08;
  border-radius: 100px;
  text-align: center;
  color: #222;
  text-decoration: none;
  font-weight: 300;
  font-size: 20px;
  padding: 10px;
  box-sizing: border-box;
  margin-top: 15px;
  transition: all .3s;
  -webkit-transition: all .3s;
  -moz-transition: all .3s;
  width: 160px;
}

<text>
  some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
  <a href="#">Download</a>
</text>


问:
how would i remove some portion of
 from a table in php?
this is my table -

```<code> <table>
     <tr>
      <td>ABC</td>
     </tr>
     <tr>
      <td> </td>
     </tr>
 </table>
</code>```

and I want to remove this one table row:

```<code><tr>
   <td> </td>
</tr>
</code>```

my expected output is:

```<code> <table>
   <tr>
     <td>ABC</td>
   </tr>
 </table>
</code>```

is it possible??please help me

答:
When rendering the table, add a unique class for the rows you wish to delete. Lets say the class is: _rowToDelete, and then using jQuery, remove all the rows that have this class.

In the below example, when you click on the button the rows are being removed, so you can see the changes. But you can do the same on page load if you wish so.

$(function() {
  $("#removeBtn").click(function() {
    $("._rowToDelete").remove() ;
  });
}) ;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
     <tr>
      <td>ABC 1</td>
     </tr>
     <tr class="_rowToDelete">
      <td> </td>
     </tr>
     <tr>
      <td>ABC 2</td>
     </tr>
     <tr class="_rowToDelete">
      <td> </td>
     </tr>
     <tr>
      <td>ABC 3</td>
     </tr>
     <tr class="_rowToDelete">
      <td> </td>
     </tr>
 </table>

 Remove</code>```

Title: how would i remove some portion of <tr><td> from a table in php?

Body:
this is my table -

      ABC

and I want to remove this one table row:

my expected output is:

     ABC

is it possible??please help me

Body:
When rendering the table, add a unique class for the rows you wish to delete. Lets say the class is: _rowToDelete, and then using jQuery, remove all the rows that have this class.

In the below example, when you click on the button the rows are being removed, so you can see the changes. But you can do the same on page load if you wish so.

$(function() {
  $("#removeBtn").click(function() {
    $("._rowToDelete").remove() ;
  });
}) ;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
     <tr>
      <td>ABC 1</td>
     </tr>
     <tr class="_rowToDelete">
      <td>&nbsp;</td>
     </tr>
     <tr>
      <td>ABC 2</td>
     </tr>
     <tr class="_rowToDelete">
      <td>&nbsp;</td>
     </tr>
     <tr>
      <td>ABC 3</td>
     </tr>
     <tr class="_rowToDelete">
      <td>&nbsp;</td>
     </tr>
 </table>

 <a href="javascript:;" id="removeBtn">Remove</a>


问:
Open only one activity, without the main activity
I have an application that has one service and 2 activities.One activity (the main one) is a preferences activity and the other one is a dialog themed activity. The service from time to time needs to open only the dialog themed activity (using FLAG_ACTIVITY_NEW_TASK).
The problem is that when the preferences activity is opened in background (for example the user pressed HOME key instead of BACK, so the activity is OnPause) and the service tries to open the dialog themed activity, also the main activity is opened (comes in foreground).
I don't want this. So, how can I open only the themed activity from the service, without the main activity pop up ?

Android Manifest .xml

```<code>    <service android:name=".SimpleService"> </service>
<activity
    android:name=".Preferences" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

           <activity android:name=".popup_activity" android:theme="@android:style/Theme.Dialog" android:label="@string/app_name">
           <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.SAMPLE_CODE" />
           </intent-filter>
           <intent-filter>
                    <action android:name="android.intent.action.VIEW" />
                    <category android:name="screenon.popup.activity" />
                    <category android:name="android.intent.category.DEFAULT" />
           </intent-filter>
            </activity>
</code>```

And from the service :

```<code>           Intent intent = new Intent(Intent.ACTION_VIEW);
               intent.addCategory("screenon.popup.activity");
               intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

               startActivity(intent);
</code>```

答:
Alex , I believe that all you want is to display preferences activity just once & then it must die(or lets say finish()) .

In that case you can override onResume of the preferences activity
to finish your preferences activity after it is resumed after pause

```<code>@Override
    public void onResume()
{
   //if activity is resumed after onPause then only run it
  this.finish();  //simply kill your activity if it is resumed after pause
}
</code>```

EDIT-To know whether the activity was paused you need to override onPause().I think you can dig out the rest.

Hope it helps!

Body:
I have an application that has one service and 2 activities.One activity (the main one) is a preferences activity and the other one is a dialog themed activity. The service from time to time needs to open only the dialog themed activity (using FLAG_ACTIVITY_NEW_TASK).
The problem is that when the preferences activity is opened in background (for example the user pressed HOME key instead of BACK, so the activity is OnPause) and the service tries to open the dialog themed activity, also the main activity is opened (comes in foreground).
I don't want this. So, how can I open only the themed activity from the service, without the main activity pop up ?

Android Manifest .xml

    <service android:name=".SimpleService"> </service>
<activity
    android:name=".Preferences" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

           <activity android:name=".popup_activity" android:theme="@android:style/Theme.Dialog" android:label="@string/app_name">
           <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.SAMPLE_CODE" />
           </intent-filter>
           <intent-filter>
                    <action android:name="android.intent.action.VIEW" />
                    <category android:name="screenon.popup.activity" />
                    <category android:name="android.intent.category.DEFAULT" />
           </intent-filter>
            </activity>

And from the service :

           Intent intent = new Intent(Intent.ACTION_VIEW);
               intent.addCategory("screenon.popup.activity");
               intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

               startActivity(intent);

Body:
Alex , I believe that all you want is to display preferences activity just once & then it must die(or lets say finish()) .

In that case you can override onResume of the preferences activity
to finish your preferences activity after it is resumed after pause

@Override
    public void onResume()
{
   //if activity is resumed after onPause then only run it
  this.finish();  //simply kill your activity if it is resumed after pause
}

EDIT-To know whether the activity was paused you need to override onPause().I think you can dig out the rest.

Hope it helps!


问:
Understanding * (zero or more) operator using re.search()
I am new to python and was going through "Google for Education" python course

Now, the line below confuses me:

* -- 0 or more occurrences of the pattern to its left

(all the examples are in python3)

e.g. 1

```<code>In [1]: re.search(r"pi*", "piiig!!").group()
Out[1]: 'piii'
</code>```

This is fine since, "pi" has 1 occurrance so it is retured

e.g. 2

```<code>In [2]: re.search(r"i*", "piiig!!").group()
Out[2]: ''
</code>```

Why does it not return "i" in fact - from my understanding, it should be returning "iii". But the result is an empty string.

Also, What exactly does "0 or more" mean? I searched on google but everywhere it is mentioned * -- 0 or more. But if there is 0 occurrence of an expression, does that not become true even if it's not there? What is the point of searching then?

I am so confused with this. Can you please help me with explaining this or point me in the right direction.

i hope the right explanation would also resolve my this issue:

```<code>In [3]: re.search(r"i?", "piiig!!").group()
Out[3]: ''
</code>```

I have tried the examples in Spyder 3.2.4

答:
The explanation is a bit more complicated than the answers we have seen so far.

First, unlike re.match() the primitive operation re.search() checks for a match anywhere in the string (this is what Perl does by default) and finds the pattern once:

Scan through string looking for the first location where the regular
  expression pattern produces a match, and return a corresponding
  MatchObject instance. Return None if no position in the string matches
  the pattern; note that this is different from finding a zero-length
  match at some point in the string. See: Ref.

If we follow every step of the regex engine while it tries to find a match, we can observe the following for the pattern i* and the test string piigg!!:

As you can see, the first character (at position 0) produces a match because p is zero times i and the result is an empty match (and not p - because we do not search for p or any other character).

At the second character (position 1) the second match (spanning to position 2) is found since ii is zero or more times i... at position 3 there is another empty match, and so far and so forth.

Because re.search only returns the first match it sticks with the first empty match at position 0. That's why you get the (confusing) result you have posted:

```<code>In [2]: re.search(r"i*", "piiig!!").group()
Out[2]: ''
</code>```

In order to match every occurrence, you need re.findall():

Return all non-overlapping matches of pattern in string, as a list of
  strings. The string is scanned left-to-right, and matches are returned
  in the order found. If one or more groups are present in the pattern,
  return a list of groups; this will be a list of tuples if the pattern
  has more than one group. Empty matches are included in the result
  unless they touch the beginning of another match. See: Ref.

Body:
I am new to python and was going through "Google for Education" python course

Now, the line below confuses me:

* -- 0 or more occurrences of the pattern to its left

(all the examples are in python3)

e.g. 1

In [1]: re.search(r"pi*", "piiig!!").group()
Out[1]: 'piii'

This is fine since, "pi" has 1 occurrance so it is retured

e.g. 2

In [2]: re.search(r"i*", "piiig!!").group()
Out[2]: ''

Why does it not return "i" in fact - from my understanding, it should be returning "iii". But the result is an empty string.

Also, What exactly does "0 or more" mean? I searched on google but everywhere it is mentioned * -- 0 or more. But if there is 0 occurrence of an expression, does that not become true even if it's not there? What is the point of searching then?

I am so confused with this. Can you please help me with explaining this or point me in the right direction.

i hope the right explanation would also resolve my this issue:

In [3]: re.search(r"i?", "piiig!!").group()
Out[3]: ''

I have tried the examples in Spyder 3.2.4

Body:
The explanation is a bit more complicated than the answers we have seen so far.

First, unlike re.match() the primitive operation re.search() checks for a match anywhere in the string (this is what Perl does by default) and finds the pattern once:

Scan through string looking for the first location where the regular
  expression pattern produces a match, and return a corresponding
  MatchObject instance. Return None if no position in the string matches
  the pattern; note that this is different from finding a zero-length
  match at some point in the string. See: Ref.

If we follow every step of the regex engine while it tries to find a match, we can observe the following for the pattern i* and the test string piigg!!:

As you can see, the first character (at position 0) produces a match because p is zero times i and the result is an empty match (and not p - because we do not search for p or any other character).

At the second character (position 1) the second match (spanning to position 2) is found since ii is zero or more times i... at position 3 there is another empty match, and so far and so forth.

Because re.search only returns the first match it sticks with the first empty match at position 0. That's why you get the (confusing) result you have posted:

In [2]: re.search(r"i*", "piiig!!").group()
Out[2]: ''

In order to match every occurrence, you need re.findall():

Return all non-overlapping matches of pattern in string, as a list of
  strings. The string is scanned left-to-right, and matches are returned
  in the order found. If one or more groups are present in the pattern,
  return a list of groups; this will be a list of tuples if the pattern
  has more than one group. Empty matches are included in the result
  unless they touch the beginning of another match. See: Ref.


问:
Angularjs 2 installation Methods
I have one angularjs 2 UI (without node modules) which i have to integrate with my backend. After installing Angular cli, Can i simply do npm install in the angularjs 2 directory folder as it have package.json or create a new app after installing angular cli and then do npm install for some node modules specific to my angularjs project. </p>

<p>Will the first approach Work successfully as it is easier </p>

答: If your backendend and frontend repos are in same package.json just serve your app. You can separate these ( in the future it will be more effective ) . So just search your starting command and run the app.</p>

Title: Angularjs 2 installation Methods

Body:
I have one angularjs 2 UI (without node modules) which i have to integrate with my backend. After installing Angular cli, Can i simply do npm install in the angularjs 2 directory folder as it have package.json or create a new app after installing angular cli and then do npm install for some node modules specific to my angularjs project.

Will the first approach Work successfully as it is easier


问:
Display queryset and it's foreign keys in order by id in django template
I am building a quiz program. Every test has question and questions have options. Option has foreign key to a question and question has foreign key to a test.
Every thing is good. But sometimes when displaying these in template, choice appear in reverse order that is sometimes choice d appears first and choice A appears last.

Here is the code:

```<code>{% for question in test.sscquestions_set.all %}

    <div class='well quest'>
         <h3 style= 'font-weight:bold;'> {{question.text}} </h3>
               {% for choice in question.choices_set.all %}
                     <p> {{choice.text}}</p>
    </div>
{%endfor%}
</code>```

How to always display choices in particular order (ie. OptionA first and Option D last)

答:
Define a field for choices for example choice_number and then use

```<code>queryset|dictsort:'choice_number'
</code>```

Body:
I am building a quiz program. Every test has question and questions have options. Option has foreign key to a question and question has foreign key to a test.
Every thing is good. But sometimes when displaying these in template, choice appear in reverse order that is sometimes choice d appears first and choice A appears last.

Here is the code:

{% for question in test.sscquestions_set.all %}

 {{question.text}}

               {% for choice in question.choices_set.all %}

 {{choice.text}}

{%endfor%}

How to always display choices in particular order (ie. OptionA first and Option D last)

Body:
Define a field for choices for example choice_number and then use

queryset|dictsort:'choice_number'


问:
Targeting an element with specific data attribute value
I am working on the code below. How can I add .click() to the a link with specific data attribute of HD?

if ($(a).data("quality") == "HD") {
  $(this).click();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="stream">
  <li>Low</li>
  <li>Med</li>
  <li>HD</li>
</ul></code>```

答:
Use an Attribute Selector

$("a[data-quality=HD]").click();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="stream">
  <li>Low</li>
  <li>Med</li>
  <li>HD</li>
</ul></code>```

Body:
I am working on the code below. How can I add .click() to the a link with specific data attribute of HD?

if ($(a).data("quality") == "HD") {
  $(this).click();
}

Low

Med

HD

Body:
Use an Attribute Selector

$("a[data-quality=HD]").click();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="stream">
  <li><a data-quality="L">Low</a></li>
  <li><a data-quality="M">Med</a></li>
  <li><a data-quality="HD">HD</a></li>
</ul>


问:
Date.getTime() in Java returning different time in different server
I need to calculate a value that is based on dates. So I'm parsing the date first using date format class and then i'm using getTime() to get milliseconds. With those milliseconds i'll calculate some value. But getTime() is returning different values in different servers. We develop here in India, where i'm getting correct value but in US server i'm getting different value.

Scenario:

```<code>public class Test {

    public static void main(String[] args) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

        String now = "11/03/2018";

        Date UsualDateformat = sdf.parse(now);

        System.out.println(UsualDateformat.getTime());
    }
}
</code>```

Above is a sample code, but my actual code is a rule in a drl file (drools).
This program returns
"1541183400000" which i convert to date is "Sat 3 November 2018 00:00:00".,
but in US server im getting "1541217600000" equal to date "Sat 3 November 2018 09:30:00".
So when i use this value i'm getting marginal decimal point formatting issue.
How to resolve this issue?

Thanks in advance!

答:
This code snippet might work for you,

```<code>public static String getGmtTime(String timezone) {
    return ZonedDateTime
            .now()
            .withZoneSameInstant(ZoneId.of(timezone))
            .toLocalDateTime()
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
</code>```

pass timezone as America/Los_Angeles to get time with proper timezone,
Timezones can be found here

Body:
I need to calculate a value that is based on dates. So I'm parsing the date first using date format class and then i'm using getTime() to get milliseconds. With those milliseconds i'll calculate some value. But getTime() is returning different values in different servers. We develop here in India, where i'm getting correct value but in US server i'm getting different value.

Scenario:

public class Test {

    public static void main(String[] args) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

        String now = "11/03/2018";

        Date UsualDateformat = sdf.parse(now);

        System.out.println(UsualDateformat.getTime());
    }
}

Above is a sample code, but my actual code is a rule in a drl file (drools).
This program returns
"1541183400000" which i convert to date is "Sat 3 November 2018 00:00:00".,
but in US server im getting "1541217600000" equal to date "Sat 3 November 2018 09:30:00".
So when i use this value i'm getting marginal decimal point formatting issue.
How to resolve this issue?

Thanks in advance!

Body:
This code snippet might work for you,

public static String getGmtTime(String timezone) {
    return ZonedDateTime
            .now()
            .withZoneSameInstant(ZoneId.of(timezone))
            .toLocalDateTime()
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}

pass timezone as America/Los_Angeles to get time with proper timezone,
Timezones can be found here


答:
you can make use of Attribute Selectors:</p>

```<code>$('a[data-quality="HD"]').click(function() {
    //do something
});
</code>```

Title: Targeting an element with specific data attribute value

Body:
you can make use of Attribute Selectors:

$('a[data-quality="HD"]').click(function() {
    //do something
});


问:
Armstrong numbers in ruby
I'm having problems with this practice question.

Write a Ruby script to display the number of Armstrong numbers in an array of numbers.

An Armstrong number is a number in which the sum of [the] cubes of the digits of the number is [the] same as the number. For instance, 153, 370 and 371 are Armstrong numbers. Example:

```<code>153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
</code>```

Sample input

```<code>numbers = [123, 124, 153, 370, 234, 23, 45]
</code>```

Then the output will be

```<code>There are 2 Armstrong numbers in the list.
</code>```

My code is the following:

```<code>def get
  number = [123, 124, 153, 370, 234, 23, 45]
  s = number.count{}
  new_num = number
  sum = 0

  while new_num > 0
    sum = sum + (new_num % 10) * (new_num % 10) * (new_num % 10)
    new_num = new_num / 10
    number.count(new_num)
  end

  if sum == number
    puts "There are #{s} Armstrong"
  end
end
</code>```

It gives no output, and I'm not sure why.

Title: Armstrong numbers in ruby

Body:
I'm having problems with this practice question.

Write a Ruby script to display the number of Armstrong numbers in an array of numbers.

An Armstrong number is a number in which the sum of [the] cubes of the digits of the number is [the] same as the number. For instance, 153, 370 and 371 are Armstrong numbers. Example:

153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

Sample input

numbers = [123, 124, 153, 370, 234, 23, 45]

Then the output will be

There are 2 Armstrong numbers in the list.

My code is the following:

def get
  number = [123, 124, 153, 370, 234, 23, 45]
  s = number.count{}
  new_num = number
  sum = 0

  while new_num > 0
    sum = sum + (new_num % 10) * (new_num % 10) * (new_num % 10)
    new_num = new_num / 10
    number.count(new_num)
  end

  if sum == number
    puts "There are #{s} Armstrong"
  end
end

It gives no output, and I'm not sure why.

Body:
If the method must be used frequently, one can save time by defining a constant holding a set (rather than an array, for faster lookup) of the first so-many Armstrong numbers. For example,

require 'set'

FIRST_ARMSTRONG_NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634,
   8208, 9474, 54748, 92727, 93084, 548834, 1741725, 4210818, 9800817, 9926315,
   24678050, 24678051, 88593477, 146511208, 472335975, 534494836, 912985153,
   4679307774, 32164049650, 32164049651].to_set
     #=> #<Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208,
     #           9474, 54748, 92727, 93084, 548834, 1741725, 4210818,
     #           9800817, 9926315, 24678050, 24678051, 88593477, 146511208,
     #           472335975, 534494836, 912985153, 4679307774, 32164049650,
     #           32164049651}>
MAX_FIRST_ARMSTRONG_NUMBERS = FIRST_ARMSTRONG_NUMBERS.max
  #=> 32164049651

def count_armstrong_numbers(arr)
  arr.count do |n|
    if n <= MAX_FIRST_ARMSTRONG_NUMBERS
      FIRST_ARMSTRONG_NUMBERS.include?(n)
    else
      n.digits.sum { |d| d**3 } == n
    end
  end
end


问:
how to get related posts where atleast 3 tag should be matched to current post in wordpress
I want to get similar (related) posts that should be matching atleast 3 tags (all post have more then 10 tags).  Is this possible? if yes please help. I have no idea about it.</p>

答:
```<code><?php
    $rTag = wp_get_post_tags($post->ID);
    foreach($rTag as $individual_tag) $tag_ids[] = $individual_tag->term_id;
        $related = get_posts( array(
                'tax_query' => array(
                  array(
                    'taxonomy' => 'post_tag',
                    'field'    => 'term_id',
                    'terms'    => $tag_ids,
                  ),
                ),
                'numberposts' => -1,
                'post__not_in' => array($post->ID),
              ) );
?>
<section id="discover">
    <h2>Related posts</h2>
    <div class="singlepost">
        <?php  if( $related )  foreach( $related as $post ) {
      setup_postdata($post);
                $tag_count = 0;
                $tag_min_match = 3;
                    foreach ( $tag_ids as $tag ) {
                        if ( has_tag( $tag ) && $tag_count < $tag_min_match ) {
                            $tag_count ++;
                        }
                    }
                if ($tag_count >= $tag_min_match) {
                    echo '<h4>'. get_the_title() .'</h4>';
                }
            }
        wp_reset_query(); ?>
    </div>
</section>
</code>```


问:
Uninstall boost and install another version
I've installed the boost libraries on Linux Mint 12 using the command sudo apt-get install libboost-dev libboost-doc, which installs the default version available in the repositories. However, the project I have to do needs the 1.44 version of boost. How do I uninstall the default (current) version 1.46 and install 1.44?

I couldn't find the documentation on the boost website to install boost from the .tar.gz package.

答:
This is how you install a specific Boost version:</p>

```<code>cd boost_1_54_0/

./bootstrap.sh --with-libraries=atomic,date_time,exception,filesystem,iostreams,locale,program_options,regex,signals,system,test,thread,timer,log

sudo ./b2 install
</code>```

Body:
This is how you install a specific Boost version:

cd boost_1_54_0/

./bootstrap.sh --with-libraries=atomic,date_time,exception,filesystem,iostreams,locale,program_options,regex,signals,system,test,thread,timer,log

sudo ./b2 install


问:
Concatenating two strings into a Textbox
I have been just learning about the basics of cryptography, and I wanted to give
one of the methods called zigzag transposition a try.

 All this method does is combining the entire sentence and give them index starting from zero.

it then separates the even indexed characters into an array and the odd ones into a different array .

When I convert the two arrays to strings and then place them in a textbox only the first string shows up.

```<code>private void ZigzagBu_Click(object sender, EventArgs e) {
    string s = PlaintextTB.Text;
    s = s.Replace(" ","");

    char[] whole = s.ToCharArray();
    char[] even = new char[whole.Length];
    char[] odd = new char[whole.Length];

    int evenIndex = 0;
    int oddIndex = 0;

    for(int i =0;i<whole.Length;i++) {
        if (i % 2 == 0) {
            even[evenIndex] = whole[i];
            evenIndex++;
        }
        else {
            odd[oddIndex] = whole[i];
            oddIndex++;
        }
    }

    s = new String(even);
    string m = new String(odd);

    CiphertextTB.Text = s+m;
}
</code>```

答:
The problem was in the size of the char arrays. I solved it by

```<code>char[] even = new char[whole.Length/2];
char[] odd = new char[whole.Length/2];
</code>```

Body:
I have been just learning about the basics of cryptography, and I wanted to give
one of the methods called zigzag transposition a try.

 All this method does is combining the entire sentence and give them index starting from zero.

it then separates the even indexed characters into an array and the odd ones into a different array .

When I convert the two arrays to strings and then place them in a textbox only the first string shows up.

private void ZigzagBu_Click(object sender, EventArgs e) {
    string s = PlaintextTB.Text;
    s = s.Replace(" ","");

    char[] whole = s.ToCharArray();
    char[] even = new char[whole.Length];
    char[] odd = new char[whole.Length];

    int evenIndex = 0;
    int oddIndex = 0;

    for(int i =0;i<whole.Length;i++) {
        if (i % 2 == 0) {
            even[evenIndex] = whole[i];
            evenIndex++;
        }
        else {
            odd[oddIndex] = whole[i];
            oddIndex++;
        }
    }

    s = new String(even);
    string m = new String(odd);

    CiphertextTB.Text = s+m;
}

Body:
The problem was in the size of the char arrays. I solved it by <br/>

char[] even = new char[whole.Length/2];
char[] odd = new char[whole.Length/2];


问:
How can I arrange sorted data in UITableViewController
I used iphones address book data in my app ,i sorted that data and arranged in UITableViewController,but now i want to make same look as of address book means sorted in GroupedStyle having initial character as heading of section .and suggestion plz</p>

答:
You have to implement the tableView methods that are

```<code>- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
</code>```

for section headers and for this this you also have to implement

```<code>- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
</code>```

By doing this your table data can be viewed in grouped style.

Body:
You have to implement the tableView methods that are

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

for section headers and for this this you also have to implement

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

By doing this your table data can be viewed in grouped style.


问:
Can't Change UIView Height When KeyboardDidHide is called
Any idea why I cannot change the height of my containerView when KeyboardDidHide notification happens? The height changes in KeyboardDidShow perfectly fine but won't change back in KeyboardDidHide. Also, it does change back if I change it in TextFieldDidEndEditing but that doesn't work quite perfectly for what I need.</p>

```<code>func setupKeyboardObserver() {
    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShow), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidHide), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}

@objc func handleKeyboardDidHide() {
    if UIDevice().userInterfaceIdiom == .phone {
        if UIScreen.main.nativeBounds.height == 2436 {
            containerView.frame.size.height += 35
        }
    }
}

func textFieldDidEndEditing(_ textField: UITextField) {
    if UIDevice().userInterfaceIdiom == .phone {
        if UIScreen.main.nativeBounds.height == 2436 {
            containerView.frame.size.height += 35
        }
    }
}

@objc func handleKeyboardDidShow() {

    if UIDevice().userInterfaceIdiom == .phone {
        if UIScreen.main.nativeBounds.height == 2436 {
            containerView.frame.size.height -= 35
        }
    }
}
</code>```

答: Try layoutIfNeeded() after setting new height value.

Body:
Any idea why I cannot change the height of my containerView when KeyboardDidHide notification happens? The height changes in KeyboardDidShow perfectly fine but won't change back in KeyboardDidHide. Also, it does change back if I change it in TextFieldDidEndEditing but that doesn't work quite perfectly for what I need.

func setupKeyboardObserver() {
    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShow), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidHide), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}

@objc func handleKeyboardDidHide() {
    if UIDevice().userInterfaceIdiom == .phone {
        if UIScreen.main.nativeBounds.height == 2436 {
            containerView.frame.size.height += 35
        }
    }
}

func textFieldDidEndEditing(_ textField: UITextField) {
    if UIDevice().userInterfaceIdiom == .phone {
        if UIScreen.main.nativeBounds.height == 2436 {
            containerView.frame.size.height += 35
        }
    }
}

@objc func handleKeyboardDidShow() {

    if UIDevice().userInterfaceIdiom == .phone {
        if UIScreen.main.nativeBounds.height == 2436 {
            containerView.frame.size.height -= 35
        }
    }
}


问:
How do I redirect the output of commands to file in silent mode in NSIS?
In GUI mode, commands like CopyFiles , Delete , etc. output their data to GUI (may be using DetailPrint) and their is a function available on NSIS forums to copy that data (at the end of section) to a file.

Queries:

If the installer is being run in silent mode, how do I get the same data (which was being directed to GUI in non-silent mode) to the file?

In GUI mode, since I am directing custom logs through DetailPrint to the log file with the help of function so that all the logs are received in order. Here the issue is that line breaks are removed from the custom logs. May be DetailPrint removes it. How shall I avoid this?

Example:

```<code>DetailPrint "This is a custom log1"
DetailPrint "$\r$\nThis is a custom log2"
/*
  Dumped these logs using function mentioned above
  Output in logs(with no line breaks):
  This is a custom log1
  This is a custom log2

  Required output:
  This is a custom log1

  This is a custom log2
*/
</code>```

答:
Your Second query is Solved.

```<code>!include "MUI2.nsh"
section
StrCpy $0 "$EXEDIR\install.log"
Push $0
    DetailPrint "This is a custom log1"
    DetailPrint "This is a custom log2"
    Call DumpLog
sectionend

;!define LVM_GETITEMCOUNT 0x1004
!define LVM_GETITEMTEXT 0x102D

Function DumpLog
  Exch $5
  Push $0
  Push $1
  Push $2
  Push $3
  Push $4
  Push $6

  FindWindow $0 "#32770" "" $HWNDPARENT
  GetDlgItem $0 $0 1016
  StrCmp $0 0 exit
  FileOpen $5 $5 "w"
  StrCmp $5 "" exit
    SendMessage $0 ${LVM_GETITEMCOUNT} 0 0 $6
    System::Alloc ${NSIS_MAX_STRLEN}
    Pop $3
    StrCpy $2 0
    System::Call "*(i, i, i, i, i, i, i, i, i) i \
      (0, 0, 0, 0, 0, r3, ${NSIS_MAX_STRLEN}) .r1"
    loop: StrCmp $2 $6 done
      System::Call "User32::SendMessageA(i, i, i, i) i \
        ($0, ${LVM_GETITEMTEXT}, $2, r1)"
      System::Call "*$3(&t${NSIS_MAX_STRLEN} .r4)"
      FileWrite $5 "$4$\r$\n"
      FileWrite $5  "$\r$\n"
      IntOp $2 $2 + 1
      Goto loop
    done:
      FileClose $5
      System::Free $1
      System::Free $3
  exit:
    Pop $6
    Pop $4
    Pop $3
    Pop $2
    Pop $1
    Pop $0
    Exch $5
FunctionEnd
</code>```

Your sample code is works for me. Its gives me output as your requirement.
Dont put  "$\r$\n" in Detailprint. Add FileWrite $5  "$\r$\n" in DumpLog function as i did. By this you will not have to put $\r$\n in each detail print.

Body:
In GUI mode, commands like CopyFiles , Delete , etc. output their data to GUI (may be using DetailPrint) and their is a function available on NSIS forums to copy that data (at the end of section) to a file.

Queries:

If the installer is being run in silent mode, how do I get the same data (which was being directed to GUI in non-silent mode) to the file?

In GUI mode, since I am directing custom logs through DetailPrint to the log file with the help of function so that all the logs are received in order. Here the issue is that line breaks are removed from the custom logs. May be DetailPrint removes it. How shall I avoid this?

Example:

DetailPrint "This is a custom log1"
DetailPrint "$\r$\nThis is a custom log2"
/*
  Dumped these logs using function mentioned above
  Output in logs(with no line breaks):
  This is a custom log1
  This is a custom log2

  Required output:
  This is a custom log1

  This is a custom log2
*/

Body:
Your Second query is Solved.

!include "MUI2.nsh"
section
StrCpy $0 "$EXEDIR\install.log"
Push $0
    DetailPrint "This is a custom log1"
    DetailPrint "This is a custom log2"
    Call DumpLog
sectionend

;!define LVM_GETITEMCOUNT 0x1004
!define LVM_GETITEMTEXT 0x102D

Function DumpLog
  Exch $5
  Push $0
  Push $1
  Push $2
  Push $3
  Push $4
  Push $6

  FindWindow $0 "#32770" "" $HWNDPARENT
  GetDlgItem $0 $0 1016
  StrCmp $0 0 exit
  FileOpen $5 $5 "w"
  StrCmp $5 "" exit
    SendMessage $0 ${LVM_GETITEMCOUNT} 0 0 $6
    System::Alloc ${NSIS_MAX_STRLEN}
    Pop $3
    StrCpy $2 0
    System::Call "*(i, i, i, i, i, i, i, i, i) i \
      (0, 0, 0, 0, 0, r3, ${NSIS_MAX_STRLEN}) .r1"
    loop: StrCmp $2 $6 done
      System::Call "User32::SendMessageA(i, i, i, i) i \
        ($0, ${LVM_GETITEMTEXT}, $2, r1)"
      System::Call "*$3(&t${NSIS_MAX_STRLEN} .r4)"
      FileWrite $5 "$4$\r$\n"
      FileWrite $5  "$\r$\n"
      IntOp $2 $2 + 1
      Goto loop
    done:
      FileClose $5
      System::Free $1
      System::Free $3
  exit:
    Pop $6
    Pop $4
    Pop $3
    Pop $2
    Pop $1
    Pop $0
    Exch $5
FunctionEnd

Your sample code is works for me. Its gives me output as your requirement.
Dont put  "$\r$\n" in Detailprint. Add FileWrite $5  "$\r$\n" in DumpLog function as i did. By this you will not have to put $\r$\n in each detail print.


问:
Cancel an AsyncTask Class in Android
I have a class name is GetData that extends from AsyncTask. In other class I have an object from GetData and with this codes I use that:

```<code>GetData getData = new GetData();
getData().execute();
</code>```

I want to stop this thread when a button clicked. I do this with:

```<code>getData().cancel(true);
</code>```

I want to know if I canceled thread while it is in doInBackground, it stopped or it goes to onPostExecute and then stop?

答:
From the Android documentation:

Calling this method will result in onCancelled(Object) being invoked on the UI thread after doInBackground(Object[]) returns. Calling this method guarantees that onPostExecute(Object) is never invoked.

So onPostExecute will not be called.

Title: Cancel an AsyncTask Class in Android

Body:
I have a class name is GetData that extends from AsyncTask. In other class I have an object from GetData and with this codes I use that:

GetData getData = new GetData();
getData().execute();

I want to stop this thread when a button clicked. I do this with:

getData().cancel(true);

I want to know if I canceled thread while it is in doInBackground, it stopped or it goes to onPostExecute and then stop?


问:
Best way to scale size of camera picture before saving to SD
The code below is executed as the jpeg picture callback after TakePicture is called. If I save data to disk, it is a 1280x960 jpeg. I've tried to change the picture size but that's not possible as no smaller size is supported. JPEG is the only available picture format.

```<code> PictureCallback jpegCallback = new PictureCallback() {
  public void onPictureTaken(byte[] data, Camera camera) {
   FileOutputStream out = null;
   Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
   Bitmap sbm = Bitmap.createScaledBitmap(bm, 640, 480, false);
</code>```

data.Length is something like 500k as expected. After executing BitmapFactory.decodeByteArray(), bm has a height and width of -1 so it appears the operation is failing.

It's unclear to me if Bitmap can handle jpeg data. I would think not but I have seem some code examples that seem to indicate it is.

Does data need to be in bitmap format before decoding and scaling?

If so, how to do this?

Thanks!

答:
On your surfaceCreated, you code set the camara's Picture Size, as shown the code below:   </p>

```<code>
public void surfaceCreated(SurfaceHolder holder) {
        camera = Camera.open();
        try {
            camera.setPreviewDisplay(holder);
            Camera.Parameters p = camera.getParameters();
            p.set("jpeg-quality", 70);
            p.setPictureFormat(PixelFormat.JPEG);
            p.setPictureSize(640, 480);
            camera.setParameters(p);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
</code>
```

Body:
The code below is executed as the jpeg picture callback after TakePicture is called. If I save data to disk, it is a 1280x960 jpeg. I've tried to change the picture size but that's not possible as no smaller size is supported. JPEG is the only available picture format.

 PictureCallback jpegCallback = new PictureCallback() {
  public void onPictureTaken(byte[] data, Camera camera) {
   FileOutputStream out = null;
   Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
   Bitmap sbm = Bitmap.createScaledBitmap(bm, 640, 480, false);

data.Length is something like 500k as expected. After executing BitmapFactory.decodeByteArray(), bm has a height and width of -1 so it appears the operation is failing.

It's unclear to me if Bitmap can handle jpeg data. I would think not but I have seem some code examples that seem to indicate it is.

Does data need to be in bitmap format before decoding and scaling?

If so, how to do this?

Thanks!

Body:
On your surfaceCreated, you code set the camara's Picture Size, as shown the code below:

public void surfaceCreated(SurfaceHolder holder) {
        camera = Camera.open();
        try {
            camera.setPreviewDisplay(holder);
            Camera.Parameters p = camera.getParameters();
            p.set("jpeg-quality", 70);
            p.setPictureFormat(PixelFormat.JPEG);
            p.setPictureSize(640, 480);
            camera.setParameters(p);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


问:
How to decode decoded files after downloading from Azure Storage?
I am trying to decode files after downloading via Azure Storage SDK for Java.

Here is my code:

```<code>try
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
            CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
            CloudBlobContainer container = blobClient.getContainerReference("mycontainer");
            CloudBlobDirectory blobDirectory = container.getDirectoryReference("shi");
            for (ListBlobItem blobItem : blobDirectory.listBlobs()) {
                if (blobItem instanceof CloudBlob) {
                    CloudBlob blob = (CloudBlob) blobItem;
                    blob.download(new FileOutputStream("/Users/shi/Downloads/" + blob.getName()));
                }
            }
        }
</code>```

This code downloads all the BLOB files from mycontainer but there are encoded. How can I download them but in decoded form.

答:
I tried to reproduce your issue.

My sample code ：

```<code>CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
CloudBlobContainer container = blobClient.getContainerReference("jay");
   for (ListBlobItem blobItem : container.listBlobs()) {
        if (blobItem instanceof CloudBlob) {
            CloudBlob blob = (CloudBlob) blobItem;
            blob.download(new FileOutputStream("E://AzureFile/" + blob.getName()));
</code>```

Download successfully ：

You can see check if the blob Content Type is text/plain in Storage Explorer first. Blob specific Content Type is not displayed on the portal.

In addition , it might because of the encoding you use when you parse blob content is inconsistent with the encoding your colleague use when the blob is uploaded.

This issue is encountered when downloading text, but the binary does not.

I suggest you get the encoding when the file was uploaded and set the character set to parse the blob content by using the following sample snippet of code:

```<code>if (blobItem instanceof CloudBlob) {
      CloudBlob blob = (CloudBlob) blobItem;
      InputStream input =  blob.openInputStream();
      InputStreamReader inr = new InputStreamReader(input, "UTF-8");
      String utf8str = org.apache.commons.io.IOUtils.toString(inr);
      System.out.println(utf8str);
}
</code>```

Hope it helps you.

Body:
I am trying to decode files after downloading via Azure Storage SDK for Java.

Here is my code:

try
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
            CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
            CloudBlobContainer container = blobClient.getContainerReference("mycontainer");
            CloudBlobDirectory blobDirectory = container.getDirectoryReference("shi");
            for (ListBlobItem blobItem : blobDirectory.listBlobs()) {
                if (blobItem instanceof CloudBlob) {
                    CloudBlob blob = (CloudBlob) blobItem;
                    blob.download(new FileOutputStream("/Users/shi/Downloads/" + blob.getName()));
                }
            }
        }

This code downloads all the BLOB files from mycontainer but there are encoded. How can I download them but in decoded form.

Body:
I tried to reproduce your issue.

My sample code ：

CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
CloudBlobContainer container = blobClient.getContainerReference("jay");
   for (ListBlobItem blobItem : container.listBlobs()) {
        if (blobItem instanceof CloudBlob) {
            CloudBlob blob = (CloudBlob) blobItem;
            blob.download(new FileOutputStream("E://AzureFile/" + blob.getName()));

Download successfully ：

You can see check if the blob Content Type is text/plain in Storage Explorer first. Blob specific Content Type is not displayed on the portal.

In addition , it might because of the encoding you use when you parse blob content is inconsistent with the encoding your colleague use when the blob is uploaded.

This issue is encountered when downloading text, but the binary does not.

I suggest you get the encoding when the file was uploaded and set the character set to parse the blob content by using the following sample snippet of code:

if (blobItem instanceof CloudBlob) {
      CloudBlob blob = (CloudBlob) blobItem;
      InputStream input =  blob.openInputStream();
      InputStreamReader inr = new InputStreamReader(input, "UTF-8");
      String utf8str = org.apache.commons.io.IOUtils.toString(inr);
      System.out.println(utf8str);
}

Hope it helps you.


问:
How to know if a string is already escaped special with special characters?
I have this URL:

```<code>"http://www.somedomain.com/folder/مرحبا المستخدم.jpg"
</code>```

So I needs to escape these Arabic values else it will not able to create URL object.

I am doing it like this,

```<code>let originalString = "http://www.somedomain.com/folder/مرحبا المستخدم.jpg"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
</code>```

This will be the output of escapedString:

http://www.somedomain.com/folder/%D9%85%D8%B1%D8%AD%D8%A8%D8%A7%20%D8%A7%D9%84%D9%85%D8%B3%D8%AA%D8%AE%D8%AF%D9%85.jpg

So far so good. But when I force to try to escape an already escaped URL then the result is weird.

How to check if a string is already encoded?

答: I am not able to test this, but I would try to 'unescape' the original string first, and then compare the result with the original string. If they match, there was no escaping in the original string.  If they don't match, the original string was escapeds already.</p>

Body:
I have this URL:

"http://www.somedomain.com/folder/مرحبا المستخدم.jpg"

So I needs to escape these Arabic values else it will not able to create URL object.

I am doing it like this,

let originalString = "http://www.somedomain.com/folder/مرحبا المستخدم.jpg"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

This will be the output of escapedString:

http://www.somedomain.com/folder/%D9%85%D8%B1%D8%AD%D8%A8%D8%A7%20%D8%A7%D9%84%D9%85%D8%B3%D8%AA%D8%AE%D8%AF%D9%85.jpg

So far so good. But when I force to try to escape an already escaped URL then the result is weird.

How to check if a string is already encoded?


答:
You can directly bind the click to the anchor with data-quality attribute

Demo

$("a[data-quality='HD']").click( function(){
  console.log($(this).text())
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="stream">
  <li>Low</li>
  <li>Med</li>
  <li>HD</li>
</ul></code>```

Body:
I am working on the code below. How can I add .click() to the a link with specific data attribute of HD?

if ($(a).data("quality") == "HD") {
  $(this).click();
}

Low

Med

HD

Body:
You can directly bind the click to the anchor with data-quality attribute

Demo

$("a[data-quality='HD']").click( function(){
  console.log($(this).text())
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="stream">
  <li><a data-quality="L">Low</a></li>
  <li><a data-quality="M">Med</a></li>
  <li><a data-quality="HD">HD</a></li>
</ul>


问:
How to enable sshpass output to console
Using scp and interactively entering the password the file copy progress is sent to the console but there is no console output when using sshpass in a script to scp files.

```<code>$ sshpass -p [password] scp [file] root@[ip]:/[dir]
</code>```

It seems sshpass is suppressing or hiding the console output of scp. Is there a way to enable the sshpass scp output to console?

答:
In this way:

output=$(sshpass -p $PASSWD scp -v $filename root@192.168.8.1:/root 2>&1)

echo "Output = $output"

you redirect the console output in variable output.

Or, if you only want to see the console output of scp command, you should add only -v command in your ssh pass cmd:

sshpass -p $PASSWD scp -v $filename root@192.168.8.1:/root

Title: How to enable sshpass output to console

Body:
Using scp and interactively entering the password the file copy progress is sent to the console but there is no console output when using sshpass in a script to scp files.

$ sshpass -p [password] scp [file] root@[ip]:/[dir]

It seems sshpass is suppressing or hiding the console output of scp. Is there a way to enable the sshpass scp output to console?