text:
Q: Why Bootstrapping standard errors and 95% confidence intervals change each time I re-conducted the analysis I was using respondent-driven sampling analysis tool (RDSAT) to get bootstrapping confidence intervals. But each time I re-did the analysis, I noticed the bootstrapping standard errors and confidence intervals changed a little bit.
Is this normal for bootstrapping confidence intervals? Thank you!

A: This is totally normal and why we set a random seed (to get the same randomization each time) via set seed in R or np.random.seed in Python.
The way bootstrap works is to take many random samples, with replacement, of your data, so there should be small fluctuations in your calculated values as those random samples vary.

A: Bootstrapping involves resampling your data randomly. Thus, each time you bootstrap, a different (re)sample will be drawn. Therefore, the results of different bootstrap runs will be different.
If these differences are large, then you should be suspicious that your bootstrap may not be working well. If the differences are trivial, they are no problem.
You may want to set the seed value of your random number generator in order to make your bootstrap exactly replicable.


text:
Q: How to fix responsive problem in Bootstrap 4 I am using Bootstrap 4 and I have the following jumbotron class:

.rounded-circle{
    vertical-align: left;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    position: absolute;
    left: -150px;
    top: -50px;
  }
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    this is mobile way of the container and other line

With this syntax, my desktop view is displaying as well following,
https://i.stack.imgur.com/mUrAe.png
but in my mobile view, it is not displaying in correct position as following https://i.stack.imgur.com/SaRuW.png
then how could I view my image and descriptions on all devices (desktop, tab and phone) as well, I need in the small device top image and then description under the image.
edited image

A: It's wrong here to use position: absolute with col, flex-box gives you the utility to make the behavior you are trying to reach without position: absolute,
First add the class align-items-center beside class row (this will align center vertically)
Second add the class col-12 to the columns (make the description below the image for smaller size)
Then optionally, you can add the classes text-center and text-md-left (on bigger sizes it will align left and on smaller it will be center)

.rounded-circle{
    width: 100px;
    height: 100px;
    border-radius: 50%;
  }
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    this is mobile way of the container and other line

redpajama_set_name: RedPajamaStackExchange


text:
Q: Call to a member function setCookie() on null on laravel middleware I made a custom route middleware to check if my user has enough privileges to see a page, when user doesn't have enough privileges I get the following error message:
 Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Call to a member function setCookie() on null

This is my controller:
<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Auth;

class AuthAdmin
{

    public function handle($request, Closure $next)
    {
        $user = Auth::user();

        if($user && $user['privileges'] > 2){
            return $next($request);
        }

        return view('auth.login');

    }
}

Any idea what's wrong with my code?

A: try
return response()->view('auth.login');

A: Instead of return view('Somepage') try return redirect('some route')


text:
Q: Diff multiple versions of a project I've recently started a new job where I have taken over developing an existing system. The system (PHP site if it matters) was setup with three instances.

*

*Live site (Used by staff and customers)

*Test site (Mainly used to demonstrate feature requests to staff)

*Dev site (Used by the previous developer)

This seemed like a reasonable thing to do (They didn't have a SVN server setup). But now that I'm a couple weeks in, I've noticed that the code (and database schemas) is different across all three sites. I expected there to be differences between dev and live, but live has features that dev doesn't.
I've run CLOC and I am looking at around 180 modified files and 110 new files between the different versions. Is there any software or easier method to compare the code across all the versions than just performing diffs file by file?

A: meld is excellent for comparing entire folders (and files) recursively in a drill-down style.

A: Blatant plug: If you're interested in diffing all three sites against each other (as opposed to diffing them two at a time), you might be interested in my difdef utility. It can produce a merge of N directories à la diff -r -D but unlike traditional diff it works for N>2 as well as N=2. (And unlike diff3 it does not assume any specific genealogical relationship among the versions.)
E.g. you could do
difdef -r -DSITE={LIVE,TEST,DEV} {live,test,dev} -o merged
grep -lr 'SITE==' merged | xargs $EDITOR

to open up an editor window on every file that differs between any two versions.
difdef does not have a better UI than the traditional diff utility, but it does have this nifty ability to diff more than 2 versions simultaneously. Open-source, C++, MIT license.


text:
Q: I want to put my jar file in html code How can I put my jar file into my html?
I tried to use that:
<html>
    <head>
    </head>
    <body>
        <applet code=Tictactoe.class archive="Test.jar">
        </applet>
    </body>
</html>

My problem is that when Im trying to run my html code java is blocking my jar file.

A: Try to add your url (local or distant server url) in exception list on java settings panel.


text:
Q: Convert unicode symbol to unicode entity I have been searching SO for a suitable solution on how to convert a Unicode symbol (ἔ) to it corresponding Unicode entity (ἔ). I have a text file which contains lot of such symbols like ῶἤÜὰὔ. I am looking for a python or even Perl script which can take the file as an argument and process each symbols and write its equivalent Unicode entity in an output file. I saw similar question here but it was dealing with html entity.

A: perl -Ci -0777 -E 'print map {sprintf "&#x%04x;", ord $_} split(//,<>)' foo.txt

A: Python 3.3+:
#coding: utf8
import re
s = 'abcῶἤÜὰὔdef'
s = re.sub(r'[\x80-\U0010FFFF]', lambda x: '&#x{:04X};'.format(ord(x.group(0))), s)
print(s)

*

*re.sub uses a regular expression and a replacement function.

*r'[\x80-\U0010FFFF]' matches a single non-ASCII Unicode character.

*lambda x: '&x{:04X};'.format(ord(x.group(0))) is an anonymous function that receives the regular expression match.  x is the match object.  x.group(0) is the substring that matched.  ord gives the Unicode ordinal number of the character, and format generates the required html entity string as the replacement.  The lambda expression is equivalent to the function:

    def replacement(matchobj):
        substring = matchobj.group(0)
        unicode_value = ord(substring)
        return '&x{:04X};'.format(unicode_value)

Output:
abcῶἤÜὰὔdef


text:
Q: Parsing shopping websites usign jsoup I have the following code:
doc = Jsoup.connect("http://www.amazon.com/gp/goldbox").userAgent("Mozilla").timeout(5000).get();

  Elements hrefs = doc.select("div.a-row.layer");
  System.out.println("Results:"+ hrefs); //I am trying to print out contents but not able to see the output.

Problem: Want to display all image src within the div with class name "a-row layer". But, i am unable to see the output.
What is the mistake with my query?

A: I have taken a look at the website and tested it myself. The issue seems to be that the piece of html code you want to extract (div.a-row.layer) is generated by JavaScript.
Jsoup does not support JavaScript and cannot parse those generated by it. You would need a headless web browser to deal with this, such as HTMLUnit.


text:
Q: LINQ Join with multiple AND conditions I want to join two entities in my MVC application for data Processing through the LINQ join.
For that I am trying to write the query like,
from enumeration in db.Enumerations
join cust in db.Customers on ( enumeration.Value equals cust.lkpStatus &&
enumeration.EnumerationTypeID.Contains('Cust')

But I am getting Problem with this Query, So please give me some suggestion on this.

A: Try this solution:
from enumeration in db.Enumerations.Where(e =>
                                          e.EnumerationTypeID.Contains('Cust'))
join cust in db.Customers on enumeration.Value equals cust.lkpStatus
select enumeration;

A: Join should be made like this:
var joinQuery =
from t1 in Table1
join t2 in Table2
  on new { t1.Column1, t1.Column2 } equals new { t2.Column1, t2.Column2 }
...

A: This one?
var data =     from c in db.Enumerations
               from d in db.Customers
               where c.Value.Equals(d.lkpStatus)
               && c.EnumerationTypeID.Contains('Cust')
               select c;

A: This works
var data = from c in db.Enumerations from d in db.Customers where c.Value==d.lkpStatus && c.EnumerationTypeID.Contains('Cust') select c;


text:
Q: INVALID MODE : s5a869f19a6c57_equivalents - type : sonata_type_collection - mapping : I am building a new feature onto a Symfony 2.8 application using a few Sonata bundles.
My Page.php entity definition includes the following mapping:
/**
 * @var ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Equivalent", cascade={"all"})
 * @ORM\JoinTable(name="page_equivalent",
 *          joinColumns={@ORM\JoinColumn(name="page_id", referencedColumnName="id")},
 *          inverseJoinColumns={@ORM\JoinColumn(name="equivalent_id", referencedColumnName="id", unique=true)}
 *     )
 */
private $equivalents;

... and my PageAdmin.php file's configureFormFields() function contains the following:
            ->add('synonyms', CollectionType::class, array('entry_type' => TextType::class, 'allow_add' => true, 'allow_delete' => true))
            ->add('equivalents', 'sonata_type_collection', array(
                'label' => "Equivalents",
                'cascade_validation' => true,
                'required' => false,
            ), array(
                'edit' => 'inline',
                'inline' => 'table',
                'targetEntity' => 'AppBundle\Entity\Equivalent',
                'admin_code' => 'app.admin.equivalent',
            ))

... which yields the message

INVALID MODE : s5a869f19a6c57_equivalents - type :
  sonata_type_collection - mapping :

I have tried setting by_reference to both true and false, and neither setting seemed to change anything. I have also run doctrine:schema:validate and spotted no problems. I have also verified that I am able to add and edit Equivalent objects in my CMS.
What can I do to fix this?

A: It turns out that this problem involved an ORM mapping that was not getting read.
(The piece of logic where the complaint lived was checking for one of several ORM mapping types, then complaining if none of those types was found.)
Running app/console doctrine:cache:clear-metadata and then re-running my doctrine:schema:update --force command was enough to get my application to recognize the many-to-many relationship that I had been trying to put in place. This got rid of the cranky message.


text:
Q: Cakephp save multiple data (users id) in a modal i want to save multiple users id in TempUser modal.
Problem:
Multiple users id is not saving in TempUser modal.
First Getting all users id:
$this->loadModel('User');
pr($this->User->find('all',  array('fields' => 'id')));

Getting Output in Array
Array
(
    [0] => Array
        (
            [User] => Array
                (
                    [id] => 1
                )
        )

    [1] => Array
        (
            [User] => Array
                (
                    [id] => 2
                )
        )

    [2] => Array
        (
            [User] => Array
                (
                    [id] => 3
                )
        )
)

Now i want to save these users id in TempUser modal.
//saving users id in **TempUser** modal
$this->loadModel('TempUser');
$this->TempUser->saveAll(); //What should i pass here in saveAll()

What should i do to save above data ?
Is there any inbuilt method in CAKEPHP to save this type of data ?

A: saveAll expects an associative array. An example:
$arr = array(
    array(
        'User' => array(
            'name' => 'John',
            'dob' => '1987-03-04'
        )
    ),
    array(
        'User' => array(
            'name' => 'Jane',
            'dob' => '1989-06-09'
        )
    )
);

$this->User->saveAll($arr);

A: try this
$cake = array
(
    array
        (
            'User' => array
                (
                    'id' => 1
                )
        ),

    array
        (
            'User' => array
                (
                    'id' => 2
                )
        ),

    array
        (
            'User' => array
                (
                    'id' => 3
                )
        ),
);

$tempUser = array();
foreach ($cake as $value) {
    $tempUser[]['TempUser']['id'] = $value['User']['id'];
}

$this->loadModel('TempUser'); //saving users id in **TempUser** modal
$this->TempUser->saveAll($tempUser); //What should i pass here in saveAll()


text:
Q: Tearing in my animation on WinForms C# I am using a library in which enables me to animate movement of WinForm elements (linked below), when I use it to move a transparent panel across the form (which has a picture background) there is an extraordinary amount of tearing.
I believe the fix is to get winforms to refresh at a rate of 30fps without being laggy. I tried settings a timer to do This.Refresh(); at 30 times a second but it just ended up with slow loading. So how would I achieve a nice refresh rate of the form?
The link described above is here -> http://code.google.com/p/dot-net-transitions/wiki/CodingWithTransitions#Creating_a_transition_that_works_on_a_single_property
Here is an example of the tearing. It might have something to do with the fact that the panel's backcolor is set to "transparent"
http://screencast.com/t/XIr3NkGI

A: I used this ages ago when I had trouble with controls on a form flickering, in my case there were many controls and when loading the form the controls would flicker quite badly.
In the end I used this:
    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= 0x02000000;
            return cp;
        }
    }

