问:
How to sort my images by name?
```<code>/* function:  returns files from dir */
function get_files($images_dir,$exts = array('jpg')) {
    $files = array();
    if($handle = opendir($images_dir)) {
        while(false !== ($file = readdir($handle))) {
            $extension = strtolower(get_file_extension($file));
            if($extension && in_array($extension,$exts)) {
                $files[] = $file;
            }
        }
        closedir($handle);
    }
    return $files;
}
</code>```

I have images named 01-image.jpg, 02-image.jpg etc but when I echo them out, they are in random order, how do I order them by name?

答:
before you echo them out use sort() - sort arrays in ascending order or rsort() - sort arrays in descending order

You can read more about sorting array here

```<code>// function to get img

$order = sort($img);
echo($order)
</code>```

Title: How to sort my images by name?

Body:
/* function:  returns files from dir */
function get_files($images_dir,$exts = array('jpg')) {
    $files = array();
    if($handle = opendir($images_dir)) {
        while(false !== ($file = readdir($handle))) {
            $extension = strtolower(get_file_extension($file));
            if($extension && in_array($extension,$exts)) {
                $files[] = $file;
            }
        }
        closedir($handle);
    }
    return $files;
}

I have images named 01-image.jpg, 02-image.jpg etc but when I echo them out, they are in random order, how do I order them by name?

Body:
before you echo them out use sort() - sort arrays in ascending order or rsort() - sort arrays in descending order

You can read more about sorting array here

// function to get img

$order = sort($img);
echo($order)


来源: stackexchange

问:
Running groovy unit tests in ant for a java project
I have a Java project with some unit tests written using JUnit. Recently some new unit tests have been added that are written in groovy (also using JUnit) as it's easier to make those
more expressive and generally easier to read. It also allows us to use the spock framework.

The project is build and tested with ant.

Before the groovy classes were added unit tests were run using the following ant task:

```<code><target name="test" depends="test-compile">
    <junit printsummary="yes">
        <classpath>
            <path refid="test.classpath"/>
        </classpath>
        <formatter type="plain"/>
        <batchtest fork="yes" todir="${test.dir}/report">
            <fileset dir="${test.dir}/unit" includes="**/*.java"/>
        </batchtest>
    </junit>
</target>
</code>```

However, this approach does not work for groovy tests as those are in *.groovy files and the JUnit Ant task, understandably, does not recognise them in the fileset.

The alternative approach is to use *.class files for the batchtest fileset like this:

```<code><batchtest fork="yes" todir="${test.dir}/report">
    <fileset dir="${test.dir}/${build.dir}">
        <include name="**/*Test*.class" />
    </fileset>
</batchtest>
</code>```

This generates false negatives as closure class files are also included so a possible workaround is to exclude those files.

```<code><batchtest fork="yes" todir="${test.dir}/report">
    <fileset dir="${test.dir}/${build.dir}">
        <include name="**/*Test*.class" />
        <exclude name="**/*$*.class" />
    </fileset>
</batchtest>
</code>```

Is there a better way to identify test classes fo the junit ant task? Perhaps one based on reflection and the @Test attribute as manually listing all the test classes (which would work perfectly well) is not really a maintainable solution. Something like the SpecClassFileSelector from the Spock framework.

答:
Can't you just write something like this?</p>

```<code>        <fileset dir="${test.dir}/unit" includes="**/*.java,**/*.groovy"/>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a Java project with some unit tests written using JUnit. Recently some new unit tests have been added that are written in groovy (also using JUnit) as it's easier to make those
more expressive and generally easier to read. It also allows us to use the spock framework.

The project is build and tested with ant.

Before the groovy classes were added unit tests were run using the following ant task:

<target name="test" depends="test-compile">
    <junit printsummary="yes">
        <classpath>
            <path refid="test.classpath"/>
        </classpath>
        <formatter type="plain"/>
        <batchtest fork="yes" todir="${test.dir}/report">
            <fileset dir="${test.dir}/unit" includes="**/*.java"/>
        </batchtest>
    </junit>
</target>

However, this approach does not work for groovy tests as those are in *.groovy files and the JUnit Ant task, understandably, does not recognise them in the fileset.

The alternative approach is to use *.class files for the batchtest fileset like this:

<batchtest fork="yes" todir="${test.dir}/report">
    <fileset dir="${test.dir}/${build.dir}">
        <include name="**/*Test*.class" />
    </fileset>
</batchtest>

This generates false negatives as closure class files are also included so a possible workaround is to exclude those files.

<batchtest fork="yes" todir="${test.dir}/report">
    <fileset dir="${test.dir}/${build.dir}">
        <include name="**/*Test*.class" />
        <exclude name="**/*$*.class" />
    </fileset>
</batchtest>

Is there a better way to identify test classes fo the junit ant task? Perhaps one based on reflection and the @Test attribute as manually listing all the test classes (which would work perfectly well) is not really a maintainable solution. Something like the SpecClassFileSelector from the Spock framework.

Body:
Can't you just write something like this?

        <fileset dir="${test.dir}/unit" includes="**/*.java,**/*.groovy"/>


问:
How to train a neural network with different types in data?
I'm facing a problem like I want to train a neural network to determine when a plant is fully grown by the height and some other stats. But there are so many types of plants so I cannot train one by for each of them.
I also tried to use a neural network trained with data of a species on another species and it didn't work. So I'm about to train a single neural network that can work with different species. But then each species has different ratios, for example:

```<code>plant      height    root radius
</code>```

```<code>chili      45-50cm   1-2cm

red_bean   25-30cm   0.5-1cm
basil      35-45cm   1-1.5cm
</code>```

The ratio of plant height and root radius is different.

I don't have the ratio of all species so I was thinking about adding a new type param into the input so with each type, the network will figure out the ratio itself. Type param may be like 1 stand for chili, 2 for red bean, 3 for basil, etc.. but don't know if it works or not.

So is anyone here ever try that before or is there another way for it?

答: Tags like that are not great candidates for simple NN's, but if you want to try it, (and you will), have a separate input for each tag. Set the input corresponding to the species of the training datum to 1 and all the others to -1.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm facing a problem like I want to train a neural network to determine when a plant is fully grown by the height and some other stats. But there are so many types of plants so I cannot train one by for each of them.
I also tried to use a neural network trained with data of a species on another species and it didn't work. So I'm about to train a single neural network that can work with different species. But then each species has different ratios, for example:

plant      height    root radius

chili      45-50cm   1-2cm

red_bean   25-30cm   0.5-1cm
basil      35-45cm   1-1.5cm

The ratio of plant height and root radius is different.

I don't have the ratio of all species so I was thinking about adding a new type param into the input so with each type, the network will figure out the ratio itself. Type param may be like 1 stand for chili, 2 for red bean, 3 for basil, etc.. but don't know if it works or not.

So is anyone here ever try that before or is there another way for it?


答:
you can use sort with SORT_STRING option

http://php.net/manual/en/function.sort.php

```<code>sort($files, SORT_STRING);
</code>```

Title: How to sort my images by name?

Body:
you can use sort with SORT_STRING option

http://php.net/manual/en/function.sort.php

sort($files, SORT_STRING);


问:
Adding a SetInterval function in jQuery
So I have this code from here: j360

This code is perfect for what I want: an html which has a draggable 360º product image view, but it lacks one thing: a button for auto rotation.

I already have the button into the html, but I can't, for more that I try, to make a function or anything to make the images go by itself, and not only when I drag it over the screen.

Here is the code I have at the moment:

```<code>(function($){
$.fn.j360 = function(options) {
    var defaults = {
        clicked: false,
        currImg: 1
    }
    var options = jQuery.extend(defaults, options);
    return this.each(function() {
        var $obj = jQuery(this);
        var aImages = {};
        $obj.css({
            'margin-left' : 'auto',
            'margin-right' : 'auto',
            'text-align' : 'center',
            'overflow' : 'hide'
        });
        $overlay = $obj.clone(true);
        $overlay.html('<img src="images/loader.gif" class="loader" style="margin-top:' + ($obj.height()/2 - 15) + 'px" />');
        $overlay.attr('id', 'view_overlay');
        $overlay.css({
            'position' : 'absolute',
            'z-index': '5',
            'top' : $obj.offset().top,
            'left' : $obj.offset().left,
            'background' : '#fff'
        });
        $obj.after($overlay);
        $obj.after('<div id="colors_ctrls"></div>');
        jQuery('#colors_ctrls').css({
            'width' : $obj.width(),
            'position' : 'absolute',
            'z-index': '5',
            'top' : $obj.offset().top + $obj.height - 50,
            'left' : $obj.offset().left
        });
        var imageTotal = 0;
        jQuery('img', $obj).each(function() {
            aImages[++imageTotal] = jQuery(this).attr('src');
            preload(jQuery(this).attr('src'));
        })
        var imageCount = 0;
        jQuery('.preload_img').load(function() {
            if (++imageCount == imageTotal) {
                $overlay.animate({
                    'filter' : 'alpha(Opacity=0)',
                    'opacity' : 0
                }, 100);
                $obj.html('<img src="' + aImages[1] + '" />');
                $overlay.bind('mousedown touchstart', function(e) {
                    if (e.type == "touchstart") {
                        options.currPos = window.event.touches[0].pageX;
                    } else {
                        options.currPos = e.pageX;
                    }
                    options.clicked = true;
                    return false;
                });
                jQuery(document).bind('mouseup touchend', function() {
                    options.clicked = false;
                });
                jQuery(document).bind('mousemove touchmove', function(e) {
                    if (options.clicked) {
                        var pageX;
                        if (e.type == "touchmove") {
                            pageX = window.event.targetTouches[0].pageX;
                        } else {
                            pageX = e.pageX;
                        }
                        var width_step = 50;
                        if (Math.abs(options.currPos - pageX) >= width_step) {
                            if (options.currPos - pageX >= width_step) {
                                options.currImg++;
                                if (options.currImg > imageTotal) {
                                    options.currImg = 1;
                                }
                            } else {
                                options.currImg--;
                                if (options.currImg < 1) {
                                    options.currImg = imageTotal;
                                }
                            }
                            options.currPos = pageX;
                            $obj.html('<img src="' + aImages[options.currImg] + '" />');
                        }
                    }
                });
            }
        });
        if (jQuery.browser.msie || jQuery.browser.mozilla || jQuery.browser.opera || jQuery.browser.safari ) {
            jQuery(window).resize(function() {
                onresizeFunc($obj, $overlay);
            });
        } else {
            var supportsOrientationChange = "onorientationchange" in window,
            orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";
            window.addEventListener(orientationEvent, function() {
                onresizeFunc($obj, $overlay);
            }, false);
        }
        onresizeFunc($obj, $overlay)
    });
}
})
(jQuery)

function onresizeFunc($obj, $overlay){

$obj.css({
    'margin-top' : $(document).height()/2
});
$overlay.css({
    'margin-top' : 200,
    'top' : $obj.offset().top,
    'left' : $obj.offset().left
});

jQuery('#colors_ctrls').css({
    'top' : $obj.offset().top + $obj.height - 50,
    'left' : $obj.offset().left
})
}

function preload(image) {

if (typeof document.body == "undefined") return;
try {
    var div = document.createElement("div");
    var s = div.style;
    s.position = "absolute";
    s.top = s.left = 0;
    s.visibility = "hidden";
    document.body.appendChild(div);
    div.innerHTML = "<img class=\"preload_img\" src=\"" + image + "\" />";
}
catch(e) {
// Error. Do nothing.
}
};
</code>```

I need a method to increment over time a function, to make the illusion of auto-rotate.

答:
This plugin doesn’t seem to have this option (a kind of autoplay) so you have to code it or search an other plugin.

Since it is a list of image, you can maybe don’t use the plugin and display images one after another with jQuery and .delay()

ContentLicense: CC BY-SA 4.0

Title: Adding a SetInterval function in jQuery

Body:
So I have this code from here: j360

This code is perfect for what I want: an html which has a draggable 360º product image view, but it lacks one thing: a button for auto rotation.

I already have the button into the html, but I can't, for more that I try, to make a function or anything to make the images go by itself, and not only when I drag it over the screen.

Here is the code I have at the moment:

(function($){
$.fn.j360 = function(options) {
    var defaults = {
        clicked: false,
        currImg: 1
    }
    var options = jQuery.extend(defaults, options);
    return this.each(function() {
        var $obj = jQuery(this);
        var aImages = {};
        $obj.css({
            'margin-left' : 'auto',
            'margin-right' : 'auto',
            'text-align' : 'center',
            'overflow' : 'hide'
        });
        $overlay = $obj.clone(true);
        $overlay.html('');
        $overlay.attr('id', 'view_overlay');
        $overlay.css({
            'position' : 'absolute',
            'z-index': '5',
            'top' : $obj.offset().top,
            'left' : $obj.offset().left,
            'background' : '#fff'
        });
        $obj.after($overlay);
        $obj.after('

');
        jQuery('#colors_ctrls').css({
            'width' : $obj.width(),
            'position' : 'absolute',
            'z-index': '5',
            'top' : $obj.offset().top + $obj.height - 50,
            'left' : $obj.offset().left
        });
        var imageTotal = 0;
        jQuery('img', $obj).each(function() {
            aImages[++imageTotal] = jQuery(this).attr('src');
            preload(jQuery(this).attr('src'));
        })
        var imageCount = 0;
        jQuery('.preload_img').load(function() {
            if (++imageCount == imageTotal) {
                $overlay.animate({
                    'filter' : 'alpha(Opacity=0)',
                    'opacity' : 0
                }, 100);
                $obj.html('');
                $overlay.bind('mousedown touchstart', function(e) {
                    if (e.type == "touchstart") {
                        options.currPos = window.event.touches[0].pageX;
                    } else {
                        options.currPos = e.pageX;
                    }
                    options.clicked = true;
                    return false;
                });
                jQuery(document).bind('mouseup touchend', function() {
                    options.clicked = false;
                });
                jQuery(document).bind('mousemove touchmove', function(e) {
                    if (options.clicked) {
                        var pageX;
                        if (e.type == "touchmove") {
                            pageX = window.event.targetTouches[0].pageX;
                        } else {
                            pageX = e.pageX;
                        }
                        var width_step = 50;
                        if (Math.abs(options.currPos - pageX) >= width_step) {
                            if (options.currPos - pageX >= width_step) {
                                options.currImg++;
                                if (options.currImg > imageTotal) {
                                    options.currImg = 1;
                                }
                            } else {
                                options.currImg--;
                                if (options.currImg < 1) {
                                    options.currImg = imageTotal;
                                }
                            }
                            options.currPos = pageX;
                            $obj.html('');
                        }
                    }
                });
            }
        });
        if (jQuery.browser.msie || jQuery.browser.mozilla || jQuery.browser.opera || jQuery.browser.safari ) {
            jQuery(window).resize(function() {
                onresizeFunc($obj, $overlay);
            });
        } else {
            var supportsOrientationChange = "onorientationchange" in window,
            orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";
            window.addEventListener(orientationEvent, function() {
                onresizeFunc($obj, $overlay);
            }, false);
        }
        onresizeFunc($obj, $overlay)
    });
}
})
(jQuery)

function onresizeFunc($obj, $overlay){

$obj.css({
    'margin-top' : $(document).height()/2
});
$overlay.css({
    'margin-top' : 200,
    'top' : $obj.offset().top,
    'left' : $obj.offset().left
});

jQuery('#colors_ctrls').css({
    'top' : $obj.offset().top + $obj.height - 50,
    'left' : $obj.offset().left
})
}

function preload(image) {

if (typeof document.body == "undefined") return;
try {
    var div = document.createElement("div");
    var s = div.style;
    s.position = "absolute";
    s.top = s.left = 0;
    s.visibility = "hidden";
    document.body.appendChild(div);
    div.innerHTML = "";
}
catch(e) {
// Error. Do nothing.
}
};

I need a method to increment over time a function, to make the illusion of auto-rotate.


答:
here try something like this</p>

```<code>select
 sum(case when (timespent/60)<15 THEN 1 ELSE 0 END) '<15',
 sum(case when (timespent/60)>15 and (timespent/60)<30 THEN 1 ELSE 0 END) '15-30',
 from time_table;
</code>```

Title: Group rows based on time intervals in MySQL

Body:
I am trying to make categories through the row values.

Here are the rows:

id is just the unique ID, uid is User Id and timespent is the time spent on the site by the user in seconds

id  |uid | timespent
--------------------
133 | 41 | 2695
3   | 43 | 49920
45  | 73 | 95
83  | 91 | 5
29  | 109 | 2365
123 | 133 | 70
9   | 431 | 22010
2   | 445 | 15065
97  | 449 | 455
113 | 453 | 3140
5  | 455 | 44975
11 | 463 | 2695
13 | 465 | 5555
15 | 467 | 1775
17 | 469 | 55
19 | 471 | 465
21 | 473 | 380
23 | 475 | 280
25 | 477 | 3165
27 | 479 | 550
31 | 481 | 1530
33 | 483 | 2695
35 | 485 | 125
37 | 487 | 235
39 | 489 | 2120
41 | 493 | 10
43 | 495 | 2735
47 | 497 | 2700
49 | 499 | 2630
51 | 501 | 70
53 | 503 | 2240
55 | 505 | 15
57 | 507 | 5
59 | 509 | 3185
61 | 511 | 555
63 | 513 | 13480

What I am trying to create different categories of times, in which all these timespent entries would be adjusted.

Here is the picture of what I am trying to do:

Any idea how I can achieve that?

Body:
here try something like this

select
 sum(case when (timespent/60)<15 THEN 1 ELSE 0 END) '<15',
 sum(case when (timespent/60)>15 and (timespent/60)<30 THEN 1 ELSE 0 END) '15-30',
 from time_table;


问:
TF30063: You are not authorized ... programmatic access not working
The code below provided in this answer did work well for a while but now its throwing Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: 'TF30063: You are not authorized to access https://{mysite}.visualstudio.com/.' again.

```<code>var credentials = new VssClientCredentials();
credentials.PromptType = CredentialPromptType.PromptIfNeeded;

var teamProjects = new TfsTeamProjectCollection(tfsCollectionUri, credentials);
teamProjects.EnsureAuthenticated();         // exception thrown
</code>```

Q How can I fix this problem?

Update Strange enough,

before executing teamProjects.EnsureAuthenticated(); the debugger reads PromptIfNeeded for credentials.PromptType.

after the exception has been thrown and the debugger has stopped the execution, it reads DoNotPrompt for credentials.PromptType.

Observation
The above code works perfectly well in a console application but fails to work in a windows forms application (i.e. it throws an exception).

Q1 How can I make the above code work in a windows forms application?

答:
VS has added a registry entry to store the credential, try to delete the entry in the following path:

HKEY_CURRENT_USER\Software\Microsoft\VSCommon\14.0\ClientServices\TokenStorage\VisualStudio\VssApp

Update:

Also, try the code below to see whether it works:

```<code> var credentials = new VssClientCredentials();
 credentials.PromptType = CredentialPromptType.PromptIfNeeded;
 credentials.Storage = new VssClientCredentialStorage(storageKind: "VssApp2", storageNamespace: "VisualStudio");
 var aTeamProjects = new TfsTeamProjectCollection(new Uri("https://xxxxx.visualstudio.com/"), credentials);
 aTeamProjects.EnsureAuthenticated();