Paste that in your form.
It activates double buffering at the form level and for all controls within it.
HOWEVER, while it stopped my flickering issue it greatly reduced the speed at which the forms elements seemed to move as they don't get drawn until they are 100% ready.
I guess you can try and see if it suits your situation.


text:
Q: Datetime and utctimetuple() In this code mDATE0 for 3 items a, b, z is:
mUNIQUE: z | mDATE0: 2010-11-14 14:55:04.293000
mUNIQUE: b | mDATE0: 2010-11-14 14:53:34.824000
mUNIQUE: a | mDATE0: 2010-11-14 14:50:14.155000

But when I do
...
utc_tuple = rep.mDATE0.utctimetuple()
...

corresponding utc_tuples are:
utc_tuple: time.struct_time(tm_hour=14, tm_min=55)
utc_tuple: time.struct_time(tm_hour=14, tm_min=55)
utc_tuple: time.struct_time(tm_hour=14, tm_min=55)

In other words min=55 for all items while mDATE0 has
z --> min=55;
b --> min=53;
a --> min=50

What am I doing wrong? Please see my related question. Thanks.

A: That isn't code!  Please post short, complete example code to illustrate a problem.  Below is what I think you are trying to do, but without seeing your code, there is no way for anyone to point your bug.
from datetime import datetime
# build up some datetime objects.
z = datetime.strptime('2010-11-14 14:55:04.293000','%Y-%m-%d %H:%M:%S.%f')
b = datetime.strptime('2010-11-14 14:53:34.824000','%Y-%m-%d %H:%M:%S.%f')
a = datetime.strptime('2010-11-14 14:50:14.155000','%Y-%m-%d %H:%M:%S.%f')
# display them
print 'z =',z
print 'b =',b
print 'a =',a
# print the minute
print 'z min =',z.utctimetuple().tm_min
print 'b min =',b.utctimetuple().tm_min
print 'a min =',a.utctimetuple().tm_min
# print the minute an easier way
print 'z min =',z.minute
print 'b min =',b.minute
print 'a min =',a.minute

Output:
z = 2010-11-14 14:55:04.293000
b = 2010-11-14 14:53:34.824000
a = 2010-11-14 14:50:14.155000
z min = 55
b min = 53
a min = 50
z min = 55
b min = 53
a min = 50