</code>```

Body:
The code below provided in this answer did work well for a while but now its throwing Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: 'TF30063: You are not authorized to access https://{mysite}.visualstudio.com/.' again.

var credentials = new VssClientCredentials();
credentials.PromptType = CredentialPromptType.PromptIfNeeded;

var teamProjects = new TfsTeamProjectCollection(tfsCollectionUri, credentials);
teamProjects.EnsureAuthenticated();         // exception thrown

Q How can I fix this problem?

Update Strange enough,

before executing teamProjects.EnsureAuthenticated(); the debugger reads PromptIfNeeded for credentials.PromptType.

after the exception has been thrown and the debugger has stopped the execution, it reads DoNotPrompt for credentials.PromptType.

Observation
The above code works perfectly well in a console application but fails to work in a windows forms application (i.e. it throws an exception).

Q1 How can I make the above code work in a windows forms application?

Body:
VS has added a registry entry to store the credential, try to delete the entry in the following path:

HKEY_CURRENT_USER\Software\Microsoft\VSCommon\14.0\ClientServices\TokenStorage\VisualStudio\VssApp

Update:

Also, try the code below to see whether it works:

 var credentials = new VssClientCredentials();
 credentials.PromptType = CredentialPromptType.PromptIfNeeded;
 credentials.Storage = new VssClientCredentialStorage(storageKind: "VssApp2", storageNamespace: "VisualStudio");
 var aTeamProjects = new TfsTeamProjectCollection(new Uri("https://xxxxx.visualstudio.com/"), credentials);
 aTeamProjects.EnsureAuthenticated();


问:
Laravel Mutators, Accessors
I've tried to implement mutators into my laravel 5.5. project since it looks like this would be the best way to auto-convert date object but for some reason it's not working. What i try to accomplish is to load a date object from mysql format Y-m-d and convert it to d.m.Y and write date objects with a format of d.m.Y to mysql with the format of Y-m-d. I get constantly errors like "delimiter not found" or "format error" etc.  </p>

```<code>protected $dateFormat = 'Y-m-d h:i';
protected $dates = [
    'joined',

];

function getJoinedAttribute()
{
    return $this->attributes['joined']->format('d.m.Y');
}

function setJoinedAttribute()
{
    return $this->attributes['joined']->format('Y-m-d');
}
</code>```

答:
You sould use Carbon library to convert date. </p>

<p>Like this : </p>

```<code> public function getDobAttribute($value)
    {
        return Carbon::parse($value)->format('d/m/Y');
    }

    public function setDobAttribute($value)
    {
        $this->attributes['dob'] = Carbon::createFromFormat('d/m/Y', $value)->toDateString();
    }
</code>```

Title: Laravel Mutators, Accessors

Body:
I've tried to implement mutators into my laravel 5.5. project since it looks like this would be the best way to auto-convert date object but for some reason it's not working. What i try to accomplish is to load a date object from mysql format Y-m-d and convert it to d.m.Y and write date objects with a format of d.m.Y to mysql with the format of Y-m-d. I get constantly errors like "delimiter not found" or "format error" etc.

protected $dateFormat = 'Y-m-d h:i';
protected $dates = [
    'joined',

];

function getJoinedAttribute()
{
    return $this->attributes['joined']->format('d.m.Y');
}

function setJoinedAttribute()
{
    return $this->attributes['joined']->format('Y-m-d');
}

Body:
You sould use Carbon library to convert date.

Like this :

 public function getDobAttribute($value)
    {
        return Carbon::parse($value)->format('d/m/Y');
    }

    public function setDobAttribute($value)
    {
        $this->attributes['dob'] = Carbon::createFromFormat('d/m/Y', $value)->toDateString();
    }


问:
Python3: Building dictionary from .fasta - "strange" printout for value
I am parsing a .fasta-File containing one big sequence into python by using:

```<code>for rec in SeqIO.parse(faFile, "fasta"):
    identifier=(rec.id)
    sequence=(rec.seq)
</code>```

Then, I am building a dictionary:

```<code>d={identifier:sequence}
</code>```

When printing sequence only, I get the following result:

```<code>CAGCCAGATGGGGGGAGGGGTGAGCGCTCTCCCGCTCAAAACCTCCAGCACTTT...CAT
</code>```

Note: All letters are printed, I made dots to shorten this

When printing the dictionary, I get:

```<code>{'NC_003047.1': Seq('CAGCCAGATGGGGGGAGGGGTGAGCGCTCTCCCGCTCAAAACCTCCAGCACTTT...CAT', SingleLetterAlphabet())}
</code>```

Where does the "Seq" and the SingleLetter alphabet come from?

Desired result would be:

```<code>{'NC_003047.1':'CAGCCAGATGGGGGGAGGGGTGAGCGCTCTCCCGCTCAAAACCTCCAGCACTTT...CAT'}
</code>```

Update1:

following the link in the comments, I tried

```<code>input_file=open(faFile)
d=SeqIO.to_dict(SeqIO.parse(faFile,"fasta"))
</code>```

resulting in:

```<code>{'NC_003047.1': SeqRecord(seq=Seq('CAGCCAGATGGGGGGAGGGGTGAGCGCTCTCCCGCTCAAAACCTCCAGCACTTT...CAT', SingleLetterAlphabet()), id='NC_003047.1', name='NC_003047.1', description='NC_003047.1 Sinorhizobium meliloti 1021 chromosome, complete genome', dbxrefs=[])}
</code>```

So, sadly, this does not help :(

Thanks in advance for your time and effort :)

答:
SeqIO doesn't return a string, it returns an object. When you print it, you print the object's string representation, which in this case is not just the data contained in (some attribute of) the object.

(Some objects are designed so that printing the object will print just the data inside it. This depends on how the library is put together and how the programmer designed its __str__() method. This is probably not useful for you at this point, but might help you understand other related resources you find if you pursue this further.)

I'm not familiar with SeqIO but quick googling suggests you probably want

```<code>d={identifier: sequence.seq}
</code>```

to put just the SeqIO object's seq attribute as the value for this identifier.

Body:
I am parsing a .fasta-File containing one big sequence into python by using:

for rec in SeqIO.parse(faFile, "fasta"):
    identifier=(rec.id)
    sequence=(rec.seq)

Then, I am building a dictionary:

d={identifier:sequence}

When printing sequence only, I get the following result:

CAGCCAGATGGGGGGAGGGGTGAGCGCTCTCCCGCTCAAAACCTCCAGCACTTT...CAT

Note: All letters are printed, I made dots to shorten this

When printing the dictionary, I get:

{'NC_003047.1': Seq('CAGCCAGATGGGGGGAGGGGTGAGCGCTCTCCCGCTCAAAACCTCCAGCACTTT...CAT', SingleLetterAlphabet())}

Where does the "Seq" and the SingleLetter alphabet come from?

Desired result would be:

{'NC_003047.1':'CAGCCAGATGGGGGGAGGGGTGAGCGCTCTCCCGCTCAAAACCTCCAGCACTTT...CAT'}

Update1:

following the link in the comments, I tried

input_file=open(faFile)
d=SeqIO.to_dict(SeqIO.parse(faFile,"fasta"))

resulting in:

{'NC_003047.1': SeqRecord(seq=Seq('CAGCCAGATGGGGGGAGGGGTGAGCGCTCTCCCGCTCAAAACCTCCAGCACTTT...CAT', SingleLetterAlphabet()), id='NC_003047.1', name='NC_003047.1', description='NC_003047.1 Sinorhizobium meliloti 1021 chromosome, complete genome', dbxrefs=[])}

So, sadly, this does not help :(

Thanks in advance for your time and effort :)

Body:
SeqIO doesn't return a string, it returns an object. When you print it, you print the object's string representation, which in this case is not just the data contained in (some attribute of) the object.

(Some objects are designed so that printing the object will print just the data inside it. This depends on how the library is put together and how the programmer designed its __str__() method. This is probably not useful for you at this point, but might help you understand other related resources you find if you pursue this further.)

I'm not familiar with SeqIO but quick googling suggests you probably want

d={identifier: sequence.seq}

to put just the SeqIO object's seq attribute as the value for this identifier.


问:
Converting a C-style string to a C++ std::string
What is the best way to convert a C-style string to a C++ std::string? In the past I've done it using stringstreams. Is there a better way?

答:
C++ strings have a constructor that lets you construct a std::string directly from a C-style string:

```<code>const char* myStr = "This is a C string!";
std::string myCppString = myStr;
</code>```

Or, alternatively:

```<code>std::string myCppString = "This is a C string!";
</code>```

As @TrevorHickey notes in the comments, be careful to make sure that the pointer you're initializing the std::string with isn't a null pointer. If it is, the above code leads to undefined behavior. Then again, if you have a null pointer, one could argue that you don't even have a string at all. :-)

Body:
C++ strings have a constructor that lets you construct a std::string directly from a C-style string:

const char* myStr = "This is a C string!";
std::string myCppString = myStr;

Or, alternatively:

std::string myCppString = "This is a C string!";

As @TrevorHickey notes in the comments, be careful to make sure that the pointer you're initializing the std::string with isn't a null pointer. If it is, the above code leads to undefined behavior. Then again, if you have a null pointer, one could argue that you don't even have a string at all. :-)


问:
Restrict or prevent iframe navigation
I have a top page which contains an iframe with untrusted content. I am hosting the untrusted content on a domain that I control, and can (in theory) make changes to it. Short of analyzing the source code with something like Google Caja, is there any way that I can prevent the untrusted content from navigating the frame itself to other URLs? (or ideally restrict it to the trusted domain)

Related, but not quite:

Only addresses anchor tags, not navigation in general

Lots and lots of webpages talking about sandbox with "allow-top-navigation". Doesn't help because I want to restrict navigation of the frame itself

Background: My goal is to allow untrusted content to run in the iframe and to pass some user data to it, but I don't want the untrusted content to turn around and send this data to a 3rd-party. (The content will be allowed instead to postMessage any results to an API exposed by the parent window.) Content Security Policy HTTP headers on the untrusted content allow me to restrict all manner of network requests except navigation.

答:
I randomly saw this new Content Security Policy option hinted at on MDN (with a little flask on it, so may still be experimental...)

navigation-to

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy

Title: Restrict or prevent iframe navigation


问:
HTTPRequest.getSession returns a fresh session after session is invalidated
I have developed a web app currently hosted in tomcat 8.5.I5. I am trying to implement SSO with IDP and here I have used filters for this. After sucessful login I set the user name as following.

```<code>HttpSession httpSession = request.getSession();
httpSession.setAttribute(SESSION_USERNAME, subject);
</code>```

When validating used the following code.

```<code>HttpServletRequest request = (HttpServletRequest) req;
HttpSession session = request.getSession();
String userName = (String) session.getAttribute(SSOHelper.SESSION_USERNAME);

 if (userName == null && request.getRequestURI().contains("dashboard.xhtml")) {
</code>```

Logout is implemented as follwing

request.getSession().invalidate();

The problem is this only works for the first time. Second time it keeps on asking the login. Seems the session is created per requested.

答: The issues seems to be when you define the host name without a dot (.). For example I have used localhost for my testing. After adding a entry to hosts file with domain name malaka.com, and used to access the web app, issue was resolved.</p>

Body:
I have developed a web app currently hosted in tomcat 8.5.I5. I am trying to implement SSO with IDP and here I have used filters for this. After sucessful login I set the user name as following.

HttpSession httpSession = request.getSession();
httpSession.setAttribute(SESSION_USERNAME, subject);

When validating used the following code.

HttpServletRequest request = (HttpServletRequest) req;
HttpSession session = request.getSession();
String userName = (String) session.getAttribute(SSOHelper.SESSION_USERNAME);

 if (userName == null && request.getRequestURI().contains("dashboard.xhtml")) {

Logout is implemented as follwing

request.getSession().invalidate();

The problem is this only works for the first time. Second time it keeps on asking the login. Seems the session is created per requested.


问:
Android: Creating a custom alert dialog inside a dynamic onclicklistener
Not sure how well that title describes what I am hoping to do but here goes. Basically I have an app that pragmatically creates a list of buttons which when clicked then return a description.

I created the following class

```<code>public class DynamicOnClickListener implements OnClickListener
{

    String description;
    public DynamicOnClickListener(String adesc) {
        //sets the description attribute at instantiation
         this.description = adesc;
    }

    public void onClick(View v) {
        //on button click returns dialog box with description in it
        Log.v("DynamicOnClickListener","1");
        AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
        builder.setMessage(description);
        builder.setCancelable(false);
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id)
                   {
                       dialog.cancel();
                   }
               });
        AlertDialog alert = builder.create();
        alert.show();
    }

 }
</code>```

This works perfectly as is, however I would very much like to jazz up the dialog box somewhat. I have been looking at some examples online and according to the android docs they suggest defining a custom xml layout and using LayourInflator set the custom xml as the view for the dialog. (Well thats how I understood it anyway, probably wrongly right enough)

Although the docs example is slightly different from mine, according to their example I should add the following lines

```<code>// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();

// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
</code>```

However when I add this to my class, resulting in the following I get an error on getActivity()

```<code>public class DynamicOnClickListener implements OnClickListener
{

    String description;
    public DynamicOnClickListener(String adesc) {
        //sets the description attribute at instantiation
         this.description = adesc;
    }

    public void onClick(View v) {
        //on button click returns dialog box with program description in it
        Log.v("DynamicOnClickListener","1");
        AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());

        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();

        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        builder.setView(inflater.inflate(R.layout.description_dialog, null));

        builder.setMessage(description);
        builder.setCancelable(false);
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id)
                   {
                       dialog.cancel();
                   }
               });
        AlertDialog alert = builder.create();
        alert.show();
    }

 }
</code>```

答:
According to CoderDecoder and kleopatra's answers here is the updated version with a shape.

```<code>    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    GradientDrawable shape = new GradientDrawable();
    shape.setColor(getResources().getColor(R.color.shape_client_textview_background_color));
    shape.setStroke(10, getResources().getColor(R.color.shape_client_textview_border_color));
    shape.setCornerRadius(50);

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
    LinearLayout popUp = new LinearLayout(this);
   // popUp.setBackgroundColor(Color.LTGRAY);
    layoutParams.setMargins(20,20,20,20);
    popUp.setOrientation(LinearLayout.VERTICAL);
    popUp.setLayoutParams(layoutParams);
    popUp.setBackground(shape);
    popUp.setPadding(20,20,20,20);

    EditText t1 = new EditText(this);
    t1.setHint("Enter Your Email ID ");
    t1.setTextColor(Color.parseColor("#FFFFFF"));
    t1.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);

    LinearLayout btnLayout = new LinearLayout(this);
 //   btnLayout.setBackgroundColor(Color.LTGRAY);
    btnLayout.setOrientation(LinearLayout.HORIZONTAL);
    btnLayout.setGravity(Gravity.CENTER);

    Button send = new Button(this);
    send.setText("Send");
    send.setTextColor(Color.WHITE);
    Button cancel = new Button(this);
    cancel.setText("Cancel");
    cancel.setTextColor(Color.WHITE);

    btnLayout.addView(send);
    btnLayout.addView(cancel);
    popUp.addView(t1);
    popUp.addView(btnLayout);

    dialog.setContentView(popUp);
    cancel.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            dialog.dismiss();
        }
    });

    dialog.show();
</code>```

Here is the result:

Body:
Not sure how well that title describes what I am hoping to do but here goes. Basically I have an app that pragmatically creates a list of buttons which when clicked then return a description.

I created the following class

public class DynamicOnClickListener implements OnClickListener
{

    String description;
    public DynamicOnClickListener(String adesc) {
        //sets the description attribute at instantiation
         this.description = adesc;
    }

    public void onClick(View v) {
        //on button click returns dialog box with description in it
        Log.v("DynamicOnClickListener","1");
        AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
        builder.setMessage(description);
        builder.setCancelable(false);
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id)
                   {
                       dialog.cancel();
                   }
               });
        AlertDialog alert = builder.create();
        alert.show();
    }

 }

This works perfectly as is, however I would very much like to jazz up the dialog box somewhat. I have been looking at some examples online and according to the android docs they suggest defining a custom xml layout and using LayourInflator set the custom xml as the view for the dialog. (Well thats how I understood it anyway, probably wrongly right enough)

Although the docs example is slightly different from mine, according to their example I should add the following lines

// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();

// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))

However when I add this to my class, resulting in the following I get an error on getActivity()

public class DynamicOnClickListener implements OnClickListener
{

    String description;
    public DynamicOnClickListener(String adesc) {
        //sets the description attribute at instantiation
         this.description = adesc;
    }

    public void onClick(View v) {
        //on button click returns dialog box with program description in it
        Log.v("DynamicOnClickListener","1");
        AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());

        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();

        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        builder.setView(inflater.inflate(R.layout.description_dialog, null));

        builder.setMessage(description);
        builder.setCancelable(false);
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id)
                   {
                       dialog.cancel();
                   }
               });
        AlertDialog alert = builder.create();
        alert.show();
    }

 }

Body:
According to CoderDecoder and kleopatra's answers here is the updated version with a shape.

    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    GradientDrawable shape = new GradientDrawable();
    shape.setColor(getResources().getColor(R.color.shape_client_textview_background_color));
    shape.setStroke(10, getResources().getColor(R.color.shape_client_textview_border_color));
    shape.setCornerRadius(50);

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
    LinearLayout popUp = new LinearLayout(this);
   // popUp.setBackgroundColor(Color.LTGRAY);
    layoutParams.setMargins(20,20,20,20);
    popUp.setOrientation(LinearLayout.VERTICAL);
    popUp.setLayoutParams(layoutParams);
    popUp.setBackground(shape);
    popUp.setPadding(20,20,20,20);

    EditText t1 = new EditText(this);
    t1.setHint("Enter Your Email ID ");
    t1.setTextColor(Color.parseColor("#FFFFFF"));
    t1.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);

    LinearLayout btnLayout = new LinearLayout(this);
 //   btnLayout.setBackgroundColor(Color.LTGRAY);
    btnLayout.setOrientation(LinearLayout.HORIZONTAL);
    btnLayout.setGravity(Gravity.CENTER);

    Button send = new Button(this);
    send.setText("Send");
    send.setTextColor(Color.WHITE);
    Button cancel = new Button(this);
    cancel.setText("Cancel");
    cancel.setTextColor(Color.WHITE);

    btnLayout.addView(send);
    btnLayout.addView(cancel);
    popUp.addView(t1);
    popUp.addView(btnLayout);

    dialog.setContentView(popUp);
    cancel.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            dialog.dismiss();
        }
    });

    dialog.show();

Here is the result:


答:
1) read the content of the directory to a variable (array)

2) sort the array as you need using any of those: Sorting Arrays

3) run your while to print the file names..

Title: How to sort my images by name?

Body:
/* function:  returns files from dir */
function get_files($images_dir,$exts = array('jpg')) {
    $files = array();
    if($handle = opendir($images_dir)) {
        while(false !== ($file = readdir($handle))) {
            $extension = strtolower(get_file_extension($file));
            if($extension && in_array($extension,$exts)) {
                $files[] = $file;
            }
        }
        closedir($handle);
    }
    return $files;
}

I have images named 01-image.jpg, 02-image.jpg etc but when I echo them out, they are in random order, how do I order them by name?


问:
Exoplayer video frames moves forward in pause state in api<23
I an using exoplayer in recyclerview. All my video are in recyclerview is in pause mode. So Video postion should remain same  when I come back to same video after scrolling.
But in my case video frames moves forward  when I come back to same video after scrolling.This happens in api lower then marshmallow(23)

I an using library  'com.google.android.exoplayer:exoplayer:r2.5.4'

Here my adapter bind data of viewholder code:

```<code>  public class VideoViewHolder extends RecyclerView.ViewHolder {

    View parent;
    SimpleExoPlayer player;
    VideoSurfaceView videoSurfaceView;
    private DefaultTrackSelector trackSelector;
    private int mainHandler;
    private MediaSource mediaSource;

    public VideoViewHolder(final View v) {
        super(v);
        parent = v;
        imgAudio = v.findViewById(R.id.imgAudio);
        videoSurfaceView = v.findViewById(R.id.exo_player);
        aspectRatioFrameLayout = v.findViewById(R.id.control_frame);
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = getAdapterPosition();
                if (position == -1)
                    return;
                VideoUri videoUri = videoInfoList.get(position);
                if (videoUri == null)
                    return;
                Intent intent = new Intent(context, PlayrtActivity.class);
                intent.putExtra("videoUri", videoUri);
                context.startActivity(intent);
            }
        });
    }

    void bindData(int position) {
        if (position == -1)
            return;
        VideoUri videoUri = videoInfoList.get(position);
        if (videoUri == null)
            return;
        BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        TrackSelection.Factory adaptiveTrackSelectionFactory =
                new AdaptiveTrackSelection.Factory(bandwidthMeter);

        trackSelector = new DefaultTrackSelector(adaptiveTrackSelectionFactory);
        @DefaultRenderersFactory.ExtensionRendererMode int extensionRendererMode =
                DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF;
        DefaultRenderersFactory renderersFactory = new DefaultRenderersFactory(context,
                null, extensionRendererMode);

        LoadControl loadControl =
                new DefaultLoadControl(new DefaultAllocator(true, C.DEFAULT_BUFFER_SEGMENT_SIZE), 5000, 10000, 2500, 5000);

            if (player == null) {
                player = ExoPlayerFactory.newSimpleInstance(renderersFactory, trackSelector,loadControl);
                MediaSourceBuilder mediaSourceBuilder = new MediaSourceBuilder(context, videoUri.getUri());
                mediaSource = mediaSourceBuilder.build();

                player.prepare(mediaSource);
                player.setVideoSurfaceView(videoSurfaceView);
                player.setPlayWhenReady(false);
            }
     }