text:
Q: an error occurred while installing therubyracer (0.12.3) and bundler cannot continue home/xxxx/Desktop/dsp-manage/vendor/bundle/ruby/2.7.0/gems/libv8-3.16.14.19/ext/libv8/location.rb:50:in `configure': By using --with-system-v8, you have chosen to use the version
(Libv8::Location::System::NotFoundError)
of V8 found on your system and not the one that is bundled with
the libv8 rubygem.
However, your system version of v8 could not be located.
Please make sure your system version of v8 that is compatible
with 3.16.14.19 installed. You may need to use the
--with-v8-dir option if it is installed in a non-standard location
from /home/xxxx/Desktop/dsp-manage/vendor/bundle/ruby/2.7.0/gems/libv8-3.16.14.19/lib/libv8.rb:7:in configure_makefile' from extconf.rb:32:in '
To see why this extension failed to compile, please check the mkmf.log which can be found here:
/home/xxxx/Desktop/dsp-manage/vendor/bundle/ruby/2.7.0/extensions/x86_64-linux/2.7.0/therubyracer-0.12.3/mkmf.log
extconf failed, exit code 1
Gem files will remain installed in /home/xxxx/Desktop/dsp-manage/vendor/bundle/ruby/2.7.0/gems/therubyracer-0.12.3 for inspection.
Results logged to /home/xxxx/Desktop/dsp-manage/vendor/bundle/ruby/2.7.0/extensions/x86_64-linux/2.7.0/therubyracer-0.12.3/gem_make.out
An error occurred while installing therubyracer (0.12.3), and Bundler cannot continue.
Make sure that gem install therubyracer -v '0.12.3' --source 'https://rubygems.org/' succeeds before bundling.
In Gemfile:
therubyracer


text:
Q: Copy an associative array in JavaScript I've the following piece of code for copying one associative array to other,
<script>

    var some_db = new Array();

    some_db["One"] = "1";

    some_db["Two"] = "2";

    some_db["Three"] = "3";

    var copy_db = new Array();

    alert(some_db["One"]);

    copy_db = some_db.slice();

    alert(copy_db["One"]);

</script>

But the second alert says "undefined".. Am I doing something wrong here? Any pointers please...

A: As @Niko says in the comment, there aren't any associative arrays in JavaScript.
You are actually setting properties on the array object, which is not a very good idea.  You would be better off using an actual object.
var some_db = {};
some_db["One"] = "1";
some_db["Two"] = "2";
some_db["Three"] = "3";

var copy_db = {}, prop;
// Loop over all the keys in the object
for (prop in some_db) {
  // Make sure the object has this value, and not its prototype
  if (some_db.hasOwnProperty(prop)) {
    copy_db[prop] = some_db[prop];
  }
}

Many libraries implement an extend function which does exactly this (copy keys from one object to another). Most notably jQuery and Underscore.js. Underscore.js also has _.clone(obj) which is effectively _.extend( {}, obj )

A: If you want to use JSON, you can take this 'associative array' object:
var assArray = {zero:0, one:1, two:2, three:3, what:'ever', you:'want'};

And 'clone' it like this:
var clonedObj = JSON.parse(JSON.stringify(assArray));

A: In JavaScript, associative arrays are called objects.
<script>
    var some_db = {
       "One" : "1",
       "Two" : "2",
       "Three" : "3"
    };

    var copy_db = clone(some_db);

    alert(some_db["One"]);

    alert(copy_db["One"]);

    function clone(obj) {
        if (null == obj || "object" != typeof obj) return obj;
        var copy = obj.constructor();
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
        }
        return copy;
    }
</script>

I would normally use var copy_db = $.extend({}, some_db); if I was using jQuery.
Fiddle Proof: http://jsfiddle.net/RNF5T/
Thanks @maja.

A: underscore.clone could help. It performs a shallow copy to the dictionary object or array.
var some_db = {
  "One" : "1",
  "Two" : "2",
  "Three" : "3"
};

copy_db = _.clone(some_db);


text:
Q: How to remove text between two specified strings (start and stop) using Python? I have a series of texts in a file.txt structured like so :
// text 1
A Title always the same for all the texts
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Maecenas mollis libero eget turpis blandit, non efficitur ipsum sodales.

A Subtitle always the same for all the texts
A text that I want to remove.

// text 2
A Title always the same for all the texts
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Maecenas mollis libero eget turpis blandit, non efficitur ipsum sodales.

A Subtitle always the same for all the texts
Another text that I want to remove.

I want to remove the text below the subtitle and above the title, ie, in my above example : "A text that I want to remove" and "Another text I want to remove". I know these texts are always between "A Subtitle always the same for all the texts" and "A Title always the same for all the texts"

A: It's easy with slicing and string.index(). The index method just returns the index where it first finds the string you're passing. So you can use it to find where your headings start and stop. Unlike the similar find() method, this will return an error if your file doesn't contain the necessary string so you'll know what's happened, while find will just return -1 and continue even though that index will be useless.
String slicing is what allows you to get a substring of a string, ie:
text = "Hello"
text[2:4]
>>> 'll'

Giving it the indices of where to start and stop will return the string between those two locations. With those combined you can get the substring like this:
text = '''Your string goes here'''
start = "A Subtitle always the sam for all the texts"
stop = "A Title always the same for all the texts"
text = text[text.index(start) : text.index(stop) + len(stop)]

(adding len(stop) makes sure the string still includes the subheading, but if you remove it the subheading will no longer be retained)

A: Using str.split:
>>> text = '''
... A Title always the same for all the texts
... Lorem ipsum dolor sit amet, consectetur adipiscing elit.
... Maecenas mollis libero eget turpis blandit, non efficitur ipsum sodales.
...
... A Subtitle always the same for all the texts
... A text that I want to remove.
... '''
>>> start = 'A Subtitle always the same for all the texts'
>>> stop = 'A Title always the same for all the texts'
>>> text.split(start, 1)[1].split(stop, 1)[0]
'\nA text that I want to remove.\n'


text:
Q: can anyone please tell me why this code is isn't producing the right output? Problem statement:

Check if two arrays are equal or not.Two arrays are said to be equal if both of them contain same set of elements, arrangements (or permutation) of elements may be different though.
This is the snippet of my code
#include <iostream>
#include<algorithm>
using namespace std;
int main() {
    int t; cin>>t;
    while(t--)
    {
        int n,i;
        cin>>n;
        int arr1[n],arr2[n];
        for(i=0;i<n;i++)
        cin>>arr1[i];
        for(i=0;i<n;i++)
        cin>>arr2[i];
        sort(arr1,arr1+n);
        sort(arr2,arr2+n);
        for(i=0;i<n;i++)
        {
            if(arr1[i]!=arr2[i])
             break;
            i++;
        }
        if(i==n) cout<<"1\n";
        else cout<<"0\n";
    }

    return 0;
}

For Input:
2      [ number of test cases ]

5      [ size of the array for test case #1 ]

1 2 5 4 0    [ array 1 ]

2 4 5 0 1   [ array 2 ]

3            [ size of the array for test case #1 ]

1 2 5         [ array 1 ]

2 4 15       [ array 2 ]

Expected Output

1

0

My code's output

0

0

A: You donot have to increment i++ again inside for loop.
 for(i=0;i<n;i++) //As,i already gets incremented here
        {
            if(arr1[i]!=arr2[i])
             break;
          // i++;
        }


text:
Q: Split string at character in JavaScript I have three links :
"http//example.com/product/iphone?source=ac"
"http//example.com/product/samsung?source=tz"
"http//example.com/product/sony?source=sn"

I want to split the string to get two variables like so:
var link1 = 'http//example.com/product/iphone';
var link2 = '?source=ac'

// The others are similar
//var link1 = 'http//example.com/product/samsung';
//var link2 = '?source=tz'
//var link1 = 'http//example.com/product/sony';
//var link2 = '?source=sn'

Please give me your opinion, and help me in this case, I'm really new to javascript. It was difficult. Thank you everyone

A: lnk = "http//example.com/product/iphone?source=ac"

let n = lnk.indexOf("?")

host = lnk.slice(0,n)
source = lnk.slice(n,)

console.log(`host = ${host}`)
console.log(`source = ${source}` )

gives me the output
host = http//example.com/product/iphone
source = ?source=ac

should work with all links as ? is a common factor
or are you looking for regex solution?

A: Here is a regex based approach using match:

var urls = ["http://example.com/product/iphone?source=ac", "https://example.com/product/iphone"];
for (var i=0; i < urls.length; ++i) {
    var parts = urls[i].match(/https?:\/\/[^?]+|\?.*/g);
    console.log(urls[i] + "\nurl => " + parts[0] + ", query => " + parts[1]);
}

A: Consider using URL API to handle URLs properly:

const path = "http://example.com/product/iphone?source=ac";

const { origin, pathname, search, hash } = new URL(path);

const link1 = origin + pathname;
const link2 = search + hash;

console.log(link1);
console.log(link2);

A: I think you want to get the url and query?
let links = [
  "http//example.com/product/iphone?source=ac",
  "http//example.com/product/samsung?source=tz",
  "http//example.com/product/sony?source=sn"
]
links.forEach((x) => {
  let [ url, query ] = x.split("?")
  console.log(url, "?" + query)
})

// http//example.com/product/iphone ?source=ac
// http//example.com/product/samsung ?source=tz
// http//example.com/product/sony ?source=sn


text:
Q: Hi, I have problem with the property (title) and the bracket of (bluilder)... I'm just fetch data from API class _Requests_TabState extends State<Requests_Tab> {
  Future<Product> productdata = getPostById();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true,
      body: Center(
        child: FutureBuilder(
          future: productdata,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Text(snapshot.data.title);
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}");
            }
            CircularProgressIndicator();
          },
        ),
      ),

A: return Text(snapshot.data[title].toString());


text:
Q: Use sinon stub for request constructor I have implement node js code to call HTTP API's using request module.
For get, post, put, delete, I have directly called request() of require module,
var sendRequest = function(req, callback) {
    request(req, function(err, res) {
        if (err) {
            callback(err, null, res);
        } else {
            callback(null, res);
        }
    }
}

I want to invoke sendRequest() but mock the response of request().
Any pointers for this.

A: One way to get it stubbed without anything but sinon, is to stub the inner class of Request, which conveniently offers its prototype, like this
stub = sinon.stub(request.Request.prototype, "init");
stub.callsFake( options => options.callback(null, {statusCode: 200}, "faked response"));

Where options in the callsFake are processed by the request function and the passed into the Request.prototype.init.
Now your callback parameters, are the ones expected in your var sendRequest = function(req, callback) {...} function

A: One of the many options is to use proxyquire to stub the request module:
var proxyquire = require('proxyquire')
  , assert = require('assert')
  , requestStub = function (req, callback) { callback(req); };

// assuming you export the sendRequest from that file
var sendRequest = proxyquire('./sendRequest', { 'request': pathStub });

describe('sendRequest', function() {
    it('request', function (done) {
        var someReq = {a: 'b'};
        sendRequest(someReq, function (req) {
            assert.equal(someReq, req);
            done();
        });
    });
});


text:
Q: react sort list mobile view I am fairly new to learning react and coding. At the moment I am working on a documentation site with docusaurus. I have created a list of content that I am rendering with a loop (.map). The content is displayed alternately (content, image, image, content) in the desktop view, which is how it should be. In the mobile view I always want text, image, text, image. I assume that I have to recreate the sorting for the mobile view. At the moment I have no idea how to do that. Thanks for your help.
Here are some screeshots:
Desktop view
Mobile view --> Text needs to be above picture
Here is what I did so far:

import React from 'react';
import clsx from 'clsx';
import styles from './HomepageFeatures.module.css';

const FeatureDetailList = [
  {
    title: 'Feature 1',
    description: (
      <>

          Awsome title

        Feature content 1 </>
    ),
  },
  {
    title: '',
    description: (

    ),
  },
  {
    title: '',
    description: (

    ),
  },
  {
    title: 'Feature 2',
    description: (
      <>

        Awsome title 2

        Feature content 2  </>
    ),
  },
];

function ListFeatures({ title, description }) {
  return (

{title}

{description}

  );
}

export default function DetailFeatures() {
  return (

          {FeatureDetailList.map((props, idx) => (
            <ListFeatures key={idx} {...props} />
          ))}

  );
}

A: Nice work, what you have until now is the desktop view working, right?
you want update the view for mobile just using CSS. That means make it responsive.
You could use MediaQueries in your styles file to override your css classes when is viewport max-width < 600px or something like that..
check https://www.w3schools.com/css/css_rwd_mediaqueries.asp


text:
Q: php code not executing after calling a javascript alert I'm having some troubles getting a php redirect to execute after a javascript alert is called. The code is below:
echo '<script>window.alert("This device is aleady registered to another user");</script>';
header('Location: page.php');

After clicking "OK" on the alert, the redirect does not execute. Any thoughts as to how I can get this code working?
Thanks

A: You can't send headers after your output. Just redirect the user thru javascript all the way instead.
echo '<script>window.location.href = "page.php";</script>';

A: You can't output anything before calling header, not even a single space. You can use header before outputting the script like in the code below
header('Location: page.php');
echo '<script>window.alert("This device is aleady registered to another user");</script>';

Hope this helps you

A: This is the best you can do use :-
window.location
http://www.w3schools.com/js/js_window_location.asp

A: try this way
echo '<script>window.alert("This device is aleady registered to another user");
window.location.href = "page.php";
</script>';


text:
Q: Wildfly and Jackson: LinkageError I'm trying to configure jboss wildfly 8 to use Jackson for JSON. So I added
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jackson-provider</artifactId>
    <version>3.0.6.Final</version>
    <type>jar</type>
</dependency>

to my ear project. But on deploying I get following error:

Caused by: java.lang.LinkageError: loader constraint violation: when
  resolving overridden method
  "org.jboss.resteasy.plugins.providers.jackson.ResteasyJacksonProvider$Proxy$_$$WeldClientProxy.disable(Lorg/codehaus/jackson/map/Des
  erializationConfig$Feature;Z)Lorg/codehaus/jackson/jaxrs/JacksonJsonProvider;"
  the class loader (instance of org/jboss/modules/ModuleClassLoader) of
  the current class,
  org/jboss/resteasy/plugins/providers/jackson/ResteasyJacksonPr
  ovider$Proxy$$$WeldClientProxy, and its superclass loader (instance
  of org/jboss/modules/ModuleClassLoader), have different Class objects
  for the type
  sy.plugins.providers.jackson.ResteasyJacksonProvider$Proxy$$$_WeldClientProx
  y.disable(Lorg/codehaus/jackson/map/DeserializationConfig$Feature;Z)Lorg/codehaus/jackson/jaxrs/JacksonJsonProvider;
  used in the signature

Is version 3.0.6 not compatible with Wildfly? how do I know which version works? I also tried with 2.3.7 and 1.1 but always the same error.
EDIT:
I have a ejb module with pojos. Here I have the dependency:
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.2.3</version>
        <scope>provided</scope>
        <type>jar</type>
    </dependency>

so that looks very much like jackson 2 to me.
and in my ear, I have following dependency:
<dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson-provider</artifactId>
        <version>3.0.6.Final</version>
        <type>jar</type>
        <scope>provided</scope>
</dependency>

do I need resteasy-jackson2-provider now? Do I need the jboss-deployment-structure.xml now?

A: WildFly 8 already includes Jackson. Mark the dependency with <scope>provided</scope>. You then need to add a jboss-deployment-structure.xml to your deployment with the following per the documentation.
<jboss-deployment-structure>
    <deployment>
        <exclusions>
           <module name="org.jboss.resteasy.resteasy-jackson-provider"/>
        </exclusions>
        <dependencies>
            <module name="org.jboss.resteasy.resteasy-jackson2-provider" services="import"/>
        </dependencies>
    </deployment>
</jboss-deployment-structure>

A: It worked for me when I imported <module name = "com.fasterxml.jackson.jaxrs.jackson-jaxrs-json-provider" />, because <module name = "org.jboss.resteasy.resteasy-jackson2-provider" services = "Import" /> does not export it
<jboss-deployment-structure>
      <sub-deployment name="erp-integrator.jar">
        <exclusions>
           <module name="org.jboss.resteasy.resteasy-jackson-provider"/>
        </exclusions>
        <dependencies>
            <module name="org.jboss.resteasy.resteasy-jackson2-provider" services="import" />
            <module name="com.fasterxml.jackson.jaxrs.jackson-jaxrs-json-provider" />
        </dependencies>
    </sub-deployment>
</jboss-deployment-structure>


text:
Q: How can I make functions available to ClojureScript's eval? In this blog post by Dmitri Sotnikov a function eval-str is provided for running a string containing ClojureScript:
(defn eval-str [s]
  (eval (empty-state)
        (read-string s)
        {:eval       js-eval
         :source-map true
         :context    :expr}
        (fn [result] result)))

If I have some function x that I want to be able to call from inside the eval string, how can I do that?

A: There are two parts to the answer, assuming x is a var associated with a ClojureScript function:

*

*The compiler analysis metadata for x needs to be present in the state passed as the first argument to cljs.js/eval. This is so that, during compilation, things like the arity of x is known, for example.

*The JavaScript implementation of the function associated with x needs to be present in the JavaScript runtime. (This is especially true if the function is actually called during the cljs.js/eval call, and not just referenced.)

If x is a core function (say the var #'cljs.core/map for example), then both of these conditions is automatically satisfied. In particular, the metadata will be produced when cljs.js/empty-state is called (assuming :dump-core is true), and the implementation of the core functions will have already been loaded into the JavaScript runtime.
But, let's say x is a wholly new function that you wish to have compiled in the self-hosted environment. The "trick" is to set up and reuse compiler state: For example put the result of (cljs.js.empty-state) into a var, and pass it to every cljs.js/eval call. If you do that, and one of the cljs.js/eval calls involves compiling a defn for x, then the compiler state will be modified (it is actually an atom), with the result being that the compiler metadata for x will be put in the state, along with, of course, the JavaScript implementation for x being set within the JavaScript environment (by virtue of evaluating the JavaScript produced for the defn).
If, on the other hand, x is a function that is part of your "ambient" ClojureScript environment (say, pre-compiled via the JVM ClojureScript compiler, but nevertheless available in the JavaScript runtime), then it will be up to you to somehow to arrange to get the compiler analysis metadata for x into the state passed to cljs.js/eval. If you look at the output of the JVM-based compiler, you will see <ns-name>.cache.json files containing such metadata. Take a look at the data that is in these files and you can ascertain its structure; with that you can see how to swap the needed information into the compiler state under [:cljs.analyzer/namespaces <ns-name>]. The cljs.js/load-analysis-cache! function exists as a helper for this use case, and a self-contained example is at https://stackoverflow.com/a/51575204/4284484


text:
Q: Woocommerce variations with select2 conflict with default selection I have noticed that once I've added select2 to variations in Woocommerce and default variations are set (lets say width and height of a product).
Then it is impossible to select default option from the select menu, once you select other option and come back to default. It is grayed out.
Looks like there is an error with aria-selected="true" being selected twice (default option has it and it is not removed once new option is selected).
I am initiating select2 with basic setup.

jQuery(".woocommerce-ordering select, .variations select, .wcpa_row select").select2({
    width: '100%',
        minimumResultsForSearch: -1
    }
);

Any idea how to fix it ?


text:
Q: How useful is dependency injection? I am new to Dependency Injection, using C#, so please forgive me for my lame question. I wanted to post this question anyway before investing time and buying expensive books on this subject.
After going through a few online documents, it appears that using dependency containers along with configuration files one can use this to swith from one type of implementation to another. However this could be easily done by an if/else statement and some config settings.
What is the advantage of using such a cumbersome implementation just to change from one class to another? I see abstract and factory patterns to be much more useful. Maybe I am wrong.

A: In short, dependency injection is used to be able to losely couple classes. By using an if else statement you introduce a dependency between classes. When adding à new implementation to your if else statement you need to add another else statement.
You've probably read http://en.m.wikipedia.org/wiki/Dependency_injection since they have a pretty good motivation section.
Perhaps complete your q with different code examples.

A: I ha s a real worl case where i needed dependency injection :
2 assembly : 1 responsible for computing a price when you do a search (lets call it Search), and the second responsible for computing a booking price with all the options (let's call it Booking).
The Booking assembly is already referencing Search(because it needs to know the initial price for computing the full price).
But here is the requirement : we need the price from Search to include all mandatories options  (yes in the tourism industry you have mandatories options) like "full room cleaning".
So I couldn't had a ref to Booking in Search (because of circular reference). So I decided use dependency injection.
My Search assembly defined an interface
public interface IAddMandatoryOptionService{
  void ChangeResultsWithMandatoryOptions(SearchResult[] results);
}

And then my Booking Assembly could implement this interface.
public class AddMandatoryOptionService : IAddMandatoryOptionService{
  public void ChangeResultsWithMandatoryOptions(SearchResult[] results){
  ...
  }
}

My SearchService class now would look like
public class SearchService{
  public SearchService(IAddMandatoryOptionService optionService){
    this.OptionService = optionService;
  }
  public SearchResult[] Search(Filter filter){
    ...
    this.OptionService.ChangeResultsWithMandatoryOptions(results);
    ...
    return results;
  }
}

So my Search Service has no dependency to the AddMandatoryOptionService class (and the Booking assembly), but it's using its functionality.The good IAddMandatoryOptionService  will be injected when I create my service (in my Application_Start or with a DI Framework)
The advantages are :

*

*Resolving the circular reference problem.

*If I want to unit test my SearchService I'll juste have to mock/fake IAddMandatoryOptionService.

Here the need for injection was more technical than logical, but I think this kind of real world scenario could help you to get the point.


text:
Q: Why does decomposing homography matrix need camera intrinsics? Both opencv and matlab have the function decomposeHomographyMatrix. This requires the homography matrix, H, and the camera intrinsic, K. I dont understand why it needs K?
Each of these function implementations reference "Malis" (https://hal.archives-ouvertes.fr/inria-00174036/document). On page 7 it talks about the intrinsic matrix K but then never uses it. It doesn't seem like it is necessary?

A: Here is how I understand the document you linked ("Deeper understanding of the homography decomposition for vision-based control"). If I am wrong, please correct me.
DecomposeHomographyMat needs K to compute euclidean homography H from projective homography G.
H = K_inv * G * K (Formula2)
R, t and n will be computed from euclidean homography matrix (Formula 3).
Opencv function decomposeHomographyMat assumes to get a projective homography matrix as an input (not euclidean)!
Notice that in the document you linked, the projective homography matrix is called G (not H!), while an euclidean homography matrix is called H.
Projective homography matrix is computed based on the vectors p - image coordinates of the points. (pixels)
alfa_p * p_c = G * p_star
Euclidean homography matrix is computed based on the vectors m "normalized projective coordinates of the points viewed from the camera pose" (e.g. meters).
alfa_m * m_c = H * m_star
Where: -c - current frame; _d - desired frame;  alfa - just scale factors
The relationship between image and projective coordinates is:
m = K_inv * p
K - matrix of the camera intrinsic parameters; K_inv - inverse of the matrix K
To be even more clear:
p_c = G * p_star
-> K * K_inv * p_c = G * K * K_inv * p_star
->  K * m_c = G * K * m_star
-> m_c = K_inv * G * K * m_star
-> m_c = H * m_star
Remember that:
K_inv * K = I - identity matrix

A: Well, you must know K in order to find R,T. Formula (1) in your reference shows this clearly (the homography G is given in your case and you are looking for the camera pose R,T). There is no way to solve for R,T without knowing K.
Whether K is used later depends on what you are going to do with the pose. If you are going to project 3D landmarks to images, you must know K for that too.
Not sure if I am telling you anything new...


text:
Q: Rails: Jquery issue with connecting to voting I just successfully created a voting system and I would like to make one button do both the voting up and down instead of two buttons. I am trying to work my way around the js file for this but I still see two buttons, any suggestions? Thank you.
Micropost Controller
class MicropostsController < ApplicationController
  def vote_up
    @micropost = Micropost.find(params[:id])
    current_user.vote_exclusively_for(@micropost)
    respond_to do |format|
      format.html { redirect_to :back }
      format.js
      end
  end

   def unvote
    @micropost = Micropost.find(params[:id])
    current_user.vote_exclusively_against(@micropost)
    respond_to do |format|
      format.html { redirect_to :back }
      format.js
      end
  end
end

JS Files
*vote_up.js*
$("#<%=micropost.id%>").html('<%= "#{micropost.votes_for}" %>');
$(".<%=micropost.id%>").html('<a href="/microposts/<%= micropost.id%>/unvote" data-remote="true" class="SquekCounterButton b2 <%= micropost.id%>"><span class="SquekCounterIcon <%= micropost.id%>">');

unvote.js
$("#<%=micropost.id%>").html('<%= "#{micropost.votes_for}" %>');
$(".<%=micropost.id%>").html('<a href="/microposts/<%= micropost.id%>/vote_up" data-remote="true" class="CounterButton b2 <%= micropost.id%>"><span class="CounterIcon <%= micropost.id%>">');

Micropost HTML

<span id='<%= micropost.id%>'><%=micropost.votes_for %>
<div class='<%=micropost.id %>'>
<a href="/microposts/<%=micropost.id %>/vote_up" data-remote='true' class='CounterButton b2'>

<div class='<%=micropost.id %>'>
<a href="/microposts/<%=micropost.id %>/unvote" data-remote='true'class='CounterButton b2'>

A: A different approach:
Create only one action, "toggle_vote" instead "vote_up", "vote_down". First call to "toggle_vote" will "vote_up", second call "vote_down", etc..
"vote_toggle.js.erb" should update button status depending on vote status.


text:
Q: C# webbrowser control - I want to use / link a specific font I'm writing a simple textviewer for the famous .nfo files.
For easy layout stuff I'm using the webbrowser control to display the nfo file.
I have font - nonstandard ofcourse - that I'd like to use.
What's the best way to include / link the font in my application ?
Do I have to include it in my application-folder and register it, or is there a way to use a font in my control that's not standard installed ?

A: The fonts are not part of the web control. The fonts come from the HTML of the web page that you're viewing with the web control.
So, the first step is to make a sample HTML page that displays correctly in a browser (with the fonts you want), then you can load that page into the webcontrol later.
To load fonts in the html page, see: How to embed fonts in HTML?
Once you have that, then the second step is to simply generate the HTML page text dynamically (with the font code in it and your NFO) and then stick that into the WebBrowser control.


text:
Q: TRANSF0ORMAR LISTS EM DICTS UTILIZANDO LIST COMPREHENSIONS A partir da lista: linguagens = ['python', 'javascript', 'java', 'php', 'c', 'julia'], utilize Dict Comprehension para construir o dicionário abaixo.
DICA: Observe que o valor associado a cada chave corresponde ao tamanho de cada string.
{'python': 6, 'javascript': 10, 'java': 4, 'php': 3, 'c': 1, 'julia': 5}
Consegui fazer de forma 'comum', porém não consegui utilizando a técnica pedida no exercício.
linguagens = ['python', 'javascript', 'java', 'php', 'c', 'julia']
lista_valor = []
for i in range(len(linguagens)):
    lista_valor.append(len(linguagens[i]))
dicionario = dict(zip(linguagens, lista_valor))
print(dicionario)

A: Para solucionar este problema recomdo você a ler este artigo sobre dicionários do python:
https://pythonacademy.com.br/blog/dict-comprehensions-no-python
Solução para o problema:
linguagens = ['python', 'javascript', 'java', 'php', 'c', 'julia']
dicionario = {l: len(l) for l in linguagens}
print(dicionario)


text:
Q: PowerShell get-childitem refusal to exclude directory I am trying to simply search for files in a network share, but exclude a useless directory. I know there is the -exclude option for get-childitem.
However, when I try to run the command  get-childitem -recurse -exclude \\share\folder\excludeddir, PowerShell ignores the -exclude parameter. Any and all permutations of the exclusion path have been attempted.
Why is powershell ignoring the -exclude parameter? Is there any way to simply exclude a directory without having to write multiple lines of code? And no, the method of piping to | ? { $_.FullName -inotmatch 'excludeddir' } is not usable, as it is completely ignored by powershell if it is used within a network share.

A: You can do the following if you want to exclude all files within a folder called Desktop.
Get-ChildItem -Recurse -File | Where {
    $_.Directory.Name -ne 'Desktop'
    } | Select-String -Pattern 'mystring'

Explanation:
The problem with -Exclude is that it only applies to the leaf item of the current item's path. The online documentation falls short in explaining how -Exclude works and the idiosyncrasies of it. So if you exclude Desktop, any file named Desktop or any folder path that ends with a folder named Desktop would be excluded. It however, does not exclude any subfolders or subfiles of an excluded directory when -Recurse is used. I do not know if that is by design or an oversight.
If you are only searching for files, the -File parameter only returns files. Since FileInfo objects have a Directory property, which is a DirectoryInfo object, you can reference its Name property to determine the parent directory name of a returned file.


text:
Q: What does flatten mean? I tried to understand the definition of Some::flatten and got into trouble. Here is how it looks:
def flatten[B](implicit ev: A <:< Option[B]): Option[B] =
  if (isEmpty) None else ev(this.get)

I didn't understand the mean of A <:< Option[B]. What does <:< mean?

A: That is a generalized type constraint and it makes sure that the type you are flattening is of the form Option[Option[T]] (or List[List[T]]). What it does it removes one layer of Option or List. So Some(Some(3)) becomes Some(3), Some(None) becomes None, and None becomes None. For lists: List(List(1,2), List(3)) becomes List(1, 2, 3).
There is a very good article that describes the use of generalized type constraints in the standard library, found here.
Edit: as @mavarazy noted, it also can flatten Seq[Option[T]] to Seq[T]. Generalized type constraints are a very powerful device that I consider one of the advanced features of the Scala type system.

A: A <: B in general means that A is a subtype of B.
A <:< B in turn is something that provides an evidence of this subtype relationship, which essentially means that there is a way to turn an A into a B.
The function flatten is a member of the Option[+A] class, and it requires an
implicit ev: A <:< Option[B]
that is, some evidence that your type A can be turned into an Option[B]. Starting out from an Option[A] given this evidence, it can be turned into an Option[Option[B]], which can then be smashed into a single Option[B], as the other answers explain it.

A: Flatten if you put it easy means - unwrap (simplify) input
In case of Option, it means if you have nullable of nullable, simplify to single level of nullable
Some(Some("a")).flatten = Some("a")

In case of Seq of Options, it means remove all nullables
Seq(Some("a"), None, Some("b")).flatten = Seq("a", "b")

In case of Seq of Seq, it means remove Seq level
Seq(Seq("a"), Seq(), Seq("b", "c")).flatten = Seq("a", "b", "c")


text:
Q: Error "syntax error near unexpected token '('" in Bash script when selecting files Running this script, bash ./cleanup.bash,
#!/bin/bash
## Going to directory-moving stuff
rm -rf !(composer.json|.git)

Gives the error:

cleanup.bash: line 10: syntax error near unexpected token '('
cleanup.bash: line 10: 'rm -rf !(composer.json|.git)'

But if I run in in the terminal directly, there aren't any problems:
rm -rf !(composer.json|.git)

I tried stripping out all other lines, but I still get the error.
How do I enter this correctly in the Bash script?
I'm on Ubuntu, and this was all done locally, not on a remote.

A: I guess your problem is due to the shell extended glob option not set when run from the script. When you claim it works in the command line, you have somehow set the extglob flag which allow to !() globs.
Since the Bash script, whenever started with a #!/bin/bash, starts a new sub-shell, the extended options set in the parent shell may not be reflected in the new shell. To make it take effect, set it in the script after the shebang:
#!/bin/bash

shopt -s extglob

## Going to directory-moving stuff
rm -rf !(composer.json|.git)


text:
Q: Javascript: I think I am attempting to use an event triggered from a form button with conditional values set from a radio button...? Well, the goal is to make the radio button true or false trigger an event that causes text corresponding to the message appear. I have failed. If you'd rather solve the problem than explain what i did wrong, that's ok too. I understand you're all busy. I'm trying very hard to learn, and if you are willing to explain what I did wrong, so I can better understand JavaScript syntax and logic, I would really appreciate it!
https://codepen.io/Slimmwillis/pen/WMRmJP

var x = 3;
var y = 2;
var z = x + y;

document.getElementById("num").innerHTML = z;

function myFunction() {
  var OnSubmit;
  var clicked = new Boolean().getvalue();
  /* I think the error is I am failing to get a value for clicked from Boolean which I believe is declared as either false or true in the form above. Help me Sensei!*/
  if (clicked == true) {
    OnSubmit = "That is correct, you know Maths";
  } else if (clicked == false) {
    OnSubmit = "Incorrect! Dummy!";
  } else {
    OnSubmit = "Please Select 1";
  }
  document.getElementById("clicker").innerHTML = OnSubmit;
}
<!DOCTYPE html>

So easy I could cry

3+2=

  <form>
    <input type="radio" name="Boolean" value="true" checked> True

    <input type="radio" name="Boolean" value="false"> False

    <input type="submit" value="Submit">

 So hard I could Cry

  </form>

A: You can use jquery API its quite simple:
<form class='myform'>
    <input type='radio' id='myRadioBox'>
</form>
$(document).ready(function(){
     $('.myform').submit(function(event){
         event.preventDefault();
         var result = document.getElementById('myRadioBox').value;
         if(result == 'checked'){
             // display true/false message
         }else{
             // display false/true message
         }
     })
});

'event.preventDefault()' is to prevent the form from submitting! you should always include it if you are checking for a condition before submitting a form, thereafter you can submit the form!
$('.myform').submit();

A: make the radio buttons have a single class the iterate the class and check for your condition along! i.e
for(var i=0; i<radioClass.length; i++){
      if(result == checked){
         // do something
      }else{
         // do something else!
      }
}
var result = document.getElementByClassName('radioClass');
// result will be an array of radio buttons;

A: *

*You need to bind the submit event to your form to call your function myFunction.

document.querySelector('form').addEventListener('submit', myFunction);

*

*To get the boolean value of clicked, execute the following selector [name="Boolean"]:checked to get the checked readiobutton:

document.querySelectorAll('[name="Boolean"]:checked').forEach(function(e) {
    clicked = e.getAttribute('value') === 'true';
});

var x = 3;
var y = 2;
var z = x + y;

document.getElementById("num").innerHTML = z;
var clicker = document.getElementById("clicker")

function myFunction(e) {
  e.preventDefault(); // remove this if you need to submit that form.
  var onSubmit,
      clicked;

  document.querySelectorAll('[name="Boolean"]:checked').forEach(function(e) {
    clicked = e.getAttribute('value') === 'true';
  });

  /* I think the error is I am failing to get a value for clicked from Boolean which I believe is declared as either false or true in the form above. Help me Sensei!*/

  if (clicked) {
    onSubmit = "That is correct, you know Maths";
  } else if (!clicked) {
    onSubmit = "Incorrect! Dummy!";
  } else {
    onSubmit = "Please Select 1";
  }

  clicker.innerHTML = onSubmit;
}

document.querySelector('form').addEventListener('submit', myFunction);
<!DOCTYPE html>

So easy I could cry

3+2=

  <form>
    <input type="radio" name="Boolean" value="true" checked> True

    <input type="radio" name="Boolean" value="false"> False

    <input type="submit" value="Submit">

 So hard I could Cry

  </form>


text:
Q: Remove Multiple Duplicate Options From Drop-down List Similar to this question here I'd like to find out how to remove duplicate options from drop down lists, however I'd like to map a list of ID's to search from and see if they have duplicate options to splice out as opposed to just one input selector.
An example of this would be as follows:
<select id="MeatList">
<option value="OBgYN7" >Ham</option>
<option value="ELmn5">Beef</option>
<option value="KrUKt6">Chicken</option>
<option value="OBgYN7" selected="selected">Ham</option>
</select>

<select id="Seats">
<option value="2" >Table For Two</option>
<option value="3">Table For Three</option>
<option value="5">Table for Five</option>
<option value="10" >Party Table</option>
</select>

<select id="Lastname">
<option value="Tao" >The Tao's</option>
<option value="Smith">The Smith's</option>
<option value="Samuels">The Samuels'</option>
<option value="Smith" >The Smith's</option>
</select>

As you can see, the inputs MeatList and Lastname have duplicate values, I want to be able to search all drop down boxes for duplicate values (or inner text) and splice them out. Would that be possible through mapping of some sort?
The code to be used would be:
[].slice.call(fruits.options)
  .map(function(a){
    if(this[a.innerText]){
      if(!a.selected) fruits.removeChild(a);
    } else {
      this[a.innerText]=1;
    }
  },{});

And to get an idea of what I mean by mapping the drop-down lists, I would use a code like this:
 var idlist= ["MeatList", "Seats", "Lastname"];
     var handlelists = idlist.join("|");
    [].slice.call(handlelists.options)
      .map(function(a){
        if(this.search([a.innerText])){
          if(!a.selected) handlelists.removeChild(a);
        } else {
          this[a.innerText]=1;
        }
      },{});

A: Not sure what you thought was going on in the handleLists part of your script. You just need to wrap the other segment in an iterator (forEach) after finding the elements corresponding to the IDs.
var idList= ["MeatList", "Seats", "Lastname"].map(function(id){return document.getElementById(id)});

idList.forEach(function(select){
  [].slice.call(select.options)
  .map(function(a){
    if(this[a.value]){
      select.removeChild(a);
    } else {
      this[a.value]=1;
    }
  },{});
});

Of course, this is bad.  You should make de-duplicating a function of it's own, eg.:
function deDuplicate(select){
  [].slice.call(select.options)
    .map(function(a){
      if(this[a.value]){
        select.removeChild(a);
      } else {
        this[a.value]=1;
      }
    },{});
}

and then:
var idList= ["MeatList", "Seats", "Lastname"].map(function(id){return document.getElementById(id)});
idList.forEach(function(select){ deDuplicate(select); });

Personally I recommend learning/using CoffeeScript as it uncrufts Javascript a great deal, the de-dupe looks like this:
deDuplicate = (select)->
  [].slice.call(select.options).map (a)->
    if @[a.value]
      select.removeChild a
    else
      @[a.value] = 1
  , {}

and then wrapped you can do:
deDuplicate select for select in ["MeatList", "Seats", "Lastname"].map (id)->
  document.getElementById id

Which reads more plainly as english, at least to me it does. As always YMMV.


text:
Q: from a droppable item find child div with class when an item is drag and dropped in order to write changes to a database I need to get the html from a div inside the dropped item.
I don't seem to be able to successfully get the html by using closest('task-type').html() and am unsure why.
I'm trying to use the receive event.  here is a jsfiddle with what I have so far, any help would be great.
here is the code
var $container = $(".task-container");
var $task = $('.todo-task');

$task.draggable({
addClasses: false,
connectToSortable: ".task-container",
});

$container.droppable({
accept: ".todo-task"
});

$(".ui-droppable").sortable({
placeholder: "ui-state-highlight",
opacity: .5,
helper: 'original',
beforeStop: function (event, ui) {
    newItem = ui.item;
},
receive: function (event, ui) {
//get task-type and task id.
        console.log($(this).closest('.task-header').html());
        var tasktype = $(this).closest('.task-type').html();
        var taskid = $(this).closest('.task-no').html();

        dropElement = $(this).closest('.ui-droppable').attr('id');
        // console.log($(this).closest('.ui-droppable').attr('id'));

        //save the status and the order of the item.
        if (dropElement == "backlog")
        {
            // save the status of the item
        }
        else if (dropElement == "pending")
        {
            // save the status of the
        }
        else if (dropElement == "inProgress")
        {
        }
        else if (dropElement == "completed")
        {
        }
}
}).disableSelection().droppable({
over: ".ui-droppable",
activeClass: 'highlight',
drop: function (event, ui) {
    $(this).addClass("ui-state-highlight");
}
});

A: http://jsfiddle.net/h5rt2qgw/7/
var tasktype = $(this).find('.task-type').html();
 var taskid = $(this).find('.task-no').html();
dropElement = $(this).attr('id');


text:
Q: Different approach to try-except blocks

try:
    pos = name.find("#")
    name = name[:pos]
except:
    pass
try:
    pos = name.find("TDCJ")
    name = name[:pos]
except:
    pass

Is there a way to combine these two try and except? My program keeps on building I feel like there is way too many try and excpet blocks. How do I avoid adding try and except often?

A: If the try-except is the same you can just loop the desired string elements. Something like the following:
l = ["#", "TDCJ"]

for elem in l:
    try:
        pos = name.find(elem)
        name = name[:pos]
    except:
        pass

Generally, you should keep the Dont Repeat Yourself (DRY) principle


text:
Q: Making js pick up HTML code inside data attribute? I have a piece of html code in data attribute.
<a href="#" data-type="video" data-video='

<video id="player" playsinline width="960" class="pswp__video" controls data-poster="img/poster.jpg"><source src="video/soulmv-low.mp4" type="video/mp4"></video>

'>

Is there any way to make js pick up the code inside data attribute and modify it, as normal?
Thanks!

A: If you want to load an html as an DOM Element to modify is easily instead of an string, you could do the following:
const link = document.querySelector('a')

const dataVideoAttribute = link.getAttribute('data-video')

const dataVideoElement = createElementFromString(dataVideoAttribute)

The helper function to create JS Object is descrbied bellow
/**
 * Create a new HTML Object from an HTML code as string
 * and returns the object.
 *
 * @params elementAsString: HTML code as a raw string
 *
 * @returns object: HTML Element created from raw string
 */
function createElementFromString(elementAsString) {
  var div = document.createElement('div');
  div.innerHTML = elementAsString.trim();

  // Change this to div.childNodes to support multiple top-level nodes.
  return div.firstChild;
}

then, you can do normal routines with your JS code, for exmaple:
dataVideoElement.setAttribute('new-att', '1')

If you want to update and save on html attributes you could:
link.getAttribute('data-video', dataVideoElement.outerHTML)

A: To get the data attribute, for example if the attribute is data-type="video"
const type = document.getElementById('item1').dataset.type;

To set it
document.getElementById('item1').dataset.type = "mp3"


text:
Q: Odd field in struct? c++ Hi I was wondering if someone could explain to me a field in a struct that looks like this:
struct example {
void (SomeClass::*someMethod)();
};

What exactly is this and how/why would you use it?  Thanks.

A: This structure contains a pointer to a function with void return type and without parameters.
We would set this pointer to an address of actual function and execute the function via the pointer some time later. Function pointers are very convenient thing for providing different functions to handle some task depending on circumstances.

A: void (SomeClass::*someMethod)();

This is declaration of pointer to member function of "SomeClass" class which is accepting and returning void.


text:
Q: android: Save to database in separate thread causes exception db is closed So Im trying to save data to database using separate thread but it causes an exception:

java.lang.IllegalStateException: database not open

I assume this is not a task for a Loader since I don't need any resulting cursor, it has just to save my data. The save to db code looks as follows:
Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        dbHelper.saveMessages(messages);
    }
});
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();

If I remove this DB operation out from a Thread everything works good but it causes UI lags. The same things happens if I'm trying to read from DB from a separate thread.
this is a part of a DB writing code:
    SQLiteDatabase db = dbAdapter.getWritableDatabase());
    try {
        if (existingMessage != null)
            insertId = db.update(Tables.Messages.TABLE_NAME, values, Tables.Messages.SERVER_ID + "=?", new String[]{String.valueOf(message.serverId)});
        else
            insertId = db.insertOrThrow(Tables.Messages.TABLE_NAME, null, values);
    } catch (Exception e) {
        e.printStackTrace();
    }

Actually exception happens at db.update() or at db.insertOrThrow() line. Its not guaranteed to throw exception but it does from time to time. It could write for instance 5 objects and then fail on 6th.
What am I doing wrong or whats wrong with SQLiteOpenHelper?
The full exception log:
10-30 22:34:52.746  10431-10536/com.myapp W/System.err﹕ java.lang.IllegalStateException: database not open
10-30 22:34:52.746  10431-10536/com.myapp W/System.err﹕ at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1224)
10-30 22:34:52.746  10431-10536/com.myapp W/System.err﹕ at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1184)
10-30 22:34:52.746  10431-10536/com.myapp W/System.err﹕ at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1264)
10-30 22:34:52.746  10431-10536/com.myapp W/System.err﹕ at com.myapp.db.DatabaseHelper.saveMessages(DatabaseHelper.java:478)
10-30 22:34:52.746  10431-10536/com.myapp W/System.err﹕ at com.myapp.db.DatabaseHelper.requestMessages(DatabaseHelper.java:1245)
10-30 22:34:52.746  10431-10536/com.myapp W/System.err﹕ at com.myapp.activity.LoginActivity$9.run(LoginActivity.java:425)
10-30 22:34:52.746  10431-10536/com.myapp W/System.err﹕ at java.lang.Thread.run(Thread.java:1096)

UPDATE:
I'd discovered that its all about reading from db actually. In my code first I read from db to ensure there is no such record. After that I decide what to do - insert or update. And the issue happens with readable db. Right after db is opened for read and the next line should read from db it appears "not opened". And there is no thread for reading, everything happens in one thread: 1st read then write. However reading randomly fails from time to time. So its not writing as I mentioned before.

A: I see multiple issues with your implementation. First dbHelper can be used by another thread and could create a deadlock so you should guard it with lock. proceedToNextActivity() looks like does some work on UI, doing anything from background thread is simply wrong and will cause a crash.
If dbHelper don't need any UI element just pass a copy of messages to this thread and create dbHelper -> do some work -> close helper -> end thread. Hopefully this will solve your issue.

A: Make an insert or update method.  If the insert fails because of a duplicate key then update.

A: Since I'm using the Dmytro Danylyk's way to work with DB (also mentioned on SO here) I made a mistake thinking that for reading purposes I should use readable DB returned by standard getReadableDatabase() method. Instead I should always use the writable one returned by openDatabase() method (which is thread safe).


text:
Q: Sequentially translate strings in a Transport Request/Task I've coded a few ABAP programs and created a some messages in a custom message class, they are under an specific Transport Request/Task.
I need to translate all translatable strings (Messages, Text Symbols, Selection Texts, etc) of the objects found in that Transport Request/Task.
Is there any tool (transaction, program, etc) to sequentially translate all those strings without manually exploring the objects one by one?

A: Use a translation worklist. It might be sensible to group the objects to be translated into separate packages for this - this also facilitates packaging and delivery of later versions.

A: You can use tcode SE63 in order to translate your messages, programs, screens basically everything.
For example you can use this path in order to translate your text elements in an ABAP program:

se63 -> Translation -> ABAP Objects -> Short Texts -> ABAP Texts ->
  REPT Text Elements.

Write down your program's name and its main language and the target language. Go for it.
Hope it was helpful.
Talha


text:
Q: IE9 Quirks mode doesn't pass event parameter to event handler I have a problem with the IE9 quirks mode. I have registered an oncahnge-event to an input element. This works so far, but in IE9 our site goes to quirks mode (it is as it is) and there I have the problem, that the browser doesn't pass the event-Object into my handler method.
document.getElementById("foo").onchange=myChangeMethod;
function myChangeMethod(event){
  //In IE 9 quirks mode "event" is undefined...
  if(event != undefined){
    //do stuff
  }
}

This can be tested in IE10 (i suppose als in IE9) with opening the WebDeveloper Console (F12), Setting BrowserMode to "IE9" and the Document-Mode to (IE5-Quirks). Then the browser behaves the same like setting the native IE9 to "IE 9 Compatibility mode" and Document-Mode to "Quirks".
Is there a possibility to get the event-Object somehow?
Thanks in advance!

A: I suppose the event is global in IE quirks mode, so checking the event parameter and assign window.event if it's undefined would solve the problem:
function myChangeMethod(evt){
  //In IE 9 quirks mode "event" is undefined...
  evt = evt || window.event; //<== HERE
  // additionally in quirks mode evt.target is evt.srcElement,
  // so if needed you could assign evt.target as:
  var originator = evt.target || evt.srcElement;
  if(evt){
    //do stuff
  }
}


text:
Q: extract values based on two columns I would like to extract a price value based on two other columns. In table 1, I am given the raw data where I want to draw from. In Table 2, I am given only the contract number, and I would like to find the type being "Mater" and have the price listed out for it.
I've tried to use this formula but I don't think I am calling the columns correctly.
=IF(AND(Table2!A1=Table1!$A$1:$A$6,Table1$C$1:$C$6="Mater"),Table1!$D$2:$D$6,"")
Is there a formula using index match, if(and), or another one that could work in this case?
Thank you!
Table 1.

Contract
Work
Type
Cost

5321a
aaa
Labor
52

5321a
ab
Mater
57

5641a
aba
Mater
10

536451a
aae
Labor
75

2441a
aan
Labor
42

53421
aar
Mater
14

Table 2

Contract
Mater Cost

5321a
57

5641a
57

53421
14

A: The following should work:
=SUMIFS(Sheet1!D2:D7,Sheet1!A2:A7,A2,Sheet1!C2:C7,"Mater")

(I'm assuming the first table in on Sheet1)


text:
Q: Как дублировать несколько элементов из html формы? У меня есть форма в html. В ней множество input и output. Мне нужно их продублировать и отобразить ниже. Также мне надо всё это обрабатывать в pythom(flask) и следовательно нужно автоматически менять id, чтобы всё не слетело. Пробовал через js, но пока что не выходит.
Вот кнопка, по клику которой отправляется запрос на сервер
$('#addServId').click(addServ)
Вот функция, которая её обрабатывает.
function addServ(){
$('.client').clone().appendTo($('#virtualId'))
$('.serv').clone().appendTo($('#virtualId'))
$('.core').clone().appendTo($('#virtualId'))
$('.ram').clone().appendTo($('#virtualId'))
$('.sata').clone().appendTo($('#virtualId'))
$('.sas').clone().appendTo($('#virtualId'))
$('.ssd').clone().appendTo($('#virtualId'))
$('.res').clone().appendTo($('#virtualId'))

}
P.S. virtualId - это id формы.
Буду благодарен любой помощи

A: Попробуйте как-то так:
const res = $('.res').clone()
res.attr('id',newResId)
res.appendTo($('#virtualId'))


text:
Q: analyze a query postgres I have a query below, may i please know what needs to be done to reduce execution time from 18sec
the query
SELECT DISTINCT ON (player_name) server_name, player_anme, logged_at, joined_at
FROM player_cache
WHERE server_name ILIKE '{query[0]}'
AND logged_at > (now() - interval '{history} hour')
ORDER BY player_name,logged_at desc;

The execution plan
Unique (cost=14326.21..14326.25 rows=7 width=82) (actual time=18907.017..18907.049 rows=32 loops=1)
  -> Sort (cost=14326.21..14326.23 rows=7 width=82) (actual time=18907.015..18907.023 rows=81 loops=1)
    Sort Key: player_name, logged_at DESC
    Sort Method: quicksort Memory: 36kB
  -> Index Scan using idx_logged_at on player_cache (cost=0.56..14326.11 rows=7 width=82) (actual time=5.605..18906.463 rows=81 loops=1)
    Index Cond: (logged_at > (now() - '30:00:00'::interval))
    Filter: ((server_name)::text ~~* 'Server-1'::text)
    Rows Removed by Filter: 79825
Planning Time: 0.665 ms
Execution Time: 18907.108 ms

A: You can create a trigram index to speed up the ILIKE condition:
CREATE EXTENSION IF NOT EXISTS pg_trgm;

CREATE INDEX ON player_cache USING gin (server_name gin_trgm_ops);


text:
Q: Show that $A^2=0$ is possible but $A^T A=0$ is not possible. Show that $A^2=0$ is possible but $A^T A=0$ is not possible.
It is clearly true when $A=0$ but for other cases I can not step to prove. Actually, I took an example and I saw it is true but I can not prove the general case.

A: Notice that :
$$\|A\|^2 = \mathrm{trace} \left(A^{\mathrm{T}} \, A\right)$$
then :
$$A^{\mathrm{T}} A = 0 \iff A = 0$$
but we can have $A^2 = 0$ for a matrix that isn't null.
Example : For :
$$A = \begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix}$$
we have $A \neq 0$ and $A^2 = 0$.


text:
Q: Debug a Qt assert in Visual Studio I am getting an assert that generates a dialog from Qt to abort, retry, or ignore. Unfortunately, when I retry, it always just goes to app.exec() so I cannot see where the error is coming from, or what inputs may be contributing.
When I debug, I can see all my code and moc code, and all variables and pointers are set appropriately. But when I step into Qt code, I get Qt5Cored.pdb not loaded. I cannot seem to locate the PDB files in my Qt installation either.
The error happens after emitting a signal and all (my) slots have completed successfully.
The error from Qt is so deep in the weeds, it is not helpful:
Debug Error!

Program: Qt5Cored.dll
Module: 5.14.2
File: painting\qoutlinemapper.cpp
Line: 105

ASSERT: '!path.isEmpty()' in file painting\qoutlinemapper.cpp, line 105

(Press Retry to debug the process)

I inspected the source code for the error, but that wasn't terribly helpful, and the debugger will not provide the caller.
I don't know what is the problem since I can't debug, so I can't provide a minimal working example either. All of my code is working as expected, but I am sure I am providing Qt with something inappropriate, but I just do not know what. Any help on how to better debug this issue so I can determine what is causing it would be appreciated.
Interestingly, if I run in release and the assert is bypassed, the applications works exactly as expected with no obvious side effects (I do realize that could just be luck).


text:
Q: how to disable one of the input field if it does not qualify My problem is how to disable one of the input field if it does not qualify in the following cases: if the user select a cash-In, the input field with the attributes name of credit must be disabled, so that the user can not fill it. vice versa if the user select a cash-Out, then input field with debit attributes name should be disabled.
I tried to create those script, but it does not run properly.

Account	Debet	Credit

        <select id="acc" name="acc" required="required">
            <option value=""></option>
            <option value="db">Cash-In</option>
            <option value="cr">Cash-Out</option>
        </select>

    <input type="text" id="debit" name="debit" />
    <input type="text" id="credit" name="credit" />

A: use .change() event instead of .click() event.

$('#acc').change(function(){
    var account = $("select#acc").val();
    if (account == "db"){
        $('#credit').prop('disabled', true);
        $('#debit').prop('disabled', false);
    }
    else if (account == "cr"){
        $('#debit').prop('disabled', true);
        $('#credit').prop('disabled', false);
    }
});

Account	Debet	Credit

        <select id="acc" name="acc" required="required">
            <option value="">Select</option>
            <option value="db">Cash-In</option>
            <option value="cr">Cash-Out</option>
        </select>

    <input type="text" id="debit" name="debit" />
    <input type="text" id="credit" name="credit" />

A: Use this
$('#acc').click(function(){
    var account = $("select#acc").val();
    if (account == "db"){
        $('#credit').attr('disabled', 'disabled');
         $('#debit').removeAttr('disabled');
    }
    else if (account == "cr"){
        $('#debit').attr('disabled', 'disabled');
         $('#credit').removeAttr('disabled');
    }
});

A: Use change() event, Then switch debit and credit field disabling if the user selected either of the two.
In your case, and you also said, that the field must be enable if the user selected the requirement,
So you should also add a condition that will force the user to select, or else he cannot use the field.
Look at this LIVE DEMO
$('#acc').change(function(){

    var account = $(this).val();
    if (account == "db"){
        $('#credit').prop('disabled', false);
        $('#debit').prop('disabled', true);
    }
    else if (account == "cr"){
       $('#debit').prop('disabled', false);
       $('#credit').prop('disabled', true);
    }
    else{
       $('#debit, #credit').prop('disabled', true);
    }

});


text:
Q: Zipping sub directories is zipping only content of sub directories but not the sub directories Below is the code I tried. it is zipping only content of the sub folder but not the folder
I need to zip all sub folders along with the contents. what i am doing wrong here.
Example: I have a folder 'demo' inside demo folder  i have a, b, c folders. I want to zip a, b, c along with contents and zip should not include parent that is demo.
static void addDir(File dirObj, ZipOutputStream out) throws IOException {
        File[] files = dirObj.listFiles();
        byte[] tmpBuf = new byte[1024];

        for (int i = 0; i < files.length; i++) {
          if (files[i].isDirectory()) {
            addDir(files[i], out);
            continue;
          }
          FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
          System.out.println(" Adding: " + files[i].getName());
          out.putNextEntry(new ZipEntry(files[i].getName()));
          int len;
          while ((len = in.read(tmpBuf)) > 0) {
            out.write(tmpBuf, 0, len);
          }
          out.closeEntry();
          in.close();
        }
      }

    public static void zipFiles(File[] subd) {

        String zipFile = "test.zip";

        try {

            FileOutputStream fos = new FileOutputStream(zipFile);

            ZipOutputStream zos = new ZipOutputStream(fos);

            for (File dir : subd) {

                addDir(dir, zos);

            }

            // close the ZipOutputStream
            zos.close();

        } catch (IOException ioe) {
            System.out.println("Error creating zip file: " + ioe);
        }

A: Here is a code I did for zip files and directories with hierarchy and without hierarchy.
zip.getHierarchy().equals("F") part does the work you want to do.
In this code, you have to pass source file, destination, hierarchy (T/F) as arguments.
Additionally you may need a DTO class.
public static void Start() throws IOException{

    FileOutputStream fos = new FileOutputStream(zip.getDestination());
    ZipOutputStream zipOut = new ZipOutputStream(fos);
    File fileToZip = new File(zip.getSourcePath());

        zipDirectory(fileToZip, fileToZip.getName(), zipOut);

    zipOut.close();
    fos.close();
}

public static void zipDirectory(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {

    if (fileToZip.isDirectory()) {

        File[] children = fileToZip.listFiles();

        for (File childFile : children) {
            if(zip.getHierarchy().equals("T")) {
                zipDirectory(childFile, childFile.getPath(), zipOut);
            }else if(zip.getHierarchy().equals("F")){
                zipDirectory(childFile, childFile.getName(), zipOut);
            }
        }
        return;
    }
    doZip(fileToZip,fileName,zipOut);
}

public static void doZip(File fileToZip,String fileName,ZipOutputStream zipOut) throws IOException {
    FileInputStream fis = new FileInputStream(fileToZip);
    ZipEntry zipEntry = new ZipEntry(fileName);
    zipOut.putNextEntry(zipEntry);
    byte[] bytes = new byte[1024];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zipOut.write(bytes, 0, length);
    }
    fis.close();
}


text:
Q: What is boundary of $S^1\times I^2$ As I know, the general cylinder is $S^k \times R^l$. For talking the boundary of general cylinder,  let $I=[0,1]$. Consider $S^k \times I^l$, obviously, when $l=1$, the boundary of $S^k \times I^l$ is two unit spheres $S^k$. But when $l\ge 2$, it is hard for me to image it. For simple, how to know what is the boundary of
 $S^1\times I^2$  ?

A: In general, the boundary of the products of two manifolds $M\times N$ is $\partial M\times N\cup M\times\partial N$.
Now $\partial S^k=\varnothing$ and $\partial I^\ell = S^{\ell-1},$ (since a filled hypercube $I^\ell$ is homeomorphic to the disk $D^\ell$, its boundary is a hypercube homeomorphic to a sphere), so for a sanity check, let's look at $$\partial(S^k\times I^1)=\partial(S^k)\times I^1\cup S^k\times \partial(I^1) = \varnothing\times I^1\cup S^k\times S^0 = S^k\times \{-1,1\}=S^k\coprod S^k,$$ so yes, that's two copies of $S^k$ since $\partial(I^1)=S^0$ is two points, and the boundary of a sphere is empty.
Next for $k=1,\ell=2,$ the formula gives us $\partial (S^1\times I^2) = S^1\times S^1$, a torus, which checks out (note that the second $S^1$ here is actually a square. The boundary of a squared off solid torus is a squared off torus).
For your general case then, $\partial (S^k\times I^\ell) = S^k\times S^{\ell-1}.$


text:
Q: Javascript - Making Array Index toLowerCase() not working I'm trying to make all array indexes lowercase strings, but it's not working. I looked at other answers on here and tried their solutions like using toString() before adding toLowerCase but it doesn't work, which is weird.
I created a jsfiddle of the problem here.
JS:
$(colorArr).each(function(i, item) // loop thru each of elements in colorArr and make lowercase + trim
{
    if(colorArr[i] !== undefined) // check if colorArr index undefined
      {
      colorArr[i].toString().toLowerCase().trim(); // FIX HERE
      /* TRIED - DIDN'T WORK!
      colorArr[i].toLowerCase().trim();
      */
       }
});

A: i updated your fiddle
https://jsfiddle.net/af91r2cq/6/
colorArr[i] = colorArr[i].toString().toLowerCase().trim(); // FIX HERE

your way was really close ;)

A: You need to set the value back
It should be
colorArr[i] = colorArr[i].toString().toLowerCase().trim(); // FIX HERE

Or simply
colorArr = colorArr.map(function(value){ return value ? value.toLowerCase().trim() : ""; });

A: Another way change all defined values in the array to lowercase is to use the jQuery.map function like so:
colorArr = $.map(colorArr, function(item, i) {
  if(item !== undefined) {
    return item.toString().toLowerCase().trim();
  }
});


text:
Q: Unable to download a complete db file I'm trying to download a db file from a GitHub repo using the following code:
library(RSQLite)
library(curl)

url <- "https://github.com/kotartemiy/newscatcher/tree/master/newscatcher/data/package_rss.db"
curl::curl_download(url = url,
              destfile = "inst/external-data/package_rss.db",
              quiet = TRUE, mode = "wb")

Which works, but downloads the file size between 79Kb and 82Kb (depending on which mode I use). But when I try to access the database file I get the warning:
sqlite.driver <- dbDriver("SQLite")
db <- dbConnect(sqlite.driver,
                dbname = "inst/external-data/package_rss.db")

Warning message:
Couldn't set synchronous mode: file is not a database
Use synchronous = NULL to turn off this warning.

Followed by the error:
dbListTables(db)

Error: file is not a database

This can be reproduced using download.file() and different mode arguments. However, if I download the file manually it has 376 Kb and the RSQLite code works without any problems. What may be causing the issue? Thanks

A: As @27ϕ9 said, you're downloading a webpage, not the file it references.
url <- "https://github.com/kotartemiy/newscatcher/tree/master/newscatcher/data/package_rss.db"
download.file(url, "~/Downloads/package_rss.db")
# trying URL 'https://github.com/kotartemiy/newscatcher/tree/master/newscatcher/data/package_rss.db'
# Content type 'text/html; charset=utf-8' length unknown
# downloaded 82 KB

readLines("~/Downloads/package_rss.db", n=10)
#  [1] ""
#  [2] ""
#  [3] ""
#  [4] ""
#  [5] ""
#  [6] "<!DOCTYPE html>"
#  [7] "<html lang=\"en\">"
#  [8] "  <head>"
#  [9] "    <meta charset=\"utf-8\">"
# [10] "  <link rel=\"dns-prefetch\" href=\"https://github.githubassets.com\">"

If you go to that URL in a browser, you'll see two links on the page:

*

*the "Download" button pushes you to a link under raw.githubusercontent.com (link), so you can hunt for that URL;

*There's also a "view raw" link, which takes the same URL you started with, replaces the /tree/ with /blob/, and appends ?raw=true (link).

(While it's possible to harvest the html and get the link programmatically, I think just starting with the correct URL is the preferred route.)


text:
Q: Usage of "has" vs "have" nowadays I'm here again with misunderstanding of some grammar rules. So there is sentence where it's said " 4 days has never felt so long". why a song writer used "has" instead of "have", when I asked question bout "he do" vs "he does" I got what's the point of it, but here, I can't understand. There is no rhyme, there is nothing that can be cause of using "has" instead of "have"
Here is the lyrics: Baby, I don't feel so good Six words you never understood I'll never let you go Five words you'll never say (aw) I laugh alone like nothing's wrong Four days has never felt so long If three's a crowd and two was us One slipped away

A: It might seem a bit confusing because "days" is plural, which makes "have" seem like the appropriate choice. However, "4 days" is a single period of time, so "has" agrees with the subject in that case.

A: Whether you use the plural or the singular depends entirely on how you are interpreting the noun.
For instance, some people say this:

Your twenty minutes starts now.

This means that there is a single period of time (singular) that totals twenty minutes.
So, after one minute has passed:

You now have nineteen minutes.
  → Your twenty minutes is still not up.

However, other people say this:

Your twenty minutes start now.

This means that there are twenty intervals of time (plural), consisting of a minute each. After each minute passes, that minute is gone.
So, after one minute has passed:

You now have nineteen minutes.
  → Your twenty minutes are not all gone.

The song lyric in the question can be interpreted in the same way. The verb used depends on how the four days are viewed.

Four days has never felt so long.
  → A single period of time that totals four days has never felt so long.

Or:

Four days have never felt so long.
  → Four individual days, one after the other, have never felt so long.


text:
Q: How do I create a schema dynamically to store the folder structure? I'm new to MongoDB, and I'm trying to design the schema structure for storing the folder hierarchy.
This is my schema design:
parent: {
   id: Schema.Object,
   title: String,
   children: []
}

Above children will store details dynamically in the following manner.
The id will refer to folder schema which has folder details.
children:[
    {
       id: Schema.Object,
       title : String,
       children:[
          {
             id:Schema.Object,
             titile: String
          }
       ]
    }
]

The above method is working fine. But I'm facing an issue on updating the title for a particular Id will be quiet complex. Is there any other way to design schema. Thanks in Advance.

A: I think nesting of children is not a proper approach to achieve this.
Rather you can introduce a new key for children, level this will help in
  identifying the structure/hierarchy.
children:[
      {
         id:Schema.Object,
         titile: String,
         level: Number
      }
   ]

eg: abc/bcd/egt/something
abc(root) - level 0
bcd - level 1
egt - level 2
something - level 3
It will be dynamic and easy to maintain.


text:
Q: PathIterator in C# In Java, we can iterate through the vertexes of a Shape with PathIterator (and detect loops and other functionality), I have been trying to convert the following code to C# by I can't find what is the class in C# that is equivalent to PathIterator. So does anyone knows what is the equivalent class or approach in C#.
The code is:
private void processCircleShape(Circle circle, final Shape cellBoundaryPolygon)
{
    initializeForNewCirclePrivate(circle);
    if (cellBoundaryPolygon == null)
    {
        return;
    }
    PathIterator boundaryPathIterator = cellBoundaryPolygon.getPathIterator(null);
    double[] firstVertex = new double[2];
    double[] oldVertex = new double[2];
    double[] newVertex = new double[2];
    int segmentType = boundaryPathIterator.currentSegment(firstVertex);
    if (segmentType != PathIterator.SEG_MOVETO)
    {
        throw new AssertionError();
    }
    System.arraycopy(firstVertex, 0, newVertex, 0, 2);
    boundaryPathIterator.next();
    System.arraycopy(newVertex, 0, oldVertex, 0, 2);
    segmentType = boundaryPathIterator.currentSegment(newVertex);
    while (segmentType != PathIterator.SEG_CLOSE)
    {
        processSegment(oldVertex, newVertex);
        boundaryPathIterator.next();
        System.arraycopy(newVertex, 0, oldVertex, 0, 2);
        segmentType = boundaryPathIterator.currentSegment(newVertex);
    }
    processSegment(newVertex, firstVertex);
}

The code is from the following answer:
Compute the area of intersection between a circle and a triangle?

A: I think it is Shape.RenderedGeometry (or DefiningGeometry) as descriptions match mostly on
https://docs.oracle.com/javase/7/docs/api/java/awt/geom/PathIterator.html
for Java
and
https://msdn.microsoft.com/en-us/library/system.windows.shapes.shape.renderedgeometry(v=vs.110).aspx
for C#


text:
Q: User privacy in WordPress file access Is it possible to create WordPress users that can only view their own uploads and not all of the uploads in the media library? If so, how?
Ultimately, I want to have a password protected interface where I can exchange files with my clients. Because of privacy issues, I do not want clients to be able to view each others files, or see any information about each other. Any ideas on how to make this possible would be greatly appreciated.

A: There is a plugin that should be able to handle this:
http://wordpress.org/extend/plugins/user-and-document-monitoring/
However, you might be better off switching to Joomla to take advantage of DocMan:
http://extensions.joomla.org/extensions/directory-a-documentation/downloads/10958


text:
Q: How do you sort the answers to a question by number of votes per answer? It seems like answers are normally sorted by number of votes, but I just found a question on StackOverflow that doesn't seem to be: What is the single most influential book every programmer should read?
Is there a way to ask StackOverflow to sort these answers by vote?

A: Use the sorting tabs that are in the top right of the answer list. It will use your last setting, so maybe you clicked a link that had a different sort order.

A: There is no way to sort by "number of votes" however, there is a way to sort by "net votes" (upvotes minus downvotes) which is the "votes" tab at the top of the answers list.


text:
Q: closures: expected u32 found type parameter Soy nuevo en Rust
EL problema radica en que mi tipo generico T solo acepta argumentos de U32 y en este caso estoy intentando pasar un  valor generico que almaceno en U.
¿Hay alguna manera de hacer cast a los genericos para pasarlos a un tipo en concreto? o que puedo hacer para solucionar el problema,
codigo:
#[derive(Debug)]
struct Cacher<T, U> where T: Fn(u32) -> u32 {
    calcular:T,
    valor:Option<U>,
}
impl<T, U> Cacher<T, U> where T: Fn(u32) -> u32 {
    fn nuevo(calcular:T, valor:U) -> Cacher<T, U> {
        Cacher{
            calcular,
            valor:None,
        }
    }
    fn valor(&mut self, arg:U) -> u32 {
        match self.valor {
            Some(v) => v,
            None => {
                let v = (self.calcular)(arg);
                self.valor = Some(arg);
                v
            }
        }
    }
}

fn generar(intensidad:u32){
    let mut resultado = Cacher::nuevo(|num| {
        println!("Trabajando");
        num
    },None);

    let res_a = resultado.valor(Some(4));
}

fn main() {
    generar(3);
}

A: Trata cambiar resultado.valor(Some(4)) a resultado.valor(4), para que U sea u32 en vez de Option<u32>. También, el mezclaje de U y u32 es problemática; es necesario siempre usar el uno o el otro si deben ser intercambiados, porque Rust no puede verificar que siempre son lo mismo. Si eso no funciona, explica porqué, y provee el mensaje de error entero.


text:
Q: How to make a function for an element to run continously or never end? Hello I'm pretty new to JS and HTML and was trying to make something close to a text editor component like Monaco Editor.
How it works-
function Ventify() takes an element and adds a gutter and a textarea. So I made an if statement in this function that checks the no of lines in the textarea and create gutter lines accordingly. the problem I experienced while doing this was that the function only numbers the lines of the text when it was loaded because the function ended. Is there a way in which I can make the function/if statement never end.
Here is a codepen for the project: https://codepen.io/chrismg/pen/qgxOxg .
JS(with JQuery):
function Ventify(element){
    element.style.display="flex";
    element.style.flexDirection = "row";
    var gutter = document.createElement("div");
    var textarea = document.createElement("textarea");
    gutter.className = "gutter";
    textarea.className = "ventiEditor";
    gutter.style.width = "100px";
    gutter.style.height = "100%";
    gutter.style.backgroundColor = "#1d252c";

    textarea.style.width = "calc(100% - 100px)";
    textarea.style.overflowY= "scroll";
    textarea.style.whiteSpace = "pre";
    textarea.style.resize = "none";
    textarea.style.height = "100%";
    textarea.style.margin = "0px 0px 0px 0px"
    textarea.style.border = "0px solid rgb(255,255,255)"
    textarea.style.backgroundColor = "#1d252c";
    textarea.value = "\n\n\n\n";
    element.appendChild(gutter);
    element.appendChild(textarea);
    if(gutter.childNodes.length != $(textarea).val().split("\n").length){
        while(gutter.childNodes.length < $(textarea).val().split("\n").length){
            var gutterChild = document.createElement("div");
            gutterChild.style.width = "100%";
            gutterChild.style.color = "rgba(58,74,88,1)"
            gutterChild.style.textAlign = "center";
            gutter.appendChild(gutterChild);
            gutterChild.innerHTML = `${gutter.childNodes.length}`
        }
    }
}
    Ventify(document.getElementsByClassName("container")[0])

HTML:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Test Ground</title>

A: A better approach will be using a onKeydown ( or similar events ) event on a input or textarea. Like in below example

function handle(){
  let element = document.getElementById('inp').value;
  console.log(element, 'called on change')
}
<input id='inp' onKeydown=handle() />

In your code can use setInterval. And clearinterval when you want to stop.
setInterval(Ventify(document.getElementsByClassName("container")[0]),200)

Codepen

A: You can use input event attached to <textarea> element to perform a task at user input. See How to continually add typed characters to a variable?.
If you are trying to check if an element childList or attributes have changed you can use MutationObserver. See call function on change of value inside
 tag.

A: You can use the onchange event to fire your function every time the user updates the content.
const element = document.getElementsByClassName("container")[0];
element.onchange = (event) => Ventify(event.target, 200);


text:
Q: Equivalent of Win32 function ::FlushFileBuffers on Android I have a simple write-ahead logging implementation in C++ on Win32 platform that write changes to a log file then does
::FlushFileBuffers(m_hLogFile);

then write the changes to the data file, does
::FlushFileBuffers(m_hDataFile);

and then clears the log with
::SetFilePointerEx(m_hLogFile, 0, FILE_BEGIN);
::SetEndOfFile(m_hLogFile);

What are the equivalent functions on Android (saying more exactly, in Android NDK)?