</code>```

答: Your videos are getting recycled (removed from memory). So, you need to save the videos position and add an onStart listener to the player that seek to that position.

Body:
I an using exoplayer in recyclerview. All my video are in recyclerview is in pause mode. So Video postion should remain same  when I come back to same video after scrolling.
But in my case video frames moves forward  when I come back to same video after scrolling.This happens in api lower then marshmallow(23)

I an using library  'com.google.android.exoplayer:exoplayer:r2.5.4'

Here my adapter bind data of viewholder code:

  public class VideoViewHolder extends RecyclerView.ViewHolder {

    View parent;
    SimpleExoPlayer player;
    VideoSurfaceView videoSurfaceView;
    private DefaultTrackSelector trackSelector;
    private int mainHandler;
    private MediaSource mediaSource;

    public VideoViewHolder(final View v) {
        super(v);
        parent = v;
        imgAudio = v.findViewById(R.id.imgAudio);
        videoSurfaceView = v.findViewById(R.id.exo_player);
        aspectRatioFrameLayout = v.findViewById(R.id.control_frame);
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = getAdapterPosition();
                if (position == -1)
                    return;
                VideoUri videoUri = videoInfoList.get(position);
                if (videoUri == null)
                    return;
                Intent intent = new Intent(context, PlayrtActivity.class);
                intent.putExtra("videoUri", videoUri);
                context.startActivity(intent);
            }
        });
    }

    void bindData(int position) {
        if (position == -1)
            return;
        VideoUri videoUri = videoInfoList.get(position);
        if (videoUri == null)
            return;
        BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        TrackSelection.Factory adaptiveTrackSelectionFactory =
                new AdaptiveTrackSelection.Factory(bandwidthMeter);

        trackSelector = new DefaultTrackSelector(adaptiveTrackSelectionFactory);
        @DefaultRenderersFactory.ExtensionRendererMode int extensionRendererMode =
                DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF;
        DefaultRenderersFactory renderersFactory = new DefaultRenderersFactory(context,
                null, extensionRendererMode);

        LoadControl loadControl =
                new DefaultLoadControl(new DefaultAllocator(true, C.DEFAULT_BUFFER_SEGMENT_SIZE), 5000, 10000, 2500, 5000);

            if (player == null) {
                player = ExoPlayerFactory.newSimpleInstance(renderersFactory, trackSelector,loadControl);
                MediaSourceBuilder mediaSourceBuilder = new MediaSourceBuilder(context, videoUri.getUri());
                mediaSource = mediaSourceBuilder.build();

                player.prepare(mediaSource);
                player.setVideoSurfaceView(videoSurfaceView);
                player.setPlayWhenReady(false);
            }
     }


问:
Windows Service running but event logs not working
I have a windows service listening to messages from a queue but the messages are not read from the queue.I created an event log to check for logs during service startup and shutdown but the logs are not written. I do not want to debug the service since it is a painful process.Is there a way to solve this issue.The messages need to be read by the service and written to a database.</p>

答:
This certainly sounds as if the account that your windows service is running under doesn't have enough rights to write to the event log in question.

Setting event log permissions for non-admin accounts can be a bit of a black art because you need to configure custom security descriptors using SDDL etc. However there's a very handy MS knowledgebase article on how to do this programmatically:

How to setup event log security programmatically using the .Net Framework

I use this all the time now and it's as simple as:

```<code>int mask = EventLogSecurity.CustomSD_ALL_ACCESS;

string logName = "Application";
string domain = "MyMachineOrDomainName";
string account = "UserAccount";

EventLogSecurity.AddUserToEventLogCustomSD(logName, domain, account, mask);
</code>```

OwnerDisplayName: kjayakum

LastEditorDisplayName: Ben Alpert

Body:
This certainly sounds as if the account that your windows service is running under doesn't have enough rights to write to the event log in question.

Setting event log permissions for non-admin accounts can be a bit of a black art because you need to configure custom security descriptors using SDDL etc. However there's a very handy MS knowledgebase article on how to do this programmatically:

How to setup event log security programmatically using the .Net Framework

I use this all the time now and it's as simple as:

int mask = EventLogSecurity.CustomSD_ALL_ACCESS;

string logName = "Application";
string domain = "MyMachineOrDomainName";
string account = "UserAccount";

EventLogSecurity.AddUserToEventLogCustomSD(logName, domain, account, mask);

OwnerDisplayName: Kev


问:
Display multiple images on scrollview by using DKImagePickerController
I would like to display multiple images on scrollview when user selected images with DKImagePickerController github.
Here is my code but images don't appear. Anyone can tell what's wrong?
Thank you in advance!</p>

```<code>    var picker = DKImagePickerController()
    var imagesArray = [Any]()

     @IBAction func pickPhoto(_ sender: Any) {

            picker.maxSelectableCount = 10
            picker.showsCancelButton = true
            picker.allowsLandscape = false
            picker.assetType = .allPhotos

            self.present(picker, animated: true)

            picker.didSelectAssets = { (assets: [DKAsset]) in

                self.imagesArray.append(assets)

                for i in 0..<self.imagesArray.count {

                    let imageView = UIImageView()
                    imageView.image = self.imagesArray[i] as? UIImage
                    imageView.contentMode = .scaleAspectFit
                    let xposition = self.view.frame.width * CGFloat(i)
                    imageView.frame = CGRect(x: xposition, y: 330, width: self.scrollView.frame.width, height: 170)
                    self.scrollView.contentSize.width = self.scrollView.frame.width * CGFloat(i * 1)
                    self.scrollView.addSubview(imageView)
                }

            }

        }
</code>```

答:
Instead of displaying images to scrollView, you can add that images in array  and reload the collectionView/TableView..

as I did it here in collectionView

```<code>func showImagePicker() {
    let pickerController = DKImagePickerController()
    self.previewView?.isHidden = false
    pickerController.assetType = .allPhotos
    pickerController.defaultAssetGroup = .smartAlbumUserLibrary
    pickerController.didSelectAssets = { (assets: [DKAsset]) in
        if  assets.count>0
        {
            for var i in 0 ... assets.count-1 {
                assets[i].fetchOriginalImage(true, completeBlock: { (image, info) in
                        self.abc.append(image)
                })
            }
        }
        self.previewView?.reloadData()
    }
    self.present(pickerController, animated: true) {}
}
</code>```

Here abc :[UIImage] and previewView? : UICollectionView
 and in collection delegate methods:

```<code>public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    return self.abc.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    var cell: UICollectionViewCell?
    var imageView: UIImageView?

    cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellImage", for: indexPath)
    imageView = cell?.contentView.viewWithTag(1) as? UIImageView
    if let cell = cell, let imageView = imageView
    {
        let tag = indexPath.row + 1
        cell.tag = tag
        imageView.image = self.abc[indexPath.row]
    }
    return cell!
}
</code>```

Body:
I would like to display multiple images on scrollview when user selected images with DKImagePickerController github.
Here is my code but images don't appear. Anyone can tell what's wrong?
Thank you in advance!

    var picker = DKImagePickerController()
    var imagesArray = [Any]()

     @IBAction func pickPhoto(_ sender: Any) {

            picker.maxSelectableCount = 10
            picker.showsCancelButton = true
            picker.allowsLandscape = false
            picker.assetType = .allPhotos

            self.present(picker, animated: true)

            picker.didSelectAssets = { (assets: [DKAsset]) in

                self.imagesArray.append(assets)

                for i in 0..<self.imagesArray.count {

                    let imageView = UIImageView()
                    imageView.image = self.imagesArray[i] as? UIImage
                    imageView.contentMode = .scaleAspectFit
                    let xposition = self.view.frame.width * CGFloat(i)
                    imageView.frame = CGRect(x: xposition, y: 330, width: self.scrollView.frame.width, height: 170)
                    self.scrollView.contentSize.width = self.scrollView.frame.width * CGFloat(i * 1)
                    self.scrollView.addSubview(imageView)
                }

            }

        }

Body:
Instead of displaying images to scrollView, you can add that images in array  and reload the collectionView/TableView..

as I did it here in collectionView

func showImagePicker() {
    let pickerController = DKImagePickerController()
    self.previewView?.isHidden = false
    pickerController.assetType = .allPhotos
    pickerController.defaultAssetGroup = .smartAlbumUserLibrary
    pickerController.didSelectAssets = { (assets: [DKAsset]) in
        if  assets.count>0
        {
            for var i in 0 ... assets.count-1 {
                assets[i].fetchOriginalImage(true, completeBlock: { (image, info) in
                        self.abc.append(image)
                })
            }
        }
        self.previewView?.reloadData()
    }
    self.present(pickerController, animated: true) {}
}

Here abc :[UIImage] and previewView? : UICollectionView
 and in collection delegate methods:

public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    return self.abc.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    var cell: UICollectionViewCell?
    var imageView: UIImageView?

    cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellImage", for: indexPath)
    imageView = cell?.contentView.viewWithTag(1) as? UIImageView
    if let cell = cell, let imageView = imageView
    {
        let tag = indexPath.row + 1
        cell.tag = tag
        imageView.image = self.abc[indexPath.row]
    }
    return cell!
}


问:
String comparison in JS for logic operators
I'm attempting to allow user defined logic criteria. Since the user definitions are basically strings, I'm trying to make the code efficient by avoiding string comparison. For example, a simple test like a == 10 would be represented by an array

```<code>var userDef = ['a', '==', 10]
</code>```

To make the logic evaluation efficient, I'd like to create an object like the ffg:

```<code>var binaryOperator = {'==': 0, '>': 1, '<': 2}
</code>```

.. so when I mine the array, I could do e.g.

```<code>if(binaryOperator[userdef[1]] == 0)
{
    return (obj[userDef[0]] == userDef[2])
}
</code>```

... where of course obj.a = something. The above code, on the face of it, avoids string comparison.

But does it really? Is the reference binaryOperator[userdef[1]] really fast or does it also involve string comparison somewhere?

In other words is there a performance difference between thisObj.a and thisObj['a']?

答:
You could omit the check for the operator and take a function as value, like

```<code>var binaryOperator = {
        '==': function (a, b) { return a === b; },
        '<': function (a, b) { return a < b; },
        '>': function (a, b) { return a > b; }
    };
</code>```

Objects in Javascript have an access of O(1).

Further readings:

Performance of key lookup in JavaScript object, JS engine desings

JavaScript object structure: speed matters, by using a fully defined object instead of adding properties at run time.

Body:
I'm attempting to allow user defined logic criteria. Since the user definitions are basically strings, I'm trying to make the code efficient by avoiding string comparison. For example, a simple test like a == 10 would be represented by an array

var userDef = ['a', '==', 10]

To make the logic evaluation efficient, I'd like to create an object like the ffg:

var binaryOperator = {'==': 0, '>': 1, '<': 2}

.. so when I mine the array, I could do e.g.

if(binaryOperator[userdef[1]] == 0)
{
    return (obj[userDef[0]] == userDef[2])
}

... where of course obj.a = something. The above code, on the face of it, avoids string comparison.

But does it really? Is the reference binaryOperator[userdef[1]] really fast or does it also involve string comparison somewhere?

In other words is there a performance difference between thisObj.a and thisObj['a']?

Body:
You could omit the check for the operator and take a function as value, like

var binaryOperator = {
        '==': function (a, b) { return a === b; },
        '<': function (a, b) { return a < b; },
        '>': function (a, b) { return a > b; }
    };

Objects in Javascript have an access of O(1).

Further readings:

Performance of key lookup in JavaScript object, JS engine desings

JavaScript object structure: speed matters, by using a fully defined object instead of adding properties at run time.


问:
BASH: If condition uses result from find command to determine which file will be written
I want to list all files in a nested directory, but in that directory has some files which having space in their name. So I wanna write down the paths of which files don't have space in their name and which have in 2 different files.

So far, I just know how to find those having space in their name by this command:

```<code>find /<my directory> -type f -name * *
</code>```

I want something like:

```<code>find /<my directory> -type f
   if [ name has space]
   then > a.txt
   else > b.txt
   fi
</code>```

Thank you in advance.

答:
Use two separate commands:</p>

```<code>find "$path" -type f -name '* *' > a.txt
find "$path" -type f -not -name '* *' > b.txt
</code>```

Body:
I want to list all files in a nested directory, but in that directory has some files which having space in their name. So I wanna write down the paths of which files don't have space in their name and which have in 2 different files.

So far, I just know how to find those having space in their name by this command:

find /<my directory> -type f -name * *

I want something like:

find /<my directory> -type f
   if [ name has space]
   then > a.txt
   else > b.txt
   fi

Thank you in advance.

Body:
Use two separate commands:

find "$path" -type f -name '* *' > a.txt
find "$path" -type f -not -name '* *' > b.txt


问:
Port number settings in cloud9, for elasticsearch and rails system
now I'm working on a Full-text search system, using web browser UI to find any text data file in my local network.

Here is develop environment.

OS：Macbook Air　El Capitan　10.11.6

IDE:Cloud9

Lang:Ruby on Rails

SearchEngine:Elasticsearch

Using this site as a reference, I faced problems of PORT number many times.

(don't need to read sentence, since it's written in Japanese)

==========

I got this error many times importing db:seed, making index( _elasticsearch__.
create.~), ... and so on.

Faraday::ConnectionFailed: Failed to open TCP connection to localhost:9200 (Connection refused - connect(2) for "localhost" port 9200)

Also, I can't see anything in "localhost:9200" in my browser.
I had no setting about PORT number in cloud9, how should I do?

setting parameters in cloud9(cloud-network)

download this project from cloud9, and continue to make in local-network

which is better, or another better plan...

答:
Follow the elastic search documentation

Installation

Download and unzip the Elasticsearch official distribution.

Run bin/elasticsearch on unix, or bin\elasticsearch.bat on windows.

Run curl -X GET http://localhost:9200/.

Start more servers …


问:
Best practice for px-to-rem mixins
I am creating some mixins to make me easier to convert px to rem values in margin which has 4 parameters top, right, bottom and left. In my code below, I make 16 mixins which is checking whether if the parameter is pixel or not.

```<code>// TODO --> margin

// T T T T
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// T F T T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// T T F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem @bottom unit(@left)/@base-font*1rem;
}

// T F F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right @bottom unit(@left)/@base-font*1rem;
}

// T T T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem @left;
}

// T F T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right unit(@bottom)/@base-font*1rem @left;
}

// T T F F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem @bottom @left;
}

// T F F F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right @bottom @left;
}

// F T T T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// F F T T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top @right unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// F T F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem @bottom unit(@left)/@base-font*1rem;
}

// F F F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top @right @bottom unit(@left)/@base-font*1rem;
}

// F T T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem @left;
}

// F F T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: @top @right unit(@bottom)/@base-font*1rem @left;
}

// F T F F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem @bottom @left;
}

// F F F F
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
}
</code>```

I have a problem when passing auto or not-a-number type of variables but it works with number and number with unit like px, rem, em, etc.

and when I see in developer mode it looks like this

Is there a better way to make my code clearer and not make a much junk in compiled css?

UPDATE

I forgot that I used , instead of and

Thank you, and sorry for my English

答:
You can use mixin as a function. to-rem can take up to 4 parameters to convert them to rem. @base-font is an additional parameter. This mixin returns 4 variables (@var1, @var2, @var3, @var4) in scope where it was called. But you can not call this mixin twice in the same scope. For margins and paddings, for example.

```<code>.to-rem(@v1: 0, @v2: 0, @v3: 0, @v4: 0, @base-font: 14px) {
  @var1: unit(@v1) / @base-font * 1rem;
  @var2: unit(@v2) / @base-font * 1rem;
  @var3: unit(@v3) / @base-font * 1rem;
  @var4: unit(@v4) / @base-font * 1rem;
}
</code>```

Usage:

```<code>a {
  .to-rem(12px, 20px, 24px, 20px);

  margin: @var1 @var2 @var3 @var4;
}

a {
  .to-rem(12px);

  margin-top: @var1;
}
</code>```

Generated css:

```<code>a {
  margin: 0.85714286rem 1.42857143rem 1.71428571rem 1.42857143rem;
}
a {
  margin-top: 0.85714286rem;
}
</code>```

Or you can rewrite your mixins to have only one margin mixin:

```<code>@base-font: 14px;

.margin(@top: null, @right: null, @bottom: null, @left: null) {
  & when not (@top = null) {
    & when (ispixel(@top)) {
      margin-top: unit(@top) / @base-font * 1rem;
    }
    & when not (ispixel(@top)) {
      margin-top: @top;
    }
  }
  & when not (@right = null) {
    & when (ispixel(@right)) {
      margin-right: unit(@right) / @base-font * 1rem;
    }
    & when not (ispixel(@right)) {
      margin-right: @right;
    }
  }
  & when not (@bottom = null) {
    & when (ispixel(@bottom)) {
      margin-bottom: unit(@bottom) / @base-font * 1rem;
    }
    & when not (ispixel(@bottom)) {
      margin-bottom: @bottom;
    }
  }
  & when not (@left = null) {
    & when (ispixel(@left)) {
      margin-left: unit(@left) / @base-font * 1rem;
    }
    & when not (ispixel(@left)) {
      margin-left: @left;
    }
  }
}
</code>```

Usage:

```<code>a {
  .margin(12px, 20px, 10px, 20px);
}
a {
  .margin(@top: auto); // You can pass only those params you need
}
</code>```

Generated css:

```<code>a {
  // Don't know how to combine this properties
  margin-top: 0.85714286rem;
  margin-right: 1.42857143rem;
  margin-bottom: 0.71428571rem;
  margin-left: 1.42857143rem;
}
a {
  margin-top: auto;
}
</code>```

Title: Best practice for px-to-rem mixins

Body:
I am creating some mixins to make me easier to convert px to rem values in margin which has 4 parameters top, right, bottom and left. In my code below, I make 16 mixins which is checking whether if the parameter is pixel or not.

// TODO --> margin

// T T T T
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// T F T T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// T T F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem @bottom unit(@left)/@base-font*1rem;
}

// T F F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right @bottom unit(@left)/@base-font*1rem;
}

// T T T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem @left;
}

// T F T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right unit(@bottom)/@base-font*1rem @left;
}

// T T F F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem @bottom @left;
}

// T F F F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right @bottom @left;
}

// F T T T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// F F T T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top @right unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// F T F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem @bottom unit(@left)/@base-font*1rem;
}

// F F F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top @right @bottom unit(@left)/@base-font*1rem;
}

// F T T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem @left;
}

// F F T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: @top @right unit(@bottom)/@base-font*1rem @left;
}

// F T F F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem @bottom @left;
}

// F F F F
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
}

I have a problem when passing auto or not-a-number type of variables but it works with number and number with unit like px, rem, em, etc.

and when I see in developer mode it looks like this

Is there a better way to make my code clearer and not make a much junk in compiled css?

UPDATE

I forgot that I used , instead of and

Thank you, and sorry for my English

Body:
You can use mixin as a function. to-rem can take up to 4 parameters to convert them to rem. @base-font is an additional parameter. This mixin returns 4 variables (@var1, @var2, @var3, @var4) in scope where it was called. But you can not call this mixin twice in the same scope. For margins and paddings, for example.

.to-rem(@v1: 0, @v2: 0, @v3: 0, @v4: 0, @base-font: 14px) {
  @var1: unit(@v1) / @base-font * 1rem;
  @var2: unit(@v2) / @base-font * 1rem;
  @var3: unit(@v3) / @base-font * 1rem;
  @var4: unit(@v4) / @base-font * 1rem;
}

Usage:

a {
  .to-rem(12px, 20px, 24px, 20px);

  margin: @var1 @var2 @var3 @var4;
}

a {
  .to-rem(12px);

  margin-top: @var1;
}

Generated css:

a {
  margin: 0.85714286rem 1.42857143rem 1.71428571rem 1.42857143rem;
}
a {
  margin-top: 0.85714286rem;
}

Or you can rewrite your mixins to have only one margin mixin:

@base-font: 14px;

.margin(@top: null, @right: null, @bottom: null, @left: null) {
  & when not (@top = null) {
    & when (ispixel(@top)) {
      margin-top: unit(@top) / @base-font * 1rem;
    }
    & when not (ispixel(@top)) {
      margin-top: @top;
    }
  }
  & when not (@right = null) {
    & when (ispixel(@right)) {
      margin-right: unit(@right) / @base-font * 1rem;
    }
    & when not (ispixel(@right)) {
      margin-right: @right;
    }
  }
  & when not (@bottom = null) {
    & when (ispixel(@bottom)) {
      margin-bottom: unit(@bottom) / @base-font * 1rem;
    }
    & when not (ispixel(@bottom)) {
      margin-bottom: @bottom;
    }
  }
  & when not (@left = null) {
    & when (ispixel(@left)) {
      margin-left: unit(@left) / @base-font * 1rem;
    }
    & when not (ispixel(@left)) {
      margin-left: @left;
    }
  }
}

Usage:

a {
  .margin(12px, 20px, 10px, 20px);
}
a {
  .margin(@top: auto); // You can pass only those params you need
}

Generated css:

a {
  // Don't know how to combine this properties
  margin-top: 0.85714286rem;
  margin-right: 1.42857143rem;
  margin-bottom: 0.71428571rem;
  margin-left: 1.42857143rem;
}
a {
  margin-top: auto;
}


答:
You can initialise a std::string directly from a c-string:

```<code>std::string s = "i am a c string";
std::string t = std::string("i am one too");
</code>```

Title: Converting a C-style string to a C++ std::string

Body: What is the best way to convert a C-style string to a C++ std::string? In the past I've done it using stringstreams. Is there a better way?

Body:
You can initialise a std::string directly from a c-string:

std::string s = "i am a c string";
std::string t = std::string("i am one too");


问:
CLion doesn't have CSV file support?
I'm new to Clion, switching form Visual Studio and I'm trying to impliment a program that reads in data from a .csv file. However, after I put the file in the directory it doesn't seem to recognize the file. Any resources? I can't find anything on jetBrain about this either.
Thanks. </p>

答:
Just like Konafets, I am not quite sure about what your exact problem is, but have you tried installing the CSV Plugin for CLion?

Go to File | Settings | Plugins, type 'csv' in the search bar, click 'Search in repositories' until you land on the install page.

Title: CLion doesn't have CSV file support?


问:
How to set Cron Job using phpseclib?
```<code>        set_include_path(get_include_path() . PATH_SEPARATOR . 'C:\wamp\www\Web Apps\backend\phpsec');
        include ('phpsec/Net/SSH2.php');
        $ssh = new Net_SSH2('www.example.com');
        if (!($ssh->login('userlogin', 'password'))) {
            exit('Login Failed');
        }

        echo "Login Success<br>";

        $output=$ssh->exec('crontab -e;30 17 * * 1 /path/to/command')

        echo "$output";
</code>```

Here I am trying to set cron job. But it gives following error "Error opening terminal: unknown. /usr/bin/crontab.cagefs: "pico" exited with status 1 bash: 30: command not found" So how to set cron job using phpseclib?

答:
Write the following command in exec() function</p>

```<code>  $ssh->exec('crontab -l | { cat; echo "* * * * * /path/to/command/"; } | crontab -');
</code>```

Title: How to set Cron Job using phpseclib?

Body:
        set_include_path(get_include_path() . PATH_SEPARATOR . 'C:\wamp\www\Web Apps\backend\phpsec');
        include ('phpsec/Net/SSH2.php');
        $ssh = new Net_SSH2('www.example.com');
        if (!($ssh->login('userlogin', 'password'))) {
            exit('Login Failed');
        }

        echo "Login Success
";

        $output=$ssh->exec('crontab -e;30 17 * * 1 /path/to/command')

        echo "$output";

Here I am trying to set cron job. But it gives following error "Error opening terminal: unknown. /usr/bin/crontab.cagefs: "pico" exited with status 1 bash: 30: command not found" So how to set cron job using phpseclib?

Body:
Write the following command in exec() function

  $ssh->exec('crontab -l | { cat; echo "* * * * * /path/to/command/"; } | crontab -');


问:
pact: validate that an array contains a matching hash
I have a service that returns an array of hashes, the order of which is non-deterministic.  I need to validate that there exists one hash that has a certain key/value, and that hash is populated with data, but the rest of the hashes I don't care about their data.  For example, if the service returns this:

```<code>[
    {
        "key":"meaningless1",
        "data": {

        }
    },
    {
        "key":"meaningless2",
        "data": {
            "some": "data",
            "goes": ["here"]
        }
    },
    {
        "key":"meaningful",
        "data": {
            "regex": "value",
            "integer": 1,
            "boolean": true
        }
    }
]
</code>```

I want to validate that in the array, there is a hash that has "key":"meaningful", and that the data hash in that hash has a key of regex with a value that matches a regex, a key of integer that is an integer, and a key of boolean that is a boolean.  I don't care if the other hashes have data at all, or if the data they have matches this schema.

I can't use EachLike, because that will verify the schema against all the hashes, not just the one with the right key.  I also tried something like this:

```<code>expected = [
    {
        "key":"meaningful",
        "data":{
            "regex":Term("v.*", "value"),
            "integer":Like(1),
            "boolean":Like(True)
        }
    }
]
</code>```

But it simply tried to verify that against the 0th element in the resulting array, which means it tried to verify against:

```<code>{
    "key":"meaningless1",
    "data": {

    }
},
</code>```

Is what I want possible?

答:
This is not currently possible. You might like to join this conversation about the feature that you are asking for: https://github.com/pact-foundation/pact-specification/issues/38

However, one thing that I will point out is that pact works best when you can control the data on the provider. If you cannot control the data, then pact might not be the best tool for your scenario. Have a read of: https://github.com/pact-foundation/pact-ruby/wiki/Why-Pact-may-not-be-the-best-tool-for-testing-public-APIs

Body:
I have a service that returns an array of hashes, the order of which is non-deterministic.  I need to validate that there exists one hash that has a certain key/value, and that hash is populated with data, but the rest of the hashes I don't care about their data.  For example, if the service returns this:

[
    {
        "key":"meaningless1",
        "data": {

        }
    },
    {
        "key":"meaningless2",
        "data": {
            "some": "data",
            "goes": ["here"]
        }
    },
    {
        "key":"meaningful",
        "data": {
            "regex": "value",
            "integer": 1,
            "boolean": true
        }
    }
]

I want to validate that in the array, there is a hash that has "key":"meaningful", and that the data hash in that hash has a key of regex with a value that matches a regex, a key of integer that is an integer, and a key of boolean that is a boolean.  I don't care if the other hashes have data at all, or if the data they have matches this schema.

I can't use EachLike, because that will verify the schema against all the hashes, not just the one with the right key.  I also tried something like this:

expected = [
    {
        "key":"meaningful",
        "data":{
            "regex":Term("v.*", "value"),
            "integer":Like(1),
            "boolean":Like(True)
        }
    }
]

But it simply tried to verify that against the 0th element in the resulting array, which means it tried to verify against:

{
    "key":"meaningless1",
    "data": {

    }
},

Is what I want possible?


问:
How to get OleDb for reading excel in asp.net core project
Is there any way of reading excel data in ASP.NET Core (built over .Net Core)? I am not able to refer OleDB in project.json of my .net core project. Is there any other way of doing this?

答:
As indicated by andrews, it is recommended to use a third-party library, especially when working with formatting. An alternative to ClosedXML is EPPlus. For most of my project I have used ClosedXML, but I had to switch to EPPlus because it has support for charts.

For ASP.NET Core, you can use EPPlus.Core. I have performed a quick test within an ASP.NET Core 2.0 console app and it seems to work fine:

```<code>var newFile = new FileInfo("some file.xlsx");
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
   var ws = xlPackage.Workbook.Worksheets.Add("etc");
   ws.Cells[1, 1].Value = "test";

   // do work here
   xlPackage.Save();
}
</code>```

Body:
As indicated by andrews, it is recommended to use a third-party library, especially when working with formatting. An alternative to ClosedXML is EPPlus. For most of my project I have used ClosedXML, but I had to switch to EPPlus because it has support for charts.

For ASP.NET Core, you can use EPPlus.Core. I have performed a quick test within an ASP.NET Core 2.0 console app and it seems to work fine:

var newFile = new FileInfo("some file.xlsx");
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
   var ws = xlPackage.Workbook.Worksheets.Add("etc");
   ws.Cells[1, 1].Value = "test";

   // do work here
   xlPackage.Save();
}


问:
How to concatenate columns on top of each other in an array
Say I have the following array:

```<code>a = np.array([[1,3,5,2,3],[3,2,5,6,7],[1,7,3,6,5]]);
</code>```

How can I stack the columns on top of each other to form a single column vector to produce the following?

```<code>b =np.array([[1], [3], [1], [3], [2], [7],[5],[5],[3],[2],[6],[6],[3],[7],[5]]);
</code>```

答:
The shortest is a.T.reshape(-1,1)  :

a.T for the good layout,

reshape for the good shape, with one column.

or equivalent : a.reshape(-1,1,order='F').

Body:
Say I have the following array:

a = np.array([[1,3,5,2,3],[3,2,5,6,7],[1,7,3,6,5]]);

How can I stack the columns on top of each other to form a single column vector to produce the following?

b =np.array([[1], [3], [1], [3], [2], [7],[5],[5],[3],[2],[6],[6],[3],[7],[5]]);


问:
how to know if a $string ends with ','?

Possible Duplicate:

Find last character in a string in PHP

How can I know if the last char of a $string is ',' ?

答:
There are a few options:

```<code>if (substr($string, -1) == ',') {
</code>```

Or (slightly less readable):

```<code>if ($string[strlen($string) - 1] == ',') {
</code>```

Or (even less readable):

```<code>if (strrpos($string, ',') == strlen($string) - 1) {
</code>```

Or (even worse yet):

```<code>if (preg_match('/,$/', $string)) {
</code>```

Or (wow this is bad):

```<code>if (end(explode(',', $string)) == '') {
</code>```

The take away, is just use substr($string, -1) and be done with it.  But there are many other alternatives out there...

Title: how to know if a $string ends with ','?

Body:
There are a few options:

if (substr($string, -1) == ',') {

Or (slightly less readable):

if ($string[strlen($string) - 1] == ',') {

Or (even less readable):

if (strrpos($string, ',') == strlen($string) - 1) {

Or (even worse yet):

if (preg_match('/,$/', $string)) {

Or (wow this is bad):

if (end(explode(',', $string)) == '') {

The take away, is just use substr($string, -1) and be done with it.  But there are many other alternatives out there...


问:
How to list data from database for a backend module in typo3 extbase
I am creating an extension with backend module in typo3 7.6.12. As a first step, I need to display the records as a list in the backend module. I just added the controller name, but no idea about how to write for a backend module listing.
So how is it possible to list in backend module from database certain fields like name, etc...
Is there any simple extensions for references other than powermail?</p>

答:
First, You need to register BE modules in your ext_tables.php file like below.

```<code>if (TYPO3_MODE === 'BE') {
    \TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerModule(
        'Vendor' . $_EXTKEY,
        'web',          // Main area
        'mod1',         // Name of the module
        '',             // Position of the module
        array(          // Allowed controller action combinations
            'Controller' => 'action, update, edit'
        ),
        array(          // Additional configuration
            'access'    => 'user,group',
            'icon'      => 'EXT:blog_example/ext_icon.gif',
            'labels'    => 'LLL:EXT:' . $_EXTKEY . '/Resources/Private/Language/locallang_mod.xml',
        )
    );
}
</code>```

After Register BE Modules. You need to create Template folder for listing records and For use this template folder you need to add below typoscript in setup.txt file.

```<code>module.tx_blogexample {
    settings < plugin.tx_blogexample.settings
    persistence < plugin.tx_blogexample.persistence
    view < plugin.tx_blogexample.view
    view {
        templateRootPath = EXT:blog_example/Resources/Private/Backend/Templates/
        partialRootPath = EXT:blog_example/Resources/Private/Backend/Partials/
        layoutRootPath = EXT:blog_example/Resources/Private/Backend/Layouts/
    }
}
</code>```

Body:
First, You need to register BE modules in your ext_tables.php file like below.

if (TYPO3_MODE === 'BE') {
    \TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerModule(
        'Vendor' . $_EXTKEY,
        'web',          // Main area
        'mod1',         // Name of the module
        '',             // Position of the module
        array(          // Allowed controller action combinations
            'Controller' => 'action, update, edit'
        ),
        array(          // Additional configuration
            'access'    => 'user,group',
            'icon'      => 'EXT:blog_example/ext_icon.gif',
            'labels'    => 'LLL:EXT:' . $_EXTKEY . '/Resources/Private/Language/locallang_mod.xml',
        )
    );
}

After Register BE Modules. You need to create Template folder for listing records and For use this template folder you need to add below typoscript in setup.txt file.

module.tx_blogexample {
    settings < plugin.tx_blogexample.settings
    persistence < plugin.tx_blogexample.persistence
    view < plugin.tx_blogexample.view
    view {
        templateRootPath = EXT:blog_example/Resources/Private/Backend/Templates/
        partialRootPath = EXT:blog_example/Resources/Private/Backend/Partials/
        layoutRootPath = EXT:blog_example/Resources/Private/Backend/Layouts/
    }
}


问:
main: src/unix/core.c:117: uv_close: Assertion `!uv__is_closing(handle)' failed
When I try to use the function uv_close((uv_handle_t*)client,NULL) in libuv library to actively close the TCP connection with the client, the error

"main: src/unix/core.c:117: uv_close: Assertion `!uv__is_closing(handle)' failed."

was reported. I search a lot online, but I still cannot find the correct way to solve the problem. I wish someone can tell me why this problem resulted and how to solve it.

答:
You are trying to close a handle that is either already closed or in a closing state (that is, somewhere along the process that brings the handle from being alive to being closed).

As you can see from the code of libuv, the uv_close function starts as:

```<code>void uv_close(uv_handle_t* handle, uv_close_cb close_cb) {
  assert(!uv__is_closing(handle));

  handle->flags |= UV_CLOSING;

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

Where uv__is_closing is defined as:

```<code>#define uv__is_closing(h)                                                     \
  (((h)->flags & (UV_CLOSING |  UV_CLOSED)) != 0)
</code>```

To sum up, as soon as uv_close is invoked on a handle, the UV_CLOSING flag is set and it's checked on subsequent calls to avoid multiple runs of the close function. In other terms, you can close a handle only once.

The error comes out because you are probably invoking uv_close more than once for a handle. However, it's hard to say without looking at the real code.

As a side note, you can use uv_is_closing to test your handle if you are in doubt. It's a kind of alias for uv__is_closing.

Body:
You are trying to close a handle that is either already closed or in a closing state (that is, somewhere along the process that brings the handle from being alive to being closed).

As you can see from the code of libuv, the uv_close function starts as:

void uv_close(uv_handle_t* handle, uv_close_cb close_cb) {
  assert(!uv__is_closing(handle));

  handle->flags |= UV_CLOSING;

  // ...

Where uv__is_closing is defined as:

#define uv__is_closing(h)                                                     \
  (((h)->flags & (UV_CLOSING |  UV_CLOSED)) != 0)

To sum up, as soon as uv_close is invoked on a handle, the UV_CLOSING flag is set and it's checked on subsequent calls to avoid multiple runs of the close function. In other terms, you can close a handle only once.

The error comes out because you are probably invoking uv_close more than once for a handle. However, it's hard to say without looking at the real code.

As a side note, you can use uv_is_closing to test your handle if you are in doubt. It's a kind of alias for uv__is_closing.