text:
Q: Implementation details of a Bayesian classifier I've implemented a simple Bayesian classifier, but I'm running into some overflow problems when using it on non-trivial amounts of data.
One strategy I tried in order to keep the numbers small, but still exact, was to keep reducing the numerator and denominator with the greatest common divisor for every part of the equation. This, however, only works when they have a common divisor...
Note, the problem goes both ways, when I keep the denominators and numerators separate for most of the calculation I struggle with integer overflow, when I do most calculations on the fly, using double arithmetic, I'm met with the various problems/limits that really small double values have (as defined by IEEE 754).
As I'm sure some of you here have implemented this algorithm before, how did you deal with these issues? I'd prefer not to pull in arbitrary precision types as they cost too much and I'm sure there exists a solution which doesn't require them.
Thanks.

A: Usually the way you handle this is by taking logs and using adds, and then doing an exp if you want to get back into probability space.
p1 * p2 * p3 * ... * pn = exp(log(p1) + log(p2) + log(p3) + ... log(pn))
You avoid under flows by working in log space.

A: If you're classifying between two categories you can introduce the log ratio of probabilities for each category. So if:
log(Pr(cat1) / Pr(cat2)) <=> 0 # positive would favor cat1 and negative cat2

That is equal to:
log(Pr(cat1)) - log(Pr(cat2)) <=> 0

And if (as in Bayesian classifiers) the category probabilities are themselves products of probabilities given conditions:
log(Pr(cat1|cond1)) + ... <=> log(Pr(cat2|cond1)) + ...

Thus you are dealing with summation rather than multiplication and you will need a massive data set to run into the same thing.


text:
Q: How to download and read a file from a web site without having web browser? If a user don't have any web browser, which java code he should write (and which classes he needs) to download and read file? Lets say that this is the URL where the file will be downloaded:
http://www.thewebsource.serv/dir1/myfile.txt
So far I have tried to access a url, but in order to download a file what procedure I should follow.
package filedownload;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class FileDownload {

public static void main(String[] args) throws URISyntaxException, IOException {

    Desktop d=Desktop.getDesktop();

    d.browse(new URI("http://www.thewebsource.serv/dir1/myfile.txt"));

    }

}

A: You could use something like this using the URL class:
import java.net.*;
import java.io.*;

public class URLReader {
    public static void main(String[] args) throws Exception {

        URL oracle = new URL("http://www.oracle.com/");
        BufferedReader in = new BufferedReader(
        new InputStreamReader(oracle.openStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    }
}

From java doc tutorials: Link

redpajama_set_name: RedPajamaStackExchange


text:
Q: Force improper comparisons to throw a warning/error in JavaScript I had JavaScript code similar to the following:
var data = {"d": 12345};
for(var i = 0; i < data.length; ++i) {
    console.log(i);
}

I know that this for loop will not execute any cycles because data.length will be 'undefined' and
0 < 'undefined' //false (I think this is false for any int?)

Anyways, while I fixed my code (in my code, data contains an array but I was accidentally referencing data.length instead of data.myarr.length) I'm hoping to avoid such problems in the future - took me quite some time to find this bug.
I have been reading up on strict mode in JavaScript but after messing around with JSFiddle I couldn't get strict mode to throw the above as an error. I tried both making the entire script strict, then, thinking maybe there was a conflict, tried it within its own method and still got nothing.
Is there a way to force "nonsensical" comparisons such as int < "undefined" to throw an error (or even a warning)? Did I miss something with strict mode? Or is the language design supposed to allow such things?

A: There is nothing within Javascript itself that will pick this one up.
I haven't kept track of the latest developments in JS Lint, but I don't know of anything there that would help.
On the other hand, TypeScript handles this situation very well.
Just as head's up -- this isn't something that can change in Javascript without breaking existing code.  There are enough array like objects that have a both a length property and numericly named property names that one iterates over.

*

*The arguments keyword

*Node lists

A: AFAIK, there's no real way to achieve what you're after. since int < undefined is a perfectly fine comparison.
One thing you could do, for this specific issue, is use Array.forEach (MDN). This would throw an error since data.forEach is undefined and attempting to call that as a function will fail (unless you added a "forEach" key on data with a function value, of course):
var data = {"d": 12345};
data.forEach(function(item, index, array){
    console.log(index);
});

Note, that IE < 9 does not have Array.forEach, so you would need to add it to Array's prototype. See more here, including how to do so, at Array.prototype.forEach() on MDN.

A: In ES6, you could use an iterator via for...of, which would result in an error since non-array objects are not iterable:
for (var x of data) { }

You will have make other arrangements if you also want the index.


text:
Q: How to parse a file using AWK I am new to shell scripting and want to use awk to parse a file. I have a log file which looks something like this log.txt where each record name(A,B,C) is shown twice.
A,10.10.250.2,Compliant
A,10.10.250.2,Compliant
B,10.10.250.3,NonCompliant
B,10.10.250.3,Compliant
C,10.10.250.4,NonCompliant
C,10.10.250.4,NonCompliant

I want to merge both the record where record name is same, something like this:
A,10.10.250.2,Compliant, NA,Compliant
B,10.10.250.3, NonCompliant,Yes,Compliant
C,10.10.250.4, NonCompliant,No,NonCompliant

The 4th Column is "NA" when both last column values are Compliant, "Yes" when NonCompliant and "Compliant" and "No" when it is NonCompliant and NonCompliant. 5th column is the last value of second record.
I am trying something like this which is not correct, needs some help
awk -F "," '{if ($1 == $1) print NR}' log.txt

A: How I have done it (and some awk details):

*

*awk reads one line at a time and processes it.

*to compare something with the next line, you can force your script to read the next input line with getline.

*if (condition) { something } else { something else } is used to check conditionals.

*&& performs "and" between two conditions.

That being said, create a file named "script.awk":
BEGIN { FS="," }
{
    compornot=$3
    getline
    if (compornot == "Compliant" && $3 == "Compliant") {
        value = "NA"
    }
    else if (compornot == "NonCompliant" && $3 == "NonCompliant") {
        value = "No"
    }
    else {
        value = "Yes"
    }
    print $1 "," $2 "," compornot "," value "," $3
}

*

*The BEGIN is to establish the field separator as the comma

*then awk reads the firt line

*keeps the third field in variable "compornot".  The 3rd field is "Compliant" or "NonCompliant"

*reads the next input line using getline.  From that point on, the numbered fields refer to that next input line.

*Use if to check if the previous line's third field is "Compliant" or "NonCompliant", and the current line's third field for the same values.

*Depending on the values of the third fields, set variable "value" to "Yes", "No" or "NA".

*Finally print the output.  Remember that $1, $2 and $3 refer to the second line of input here, not the first anymore!

*And the process starts again with the 3rd line of input.

The sequence of processed lines is:

*

*first line, getline, second line

*third line, getline, fourth line

*fifth line, getline, sixth line

*...

So only the odd numbered lines are processed, and the even lines are explicitly read via getline.
To use it, the command is:
awk -f script.awk input.txt


text:
Q: Should I check if file exists before responding via .sendFile()? Say I have this route handler in my Express.js app:
app.get('/files/:name', function (req, res) {
    res.sendfile('path/to/files/' + req.params.name + '.html');
});

This path is used via Ajax on my site. I wonder if I should guard against situations where a file with the requested name does not exist on the server, in which case the server returns a 404 response. I can work with this, i.e. detect the 404 in the browser and act accordingly (e.g. display a message to the visitor). However, I'm not sure if this is a good approach. Is it OK to use the 404 response here, or am I supposed to try to avoid 404 responses if possible. (E.g. I could if a file with the requested name exists on the server and only use .sendFile() if it does.)
I'm worried that performing a manual check would only slow things down as .sendFile() already has this check built-in (i.e. it's possible to avoid this check and instead detect 404 responses in the browser which is what I'm doing right now and it works fine).

A: I would stick with returning a 404 instead, as that's the 404's purpose.I'm not sure there really is any other common/practical alternative.
Good luck.


text:
Q: Best way to parse requested URL in AngularJS I have a URL like:
http://www.something.com/project/edit/987654321
What's the best way to parse the 987654321 part of the URL using AngularJS? Are there any helper functions within Angular? (I'd prefer to not use jQuery)
If I understand it correctly, the routing functions within AngularJS won't work unless you use a # within the URL or enabled HTML5 mode.
We need to parse this URL when the page is first loaded.

A: You can use the $location service's $location#path() function:
# given: url = http://www.something.com/project/edit/987654321
$location.path().split('/').pop();

However, it sounds like you have a routing issue.  Check out the Angular Tutorial on Routing, which shows how to correctly use $routeProvider routes in your app.js configuration.  From the tutorial:
phonecatApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
       when('/phones/:phoneId', {
        templateUrl: 'partials/phone-detail.html',
        controller: 'PhoneDetailCtrl'
      })
      .otherwise( ...)  //omitting remainder of cut/paste

So your app.js would have a route definition like:
ender2050App.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/project/edit/:id', {
        templateUrl: 'partials/editor.html',
        controller: 'EditorCtrl'
      })

And your controller file (i.e., controllers.js) would have the EditorCtrl that injects the $routeParams service to access the id variable.
If you need a more customized parsing option, check out the $parse service.

A: Both the question AND the answer don't respect the title. I landed here trying to search how to parse ANY url in angular. This question is about parsing the requested url. What if I want to parse http://www.google.com ??
Edited it.

A: I'll answer the question based on the title because I landed here looking for a way to parse a url as well. Here's the answer I found on a fiddler page.
var parser = document.createElement('a');
parser.href = "http://www.example.com";
//At this point it's parsed and all the info is on the parser object
console.log(parser.protocol);
console.log(parser.hash);
console.log(parser.hostname);
console.log(parser.port);
console.log(parser.pathname);
console.log(parser.search);

[Update]
I just noticed there's a URL class.
var parsedURL = new URL('http://www.example.com');
console.log(parsedURL.hash);
console.log(parsedURL.protocol);
console.log(parsedURL.host);
//etc


text:
Q: Connection between Activity and remote service on different machine I have implemented an android program with an activity and remote service. The activity is using AIDL to communicate and interact with the service but on a same machine and know that they use IPC mechanism to communicate with each other. Now, I want to put them on separate machines and make connection between them. I'm trying to use socket to make the connection but I don't know how I can do it. How can I start/stop and bind the service, which is running on different machine from activity? The socket is the best choice for this case or there are other better solutions? Do I need to change the Binder class on the Android OS to handle this? I'd appreciate if you could help me to find the solution.
Thanks,
Ra

A:
How can I start/stop and bind the service, which is running on different machine from activity?

You don't.

The socket is the best choice for this case or there are other better solutions?

Direct device-to-device communications is generally not possible over the Internet, unless they are both on the same WiFi routing segment, due to NAT restrictions and the like. This is no different than the issues with direct PC-to-PC communications, with the added challenge that you typically do not control the firewalls involved. Most solutions involve using a server in the middle, acting as a broker or proxy.

Do I need to change the Binder class on the Android OS to handle this?

You need to not use Binder. Binder is IPC (inter-process communication), not RPC (remote procedure calls).


text:
Q: How to convert map with List as key to collection of merged list values? I have a structure that looks like this:
Map<Long, List<Double>

I want to convert it to
List<Double>

where each item in this resulting list represents sum of the values for one key. With example Map:
{1: [2.0, 3.0, 4.0],
 2: [1.5, 10.0]}

I want to achieve as a result:
[9.0, 11.5]

or
[11.5, 9.0]

(order doesn't matter).
Is it possible with Java 8 merge() method?
Actually the case above is a little bit simplified, because in fact my List is parametrized with some complex class and I want to create merged object of this class but I just want to grasp the general idea here.

A: Try:
Map<Long, List<Double>> map = // ...
List<Double> sums = map.values()
                       .stream()
                       .map(l -> l.stream().mapToDouble(d -> d).sum())
                       .collect(Collectors.toList())


text:
Q: GitHub API returning message requires authentication even though I am providing access token I am calling GitHub API https://api.github.com/user/emails from a PHP script. Basically I need GitHub email address of GitHub account used for logging in.
Here is the response I am receiving from API:
{
    "message": "Requires authentication",
    "documentation_url": "https://developer.github.com/v3/users/emails/#list-email-addresses-for-a-user"
}

Even though I am passing access token with header for authorization, I am still receiving requires authentication message.
Here is my code:
    $token = $_GET['token'];
    echo $token;

    $url = "https://api.github.com/user/emails";
    $auth = "Authorization: token ".$token;
    echo $auth;
    $accept = "Accept: application/vnd.github.v3+json";
    $useragent = "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 YaBrowser/16.3.0.7146 Yowser/2.5 Safari/537.36";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array($auth));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array($accept));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array($useragent));

    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

    $res = curl_exec($ch);
    echo ($res);
    curl_close($ch);

Any idea what I am doing wrong here? I am open to any other suggestions for getting GitHub email address associated with logged in GitHub account.

A: Calling curl_setopt() multiple times for CURLOPT_HTTPHEADER won't work because it will overwrite the previous value specified for the CURLOPT_HTTPHEADER field.
You can check this yourself by enabling CURLOPT_VERBOSE, after which you can see what cURL does internally for your request.
You'll have to specify a single array which you supply to CURLOPT_HTTPHEADER:
$headers = array(
    "Authorization: token ".$token,
    "Accept: application/vnd.github.v3+json",
    "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 YaBrowser/16.3.0.7146 Yowser/2.5 Safari/537.36"
);

Now you can just use curl_setopt() to set CURLOPT_HTTPHEADER to include all the headers specified in $headers:
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);


text:
Q: Can NSManagedObject attribute contain a reference to another NSManagedObject? Please forgive me if I do this wrong, it's my first time asking a question on StackOverflow. And... it looks like I don't have enough reputation to include a screenshot, so here is a link instead. Sorry.
>> Image of my xcdatamodel
So anyway, I've got an NSManagedObject subclass called Category, which has a relationship of one-to-many to a subclass called Exercise.
I'd like to have an attribute in my Category class that could contain a reference to a particular "active" Exercise. So my question is: is that possible? And if so, what attribute type would I use?
So far I've been using a simple Int16, and tracking an index attribute on my Exercise objects, but it becomes troublesome when the user starts rearranging cells in a TableView, deleting, etc. The calculations to track the correct object seem really error prone.
Thanks in advance.

A: To visualize @Martin-R's answer, you would add a to-one relationship on your Category entity to your Exercise entity.

Indicated here with the relationship 'activeExercise <- -> inverseActiveExercise'.


text:
Q: Export excel from table tools not showing in IE but working with chrome I'm using jQuery datatable. I need export excel and clolVis(col visible / hide) button in toolbar. I used following code but export excel button is not displaying in IE. I'm using IE10.
function DrawAllFundTable() {
    $("#AllFundsData").empty();
    $("#AllFundsData").html('

');

    AllFundsTable = $('#AllFundsData-Table').dataTable({
        "data": AllFundDataEquity,
        "aaSorting": [[0, "asc"]],
        "dom": 'T<"clear">ft<"bottom"p>',

        "language": {
            "sSearch": "Search"
        },
        "iDisplayLength": 10,
        "columnDefs": [
        { "targets": [0], "searchable": true, "visible": true, "title": "Fund", "sortable": true, "className": "col-xs-3" },
        { "targets": [1], "searchable": true, "visible": false, "title": "Sub Type", "sortable": true, "className": "col-xs-1" },
        .....Other columns....
        ],
       "sDom": '<"toolbar">lC<"H"Tfr>t<"F"p>',

                "oColVis": {
                    "buttonText": "Show / hide columns",
                    "bRestore": true,
                    "sAlign": "left"
                },
                "oTableTools": {
                    "sAlign": "left",
                    "sSwfPath": "assets/swf/copy_csv_xls.swf",

                    "aButtons": [
                        {
                          "sButtonText": "Export to Excel",
                            'sExtends':'xls',
                            'mColumns':'visible', //set which columns here
                            "oSelectorOpts": { filter: 'applied', order: 'current' },
                            "sButtonClass": "back_image"
                        }  ]
                }

  });

}

This working fine with Chrome but I need it should work in IE.
Datatable JS

    <%--
    --%>

CSS
<link href="http://cdn.datatables.net/colvis/1.1.2/css/dataTables.colVis.css" rel="stylesheet" />
    <%-- <link href="http://cdn.datatables.net/colreorder/1.1.3/css/dataTables.colReorder.css" rel="stylesheet" /> --%>
    <link href="http://datatables.net/release-datatables/extensions/TableTools/css/dataTables.tableTools.css"
        rel="stylesheet" />


text:
Q: Can Chrome extensions send messages to other users' browsers? I'm looking for a way to do some key control with a Chrome extension -- let's say that Alice and Bob both have Extension C installed on Chrome. Is there a way for Alice to send a keypress event to Bob through the extension?
https://developer.chrome.com/extensions/messaging#external This article almost covers this use case, but it seems not to be about communicating between two instances of the same extension, more about between two different extensions.


text:
Q: Alamofire 4 multipart request upload progress How should I track progress of my multipart upload request using Alamofire 4?
My encodingCompletion handler:
encodingCompletion: {
        encodingResult in
        switch encodingResult {
        case .success(let uploadRequest, _, _):
            uploadRequest.uploadProgress {
                p in
                print(p.completedUnitCount, p.totalUnitCount)
            }
            break
        case .failure( _):
            print("Failed to encode upload")
        }
}

The error I get says:

Cannot call value of not-function type 'Progress'

A: Try this:
Alamofire.upload(
        multipartFormData: { multipartFormData in
            multipartFormData.append(URL(string: "http://example.com/url1")!, withName: "one")
            multipartFormData.append(URL(string: "http://example.com/url2")!, withName: "two")
        },
        to: "http://example.com/to",
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    debugPrint(response)
                }
                upload.uploadProgress { progress in

                    print(progress.fractionCompleted)
                }
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    )

A: You need to wrap the fractionCompleted, totalUnitCount and completedUnitCount with a cast to Int or Float (depending on what you need).
It works!
source: https://github.com/Alamofire/Alamofire/issues/1652#issuecomment-259020449


text:
Q: Different Firebird query results from dev machine and production server (cyrillic characters) I'm connecting to a remote Firebird 2.1 DB Server and i'm querying data that contains some cyrillic characters togeather with some latin ones.
The problem is that when i deploy the app on the production system, the cyrillic characters look like this: ÂÚÇÄÓØÍÀ. In addition, when trying to log what comes in from the DB, the cyrillic content is just skipped in the log file (i.e. i'm not seeing the ÂÚÇÄÓØÍÀ at all).
At this point i'm not sure whether i'm getting inconsistent data from the DB OR the production environment can't recognize those characters for some reason.
I've been wandering about for quite some time now and ran out of ideas, so any hints would be great.
The Dev machine that i use runs Windows 7 Ultimate SP1. My system locale is Bulgarian
The Production Server is accessed via Paralles Plesk Panel, and i'm not sure what's underneath.

A: If you did not specify any character set in your connection properties, then almost all Firebird drivers default to connection character set NONE. This means that Firebird will send the bytes of strings as they are stored in the database without any conversion, on the other side the driver will use the default system character set to convert those bytes to strings. If you use multiple systems with various default system character sets you will get different results.
You should always explicitly specify a connection characterset (WIN1251 in your case), unless you really know what you are doing.


text:
Q: Windows application - Just Starting I am planing to make an windows app and I don't know where to start, which it's the best language for succeeding this.
My goal it's the following :

*

*an app for windows with an UI that I can customize however I want

*the app must be able to use very big database , because the plans for my app will that it will have something like 500 000 entries each day.

*the app must be able to connect with different other hardware like : thermal printer, laser printer, barcode scanner etc.

I did already programed in PHP and i am still doing it so I know some principles, I use PHP with HTML, JS, CSS and MySQL or MSSQL.
Can someone give an idea from where should i start and with what?
Thank you very much.

A: You can start with C# language, which is one of the languages in .Net framework.
Here is a link for how to create a simple Windows application.
Then you can get known to .Net framework, on which Windows apps rely here, this is a really great video tutorial if you are a beginner.
Then for databases and other things here is another article which shows you how connect your data to application.
Or you can choose WPF ( Windows Presentation Foundation) depending on what kind of program you are going to develop.
Here is a tutorial for WPF.
Start with these things, and you can make your program successfully :)


text:
Q: Do we need admin priviledge to install NativeHost client of chrome extension? I am developing a chrome extension which communicates to a NativeHost client installed under NativeHost dorectory on Mac, but to install it on the Windows we need to change the registory values. Do we need admin privildge for that**?** if yes, then doe we have any way to bypass this**?**
because my users may/maynot have admin privildge to use my extension.

A: As you can add native messaging hosts in the Current User key (HKCU/HKEY_CURRENT_USER) then you do not need admin privilege for that.
It would be installed only for that user.


text:
Q: django cms permissions per language It is very easy to give permissions to edit a specific page in django cms
However, I didn't find a way to give a permission to edit a page in a certain language.
It's a very common scenario, I have my Spanish, Russian and English editors, and I want that everyone will be able to edit only the pages in their language.
Is there a way of doing it that i'm missing? and if not, what can be done to solve it?

A: At this moment there is an overhaul done of the page permission in Django CMS. One of the things they want to solve is Permission per language.
https://github.com/divio/django-cms/issues/4598
If everything goes well, it will be released in DjangoCMS 3.4

A: As of today, there is no way to set permissions on a page+language basis.
The remaining options are to submit a feature request or fork django-cms and implement on your own.


text:
Q: How can I change the font beyond the ones in options in Git Bash? I want to use the Hack Nerd Font for Git Bash on Windows.
I have the font installed, but it doesn't appear in options. If I run the command mintty -o Font="Hack NF", it does work in a new mintty window, but if I provide the -o Font option to git-bash.exe itself, it doesn't work. Is there a way to do this?

A: According to the issue tracker at mintty they only look at fonts that are flagged as monospace.
I found an issue against Roboto Mono asking for the 'isFixedPitch' flag to be set for the font, so it is not an uncommon problem.
You can specify the font manually in the .minttyrc file located in your home directory.
For example I tried this and it works.
FontHeight=16
Font=Hack Nerd Font


text:
Q: Asynchronous jQuery Upload Still Seems to Upload Something to Heroku I have a fairly simple Rails app running on Heroku where end users can upload two photos and receive a link to the photo via email and SMS.
The app was originally running Paperclip in real-time and timing out sometimes because of Heroku's 30-second limit. I switched to jQuery Upload and S3 to upload the images prior to hitting submit to create the customer, with Paperclip as a delayed job after the fact. This works perfectly -- except it continues to time out upon #create, and when I look in the lower left of my browser it says "Uploading (XX%)" as though it is uploading the already-uploaded files upon #create. I am pulling my hair out.
Again, the photos load fine to S3. On a fast connection, this does not time out, and everything works fine. On a slower connection, it times out upon hitting Submit on the form (after images are uploaded successfully).
Code below. Very appreciative if anyone sees what I am missing - why would this form be trying to submit the photos again?
#Controller

def create
    @s3_direct_post = S3_BUCKET.presigned_post(key: "photos/#{SecureRandom.uuid}/${filename}", success_action_status: 201, acl: :public_read)

if params[:customer][:sms]
  params[:customer][:sms].gsub!(/[\s\-\(\)]+/, '')
end

@customer = current_salesperson.customers.build(customer_params)

if @customer.direct_upload_photo2_url?
  @customer.turkee_status = "ready_to_send"
end

respond_to do |format|
  if @customer.save
    @customer.queue_processing

    unless @customer.email.blank?
      CustomerMailer.delay.welcome_email(@customer)
    end

    unless @customer.sms.blank?
      send_sms
    end

    if params[:fbemail]
      CustomerMailer.post_to_facebook(@customer).deliver
    end
    format.html { redirect_to @customer, notice: 'Customer was successfully created.' }
    format.json { render action: 'show', status: :created, location: @customer }
  else
    format.html { render action: 'new' }
    format.json { render json: @customer.errors, status: :unprocessable_entity }
      end
    end
  end

Relevant Model
class Customer < ActiveRecord::Base

  has_attached_file :photo,
          :styles => { :thumb => "228x152#" },
          :storage => :s3,
          :s3_credentials => {
            :bucket => ENV['S3_BUCKET_NAME'],
            :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
            :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
          },
          :url =>  ":s3_domain_url",
          :path => "photos/:owner_id/:id:hash:style.:extension",
          :hash_secret => "XXX",
          :region => "us-west-2",
          :s3_host_name => "s3.amazonaws.com",
          :default_url => "https://s3-us-west-2.amazonaws.com/missing.jpg"

def queue_processing
        Customer.delay.send_to_paperclip(id)
      end

Form:

 <%= form_for(@customer, :html => { class: "directUpload" }) do |f| %>   <% if @customer.errors.any? %>

<%= pluralize(@customer.errors.count, "error") %> prohibited this customer from being saved:

          <% @customer.errors.full_messages.each do |msg| %>
            <%= msg %>

          <% end %>

   <% end %>

    <%= f.label :name, "Customer Name" %>
    <%= f.text_field :name, class: 'form-control', :disabled => @disabled %>

    <%= f.label :email %>
    <%= f.text_field :email, class: 'form-control' %>

    <%= f.label :sms, 'Cell Phone # (for one-time SMS)' %>
    <%= f.text_field :sms, class: 'form-control' %>

   <%= f.label :direct_upload_photo2_url, 'Photograph the Second Part' %>   <%= f.file_field :direct_upload_photo2_url, class: 'form-control' %>

   <%= f.label :direct_upload_photo_url, 'Take or Choose a LANDSCAPE Photo' %>   <%= f.file_field :direct_upload_photo_url, class: 'form-control' %>

      <input id="fbemail" name="fbemail" type="checkbox" value="1"> Post to Facebook

    <%= f.button "Submit", class: 'btn btn-primary' %>

<% end %>

The error in the logs is:
    Jan 29 06:14:20 myname app/web.1: Started POST "/customers" for 70.192.215.71 at 2015-01-29 14:14:19 +0000
Jan 29 06:14:20 myname app/web.1:   Parameters: {"utf8"=>"✓", "authenticity_token"=>"ypEWqX54OUBUGTm4GNtfM1QjSnqxZHB4bFcKw==", "customer"=>{"name"=>"John ", "email"=>"XXX@gmail.com", "sms"=>"206XXXXXXX", "direct_upload_photo2_url"=>"//myname.s3.amazonaws.com/photos/380057ca-f611-4541-80a1-6850560de612/image.jpg", "direct_upload_photo_url"=>"//myname.s3.amazonaws.com/photos/380057ca-f611-4541-80a1-6850560de612/image.jpg", "second_salesperson_id"=>"", "owner_id"=>"26"}, "button"=>""}
Jan 29 06:14:20 myname app/web.1: Processing by CustomersController#create as HTML
Jan 29 06:14:20 myname app/web.1:   Salesperson Load (1.9ms)  SELECT  "salespeople".* FROM "salespeople" WHERE "salespeople"."id" = $1  ORDER BY "salespeople"."id" ASC LIMIT 1  [["id", 39]]
Jan 29 06:14:20 myname app/web.1:    (2.2ms)  BEGIN
Jan 29 06:14:20 myname app/web.1:   SQL (3.7ms)  UPDATE "salespeople" SET "customers_count" = COALESCE("customers_count", 0) + 1 WHERE "salespeople"."id" = $1  [["id", 39]]
Jan 29 06:14:20 myname app/web.1:    (0.7ms)  BEGIN
Jan 29 06:14:20 myname app/web.1:    (2.7ms)  COMMIT
Jan 29 06:14:20 myname app/web.1:   SQL (6.0ms)  INSERT INTO "customers" ("name", "email", "owner_id", "sms", "direct_upload_photo_url", "direct_upload_photo2_url", "salesperson_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING "id"  [["name", "John "], ["email", "XXX@gmail.com"], ["owner_id", 26], ["sms", "206XXXXXXX"], ["direct_upload_photo_url", "//myname.s3.amazonaws.com/photos/380057ca-f611-4541-80a1-6850560de612/image.jpg"], ["direct_upload_photo2_url", "//myname.s3.amazonaws.com/photos/380057ca-f611-4541-80a1-6850560de612/image.jpg"], ["salesperson_id", 39], ["created_at", "2015-01-29 14:14:20.443471"], ["updated_at", "2015-01-29 14:14:20.443471"]]
Jan 29 06:14:20 myname app/worker.1:   Delayed::Backend::ActiveRecord::Job Load (2.7ms)  UPDATE "delayed_jobs" SET locked_at = '2015-01-29 14:14:20.518245', locked_by = 'host:b4e4f686-7966-4131-9609-61b493f6ca44 pid:3' WHERE id IN (SELECT  "delayed_jobs"."id" FROM "delayed_jobs" WHERE ((run_at <= '2015-01-29 14:14:20.517036' AND (locked_at IS NULL OR locked_at < '2015-01-29 10:14:20.517201') OR locked_by = 'host:b4e4f686-7966-4131-9609-61b493f6ca44 pid:3') AND failed_at IS NULL)  ORDER BY priority ASC, run_at ASC LIMIT 1 FOR UPDATE) RETURNING *
Jan 29 06:14:20 myname app/web.1:    (2.8ms)  COMMIT
Jan 29 06:14:20 myname app/web.1:   SQL (1.2ms)  INSERT INTO "delayed_jobs" ("handler", "run_at", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["handler", "--- !ruby/object:Delayed::PerformableMethod\nobject: !ruby/class 'customer'\nmethod_name: :send_to_paperclip\nargs:\n- 111\n"], ["run_at", "2015-01-29 14:14:20.521860"], ["created_at", "2015-01-29 14:14:20.522421"], ["updated_at", "2015-01-29 14:14:20.522421"]]
Jan 29 06:14:20 myname app/web.1:    (0.7ms)  BEGIN
Jan 29 06:14:20 myname app/web.1:    (3.2ms)  COMMIT
Jan 29 06:14:20 myname app/web.1:   SQL (3.0ms)  INSERT INTO "delayed_jobs" ("handler", "run_at", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["handler", "--- !ruby/object:Delayed::PerformableMailer\nobject: !ruby/class 'CustomerMailer'\nmethod_name: :welcome_email\nargs:\n- !ruby/object:customer\n  raw_attributes:\n    id: '111'\n    name: 'John '\n    email: XXXX@gmail.com\n    created_at: 2015-01-29 14:14:20.443471733 Z\n    updated_at: 2015-01-29 14:14:20.443471733 Z\n    salesperson_id: 39\n    photo_file_name: \n    photo_content_type: \n    photo_file_size: \n    photo_updated_at: \n    views: '0'\n    owner_id: '26'\n    photo26: \n    tweet_count: '0'\n    facebook_count: '0'\n    photo2_file_name: \n    photo2_content_type: \n    photo2_file_size: \n    photo2_updated_at: \n    second_salesperson_id: ''\n    turkee_task_id: \n    turkee_status: not_sent\n    make: \n    model: \n    year: \n    sms: '206XXXXXXX'\n    direct_upload_photo_url: //myname.s3.amazonaws.com/photos/380057ca-f611-4541-80a1-6850560de612/image.jpg\n    direct_upload_photo2_url: //myname.s3.amazonaws.com/photos/380057ca-f611-4541-80a1-6850560de612/image.jpg\n  attributes: !ruby/object:ActiveRecord::AttributeSet\n    attributes: !ruby/object:ActiveRecord::LazyAttributeHash\n      types:\n        id: &3 !ruby/object:ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Integer\n          precision: \n          scale: \n          limit: \n          range: !ruby/range\n            begin: -2147483648\n            end: 2147483648\n            excl: true\n        name: &1 !ruby/object:ActiveRecord::Type::String\n          precision: \n          scale: \n          limit: 255\n        email: *1\n        created_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter\n          subtype: &2 !ruby/object:ActiveRecord::ConnectionAdapters::PostgreSQL::OID::DateTime\n            precision: \n            scale: \n            limit: \n        updated_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter\n          subtype: *2\n        salesperson_id: *3\n        photo_file_name: *1\n        photo_content_type: *1\n        photo_file_size: *3\n        photo_updated_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter\n          subtype: *2\n        views: *3\n        owner_id: *3\n        photo26: *1\n        tweet_count: *3\n        facebook_count: *3\n        photo2_file_name: *1\n        photo2_content_type: *1\n        photo2_file_size: *3\n        photo2_updated_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter\n          subtype: *2\n        second_salesperson_id: *3\n        turkee_task_id: *3\n        turkee_status: *1\n        make: *1\n        model: *1\n        year: *1\n        sms: &4 !ruby/object:ActiveRecord::Type::String\n          precision: \n          scale: \n          limit: \n        direct_upload_photo_url: *4\n        direct_upload_photo2_url: *4\n      values:\n        id: \n        name: \n        email: \n        created_at: \n        updated_at: \n        salesperson_id: \n        photo_file_name: \n        photo_content_type: \n        photo_file_size: \n        photo_updated_at: \n        views: '0'\n        owner_id: \n        photo26: \n        tweet_count: '0'\n        facebook_count: '0'\n        photo2_file_name: \n        photo2_content_type: \n        photo2_file_size: \n        photo2_updated_at: \n        second_salesperson_id: \n        turkee_task_id: \n        turkee_status: not_sent\n        make: \n        model: \n        year: \n        sms: \n        direct_upload_photo_url: \n        direct_upload_photo2_url: \n      additional_types: {}\n      materialized: true\n      delegate_hash:\n        id: !ruby/object:ActiveRecord::Attribute::FromUser\n          name: id\n          value_before_type_cast: '111'\n          type: *3\n          value: 111\n        name: !ruby/object:ActiveRecord::Attribute::FromUser\n          name: name\n          value_before_type_cast: 'John '\n          type: *1\n          value: 'John '\n        email: !ruby/object:ActiveRecord::Attribute::FromUser\n          name: email\n          value_before_type_cast: XXX@gmail.com\n          type: *1\n          value: XXX@gmail.com\n        created_at: !ruby/object:ActiveRecord::Attribute::FromUser\n          name: created_at\n          value_before_type_cast: 2015-01-29 14:14:20.443471733 Z\n          type: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter\n            subtype: *2\n          value: 2015-01-29 14:14:20.443471733 Z\n        updated_at: !ruby/object:ActiveRecord::Attribute::FromUser\n          name: updated_at\n          value_before_type_cast: 2015-01-29 14:14:20.443471733 Z\n          type: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter\n            subtype: *2\n          value: 2015-01-29 14:14:20.443471733 Z\n        salesperson_id: !ruby/object:ActiveRecord::Attribute::FromUser\n          name: salesperson_id\n          value_before_type_cast: 39\n          type: *3\n          value: 39\n        photo_file_name: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: photo_file_name\n          value_before_type_cast: \n          type: *1\n          value: \n        photo_content_type: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: photo_content_type\n          value_before_type_cast: \n          type: *1\n          value: \n        photo_file_size: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: photo_file_size\n          value_before_type_cast: \n          type: *3\n          value: \n        photo_updated_at: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: photo_updated_at\n          value_before_type_cast: \n          type: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter\n            subtype: *2\n          value: \n        views: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: views\n          value_before_type_cast: '0'\n          type: *3\n          value: 0\n        owner_id: !ruby/object:ActiveRecord::Attribute::FromUser\n          name: owner_id\n          value_before_type_cast: '26'\n          type: *3\n          value: 26\n        photo26: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: photo26\n          value_before_type_cast: \n          type: *1\n          value: \n        tweet_count: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: tweet_count\n          value_before_type_cast: '0'\n          type: *3\n          value: 0\n        facebook_count: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: facebook_count\n          value_before_type_cast: '0'\n          type: *3\n          value: 0\n        photo2_file_name: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: photo2_file_name\n          value_before_type_cast: \n          type: *1\n          value: \n        photo2_content_type: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: photo2_content_type\n          value_before_type_cast: \n          type: *1\n          value: \n        photo2_file_size: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: photo2_file_size\n          value_before_type_cast: \n          type: *3\n          value: \n        photo2_updated_at: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: photo2_updated_at\n          value_before_type_cast: \n          type: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter\n            subtype: *2\n          value: \n        second_salesperson_id: !ruby/object:ActiveRecord::Attribute::FromUser\n          name: second_salesperson_id\n          value_before_type_cast: ''\n          type: *3\n          value: \n        turkee_task_id: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: turkee_task_id\n          value_before_type_cast: \n          type: *3\n          value: \n        turkee_status: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: turkee_status\n          value_before_type_cast: not_sent\n          type: *1\n          value: not_sent\n        make: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: make\n          value_before_type_cast: \n          type: *1\n          value: \n        model: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: model\n          value_before_type_cast: \n          type: *1\n          value: \n        year: !ruby/object:ActiveRecord::Attribute::FromDatabase\n          name: year\n          value_before_type_cast: \n          type: *1\n          value: \n        sms: !ruby/object:ActiveRecord::Attribute::FromUser\n          name: sms\n          value_before_type_cast: '206XXXXXXX'\n          type: *4\n          value: '206XXXXXXX'\n        direct_upload_photo_url: !ruby/object:ActiveRecord::Attribute::FromUser\n          name: direct_upload_photo_url\n          value_before_type_cast: //myname.s3.amazonaws.com/photos/380057ca-f611-4541-80a1-6850560de612/image.jpg\n          type: *4\n          value: //myname.s3.amazonaws.com/photos/380057ca-f611-4541-80a1-6850560de612/image.jpg\n        direct_upload_photo2_url: !ruby/object:ActiveRecord::Attribute::FromUser\n          name: direct_upload_photo2_url\n          value_before_type_cast: //myname.s3.amazonaws.com/photos/380057ca-f611-4541-80a1-6850560de612/image.jpg\n          type: *4\n          value: //myname.s3.amazonaws.com/photos/380057ca-f611-4541-80a1-6850560de612/image.jpg\n  new_record: false\n"], ["run_at", "2015-01-29 14:14:20.551569"], ["created_at", "2015-01-29 14:14:20.551905"], ["updated_at", "2015-01-29 14:14:20.551905"]]
Jan 29 06:14:20 myname app/web.1:   owner Load (2.4ms)  SELECT  "owners".* FROM "owners" WHERE "owners"."id" = $1 LIMIT 1  [["id", 26]]
Jan 29 06:14:21 myname app/web.1: SMS: To: +1206XXXXXXX Body: "Check out your photo at http://url/name/111"
Jan 29 06:14:21 myname app/web.1: E, [2015-01-29T14:14:20.779161 #3] ERROR -- : worker=0 PID:6 timeout (30s > 29s), killing
Jan 29 06:14:21 myname app/web.1: E, [2015-01-29T14:14:20.808642 #3] ERROR -- : reaped #<Process::Status: pid 6 SIGKILL (signal 9)> worker=0
Jan 29 06:14:21 myname heroku/router: at=error code=H13 desc="Connection closed without response" method=POST path="/customers" host=www.url.com request_id=e02c7966-0e1c-44a6-b624-72c882683507 fwd="70.192.215.71" dyno=web.1 connect=1ms service=29974ms status=503 bytes=0

A: I ended up moving the jQuery Upload into its own separate form above the Rails create form. This fixed it.


text:
Q: Does Production Electron need node_modules/ Been working on a Electron and React app for the past 4 months and we are getting close to releasing it. This is my first production Electron app and I noticed the unpacked size was very large and the app.asar contained over 100mb of node_modules.

*

*My colleague wrote the electron-builder config (probably just boilerplate code - Python dev) and it includes the react build/ and node_modules/ in the electron build. I understand React doesn't need any Node_modules once it is built because all of the code is bundled and a majority of these node_modules are for the react app.

*I would assume it would be the same after electron is built/compiled. Or is it needed for nodejs deps? For the testing I did today I moved all of the react app's deps into devDeps so electron-builder doesn't include them. It reduced the unpacked size by over 80% (over 500mb to under 150mb) because it included a bunch of ui stuff like icons that were tree shaken for the built react app. Inspecting the source tree for the built react app is under 2mb for node_modules.

TLDR: does my built electron app actually need node_modules included in the build (built for linux and armv7l)? I know the react app does not after being built. And my temp work around has been moving my react deps to devDependencies so electron-builder ignores them.
-- (I know this is not best practice because deploying the react app alone with a lot of services will only read the production dependencies - but shouldn't be an issue for our app's deployment)

A: No, you should not need to include your node_modules in the electron build. Most of the required dependencies should be transpiled into the build folder.
Docs here: https://www.electronjs.org/docs/latest/tutorial/using-native-node-modules
You should also be able to test this our pretty easily. Remove node_modules from the build target and test after running build.


text:
Q: A block connected to a string is kept on a rough surface. If an external force is applied, which force would counteract first- tension or friction? I imagine the title wasn't very clear, so here is the question in a bit more detail. Consider a block attached to a nonextensible and massless string as shown in the figure below. The static friction is $f_s$ and an external force of magnitude $F$ is applied to the block such that the system is at rest. The block is connected to a nonextensible, massless ideal string. The string is such that, even when no external force $F$ is applied, it remains taut, with the tension $T$ being zero, of course.

Now, suppose the surface underneath the block was frictionless. Then, if a force $F$ was applied such that the system would be at rest, then the applied force would be countered by the tension in the string, $T$. As we will increase the force, the tension will also increase, until finally the force is strong enough to break the string and accelerate the block.
Consider an alternative situation in which there is no string attached to the block, but the surface was not frictionless and instead the maximum value of static friction was $f_{s, max}$. Then, as we increase the force $F$, the block will remain at rest as the force would be countered by the static friction, up to its maximum value, after which the block will slide and begin to accelerate.
So, now here's the question. Consider that both the situation were to happen together, that is the surface was not frictionless, and the string was attached to the block as described in the previous situation. Then, we can all agree, that, if the block was at rest then, $ F = T + f_s $.
But which force, amongst the static friction $f_s$ and the tension $T$ will counter the effect of the applied force $F$ first ? That is, if the force $F < min(T, f_s)$ then which force will counter the effect of the applied force ? Tension or static friction ?
We were given this question today in our JEE prep class (for those who don't know, JEE is a prestigious examination in India, which serves as an entrance examination for engineering students for admission in Indian colleges). Our sir told us that a question as described above was asked in one of the previous years JEE question papers, and the answer to the question was that friction will counteract the applied force before tension. When asked for reason, he told us that no reason was put forward by the people who designed the question, and since then (for the past 10 or so years) this question was taught as friction will act before tension, all over India, without explaining the reasoning behind it.
I try to come up with my own reasoning, I don't know if it is right or wrong, but here it is. I think that, as you can see from the diagram, the force is applied on the extreme left-most point of the block. If we were to imagine, the block as a rigid body comprised of multiple smaller rigid bodies (atoms and molecules) then we can think of the force $F$ pulling on the leftmost point, which then pulls on the point immediately next to and so on and so forth, until it finally reaches the rightmost point at which the string is attached. It is only now that the tension in the string starts pulling the rightmost point, which then pulls the point to the left of it and so on and so forth. However, as friction will act as soon as the first point is pulled by the applied force, friction will act before the tension.
But this raises more questions than it explains. Suppose that this were true, but then what would happen when the rightmost point (the one attached to the string) is pulled by the point before it? Is that force countered by the tension and friction evenly or only by friction? Or only by tension? Or unevenly by both the forces?
I don't think that my reasoning is correct, but thought still I might share it with you, as you might understand where I am coming from.
Please explain this to me. Can you explain the conceptual reasoning, the intuition behind the answer, as well as establish your answer rigorously using mathematics ?
Thanks in advance.

A: In my opinion, the requirement that the string be nonextensible creates conceptual issues.
On the one hand, it is stated that the string is nonextensible. On the other hand, it is stated on the diagram the "External force $F$ is applied such that the block remains at rest". The problem is if the string is nonextensible, and initially has no slack, then the block cannot move to the left, i.e., it will always be "at rest", regardless of the force $F$ to the left.
But more importantly, it makes it difficult to explain (1) why the static friction force counters the applied force before the tension in the string and (2) why when equilibrium is reached the friction force no longer exists.
To facilitate the answers to these questions I will replace the string with an ideal spring (see the figures below). An ideal spring, like the string, is massless. But unlike the string, it is extensible to the degree allowed by the spring constant. The magnitude of the tension in the spring is equals the magnitude of its restoring force, or $T=k\Delta x$ where $k$ is the spring constant and $\Delta x$ is its extension beyond the "relaxed" stated.
Now consider the following where the block is considered a rigid (nonextensible) body:

*

*The spring, like the string, is initially relaxed so there is no tension. FIG 1 shows the block with no external force and the relaxed spring attached to the wall

*In Fig 2 we gradually apply an increasing external force $F$ that is less than the maximum static friction force. Since the block cannot move, the spring cannot extend and thus the tension in the spring is still zero. This explains, for a physically real scenario, why the applied force $F$ is countered first by the static friction force.

*In FIG 3 the applied force reaches the maximum static friction force and the friction force becomes kinetic friction, which is generally considered constant. Since kinetic friction is usually less than static friction, if the applied force $F$ is maintained at the value of the maximum static friction there will initially be a net force to the left causing the block to move to the left. (Note that actual value of the friction force during the transition from static to kinetic is undefined for the standard model of friction).  At the same time, however, the spring extends creating an opposing tension force. So during this phase before the extension of the spring is a maximum, we have
$$F-f_{k}> T$$
$$\mu_{s}mg-\mu_{k}mg>k\Delta x$$
and the block is moving to the left.

*When the extension of the spring is such that the tension in the spring equals the applied force $F$, it's extension is maximized and we have

$$F=T=k\Delta x_{max}$$
Substituting into the first equation,
$$f_{k}=0$$
Meaning there is no net force for friction to oppose.
Note that in this example, the stiffer the spring (the greater $k$ is) the less the block needs to move before the tension equals the applied force, i.e., the quicker the tension rises. The nonextensible string is simply a spring with an infinite $k$.
Hope this helps.


text:
Q: como atribuir codigo html na variavel javascript? quero atribuir esse codigo

...

a uma variavel JS, tipo isso :
var Code = '
...

A: Se tiver apenas um elemento com a class na página, você pode fazer assim:
var Code = document.body.querySelector(".menu");

Se forem mais, você deverá especificar um índice, com querySelectorAll:
var Code = document.body.querySelectorAll(".menu")[1];

O onde o [1] representa o segundo elemento da página com a classe .menu.

Os exemplos acima irão selecionar o elemento como um objeto. Se quiser pegar o HTML, adicione .outerHTML:
var Code = document.body.querySelector(".menu").outerHTML;

ou
var Code = document.body.querySelectorAll(".menu")[1].outerHTML;

Se quiser pegar o HTML interno do elemento:
var Code = document.body.querySelector(".menu").innerHTML;

ou
var Code = document.body.querySelectorAll(".menu")[1].innerHTML;

Lembrando que o índice [1] é um exemplo que se refere ao segundo elemento com a
  classe .menu, quando houverem mais de 1 elemento com a mesma classe.

A: Se você quer pegar um código html e atribui a uma variável chame ela por um id, classe, nome da tag ou algo assim:

var code = document.getElementsByClassName('menu')[0]

console.log(code)

...


text:
Q: Find one-dimensional distribution function $F(y\mid t)$ of random process $Y(t)$ $ Y(t)=tZ^2;\quad Z\sim U(-2;2);  \quad t\ge0. \quad$
I need to
1) find one-dimensional distribution function $F(y|t)$ of random process $Y(t)$.
2) calculate probability that trajectory of the process at moment $t=4$ will intersect interval $[9;25]$.
U is a continuous uniform distribution.
What I've done so far:
1) Probability density function:
$p(y) =
\begin{cases}
{1 \over 4},  & y\in(-2;2) \\
0, & y\notin(-2;2)
\end{cases} $
Cumulative distribution function:
$F(y) =
\begin{cases}
0,  & y\le-2 \\
y+2 \over 4, & -2\lt y\lt 2  \\
1, & y \ge 2
\end{cases} $
$ F(y\mid t)=P(Y(t)\le y)=P(tZ^2 \le y)=P(|Z| \le \sqrt{y \over t})=F_Z( \sqrt{y \over t}) -F_Z( -\sqrt{y \over t})$
$F_Z( \sqrt{y \over t}) =
\begin{cases}
0,  & \sqrt{y \over t}\le-2 \\
\sqrt{y \over t} +2 \over 4, & -2\lt \sqrt{y \over t}\lt 2  \\
1, & \sqrt{y \over t} \ge 2
\end{cases} $
$F_Z( \sqrt{y \over t}) =
\begin{cases}
0,  & \text{no solution} \\
\sqrt{y \over t} +2 \over 4, & 0 \le y \le 4t  \\
1, & y \ge 4t
\end{cases} $
$F_Z( -\sqrt{y \over t}) =
\begin{cases}
0,  & y \ge 4t \\
\sqrt{y \over t} +2 \over 4, & 0\le y\lt 4t  \\
1, & \text{no solution}
\end{cases} $
2) $P(4Z^2 \in [9;25])=P(Z^2 \in [{9 \over 4};{25 \over 4}])=P(|Z|\in [{3 \over 2} ; {5 \over 2}])=\cdots$
Can someone explain how to solve the 2nd part? I tried to follow the example I have with two moments and two intervals but I don't seem to understand it either. I can post the example as well if needed. It is solved in two ways.
Edit:
How do I calculate $P(|Z|\in [{3 \over 2} ; {5 \over 2}])$ ?

A: Compare:

*

*$Z\sim U(-2;2)$

*How do I calculate $P(|Z|\in [{3 \over 2} ; {5 \over 2}])$ ?

Is this really a problem? Then we have a problem (Houston)... :-)


text:
Q: Formatting y-axis tick text plot The tick text of the y axis in my matplotlib plot has too many decimal digits.
How can I format the text to show two decimal digits only.
I.E. I would like to convert 10.39658602 into 10.40
I've already tried with:
ax.get_yaxis().set_major_formatter(matplotlib.ticker.FormatStrFormatter('%5.2f'))
but the decimal digits are set to 0 (the previous number becomes 10.00).
Here is some image. Before:

After:

Edit: I'm including also an example of the code to reproduce the problem.
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
lineObjects = plt.plot(epochs, data1, 'rs',
                       epochs, data2, 'b^',
                       epochs, data3, 'gv',
                       epochs, data4, 'ko', )
# also %.2f does not work as intended
ax.get_yaxis().set_major_formatter(matplotlib.ticker.FormatStrFormatter('%5.2f'))
plt.show()

I'm using Python 3.6 on Anaconda. data1, data2, data3, data4 are NumPy ndarrays of type str_, I've already tried to convert them to float, but the results are similar.

A: Use this formatting.
ax.yaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter('%.2f'))


text:
Q: Ruby: how to parse e-mail mime from the stdin Anyone know how I can parse the E-mail MIME from Ruby when the input is from STDIN? I have found a gem called "mail" which looks really nice but so far as I can see it's able to read a mail only from the file:
require 'mail'
mail = Mail.read('/path/to/message.eml')

This is how I'm testing it:
# First one is from stdin:
require 'mail'
mail = Mail.new($stdin.readlines)
p mail.from
p mail.to

returns:
nil
nil
# This one is from the file:
mail2 = Mail.new("my_email.txt")
p mail2.from
p mail2.to

returns:
nil
nil
# The same file but I'm using Mail.read:
mail3 = Mail.read("my_email.txt")
p mail3.from
p mail3.to

returns:
["test@gmail.com"]
["test2@gmail.com"]
STDIN I'm testing like:
# cat my_email.txt | ruby code.rb

So the method Mail.read works fine with my e-mail, but when I want to put my stdin to the Mail.read I have:
mail/mail.rb:176:in `initialize': no implicit conversion of Array into String (TypeError)

I know that I can save that file from stdin to the temp folder and then open it by Mail.read but I don't want to do this in that way since it will be slow.
The full url to the gem is: https://github.com/mikel/mail

A: readlines returns an array... of lines! You might want to try read on ARGF which is the input provided by $stdin instead.
mail = Mail.new ARGF.read

See the relevant documentation.

A: IO#readlines produces an array. You want a string there:
# readmail.rb
require 'mail'
mail = Mail.new(STDIN.read)
p mail.from
p mail.to

# mail.eml
From: bob@test.lindsaar.net
To: mikel@test.lindsaar.net
Subject: This is an email

This is the body

# command line
$ ruby readmail.rb < mail.eml
# => ["bob@test.lindsaar.net"]
# => ["mikel@test.lindsaar.net"]


text:
Q: Using haproxy in front of Apache, reported SERVER_PORT wrong I'm using haproxy 1.5-dev19 in front of Apache 2.4 (on Ubuntu 12.04).
Haproxy is listening on ports 80 and 443, and Apache is listening on 8080 — yet, when I output $_SERVER['SERVER_PORT'] from PHP (5.5), it shows as 80, when it should be 8080.
That is, I would assume PHP sees the Apache server port, but that doesn't seem to be the case.
What could I be overlooking?

A: Setting UseCanonicalPhysicalPort On and UseCanonicalName On in the Apache configuration file will cause PHP to report the correct server port.
It's possible haproxy "spoofs" its forwarded requests so that PHP sees the requests as port 80 instead of 8080.


text: Q: how to dynamically save and load find-tuned models server-side? I would like to fine-tune a model specifically to a users input (f.e stable diffusion) and save that tuned model persistently on cloud storage or s3 after  - then i want to be able to (down)load it back into memory for inference anytime later - how would i go about that setup? Also are there some serverless setups to design this for autoscalability? (correct me on any level if there are wrong assumptions)


text:
Q: Dynamically build simply-typed java objects from JSON REST I am consuming a REST API using Retrofit. I can receive the JSON object and print it. I want to dynamically convert it to a nested simply typed Java object.
i.e. I want the Java object to consist of nested Map, Array, String, Int/Double, Boolean, and null built dynamically based on the JSON object (similar to json.loads in Python). I'm attempting to use Jackson for this. Here's what I have:
API api = APIHandler.getApiInterface();
api.getFoo(new Callback<Object>() {
    @Override
    public void success(Object o, Response response) {
        Log.i("Tag", "Print JSON " + o.toString());

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> json = mapper.readValue(o, Map.class);

    }

    @Override
    public void failure(RetrofitError error) {

    }
});

The JSON is logged but the line mapper.readValue(o, Map.class); gives a "cannot resolve method" error. Changing the return type to String seems to cause more problems.
What's the right way to do this?

A: Insted Object o your shoud use custom class. So use new Callback<MyMapper> instead new Callback<Object>.
e.g.
public class MyMapper {
    public String name;
    public int age;
}


text:
Q: ColdFusion Query -- Get index of column by column name I have a column name and, for the sake of SpreadsheetSetCellFormula, I want to get the index of that column from its name.  This is important for expandability, as columns may be added or taken away in the future.
When I use queryName.ColumnList, ColdFusion automatically alphabetizes the list.  However, passing it into SpreadsheetAddRows dumps the columns in original order.  How can I get the index of a column from its name?

A: <!--- get the column list, in the original order, as a coldfusion compatible array --->
<cfset variables.columnArray = createObject("java","java.util.Vector").init(
   createObject("java","java.util.Arrays").asList(
      query.getColumnList()
   )
)/>
<!--- get the index of the column. note that this is case sensitive. --->
<cfset variables.myColumnIndex = variables.columnArray.indexOf("MY_COLUMN")/>

No looping required.

A: This doesn't directly answer your question, however this may be VERY useful in your situation (I have used it in a similar situation)
This is taken from:
http://existdissolve.com/2010/11/quick-coldfusion-goodness/
columns = arrayToList(myquery.getMeta().getcolumnlabels())

gives you a list of the columns in their original order, with their original case sensitivity (not all upper case)

A: You can use the getMetaData() function, which you can read about here.  This function will return an array of Columns in the correct order, including some other information.  You would use it as follows:
getMetaData(queryName)


text:
Q: numpy.allclose() on SciPy sparse matrix def simrank_sparse(A,c,maxiter,eps=1e-4):

    if not sp.issparse(A):
        raise Exception("Input is not a sparse matrix ")

    n=sp.csr_matrix.get_shape(A)[0]
    Q=misc.get_column_normalized_matrix(A)
    sim=sp.eye(n)
    I=sp.eye(n)
    sim_prev=sp.csr_matrix(sim)

    for t in range(maxiter):

        if sc.allclose(sim,sim_prev,atol=eps):
            break
        sim_prev=sc.copy(sim)
        sim=c*(Q.T*sim_prev*Q)+(1-c)*I

    print("Converge after %d iterations (eps=%f)." % (t, eps))
    return sim

I am using sparse matrices but the numpy.allclose() function is giving errors as it only takes numpy arrays as input.  I don't want to convert the sparse matrices to arrays and back to sparse matrices again, as it will be inefficient.  Is there another way to check two sparse matrices for allclose()?

A: You can set up the architecture for the comparison, and then use numpy for the evaluation:
def csr_allclose(a, b, rtol=1e-5, atol = 1e-8):
    c = np.abs(np.abs(a - b) - rtol * np.abs(b))
    return c.max() <= atol

The csr_matrix c will contain the difference of the two matrices being compared, and if any of the absolute differences are greater than your threshold levels, csr_allclose will return False.  This implementation doesn't include the NaN features offered by the numpy.allclose method, however.

A: If you know that the matrices match in sparsity - number of nonzeros and matching nonzero indices, the you could just compare the data.
np.allclose(sim.data,sim_prev.data,atol=eps)

The would be true if the matrices are constructed in the same way, or one is sparsity preserving derivation of the other.
Some time tests:
In [153]: M = sparse.random(1000,1000,.2, 'csr')
In [154]: M
Out[154]:
<1000x1000 sparse matrix of type '<class 'numpy.float64'>'
    with 200000 stored elements in Compressed Sparse Row format>

Another matrix of same shape, but different sparsity
In [155]: M1 = sparse.random(1000,1000,.2, 'csr')
In [156]:
In [156]: timeit np.abs(M-M1).max()
12.3 ms ± 339 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [157]: timeit np.abs(M.A-M1.A).max()
24.4 ms ± 624 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

If the matrices match in sparsity, we can compare the data attributes for a considerable time savings:
In [158]: M2 = M.copy()
In [159]: M2.data += np.random.rand(M2.data.shape[0])*.001
In [160]: timeit np.abs(M.data-M2.data).max()
2.77 ms ± 13.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

A preliminary check on sparsity could save a lot of time (provided we aren't worried epsilon size nonzero values):
In [170]: timeit np.allclose(M.indptr,M1.indptr)
97.8 µs ± 2.29 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Remove the toarray() step from the timings, in effect allclose on equivalent size dense arrays:
In [164]: %%timeit Ma=M.A; M1a=M1.A
     ...: np.abs(Ma-M1a).max()
     ...:
14.8 ms ± 31 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Subtraction of the sparse matrices is doing better than I expected.

Actually I don't need to use np.abs; the Python abs delegates to M.__abs__ method, which is:
def __abs__(self):
    return self._with_data(abs(self._deduped_data()))


text:
Q: Recurrence Relations With Exponents Solve the following:
$$a_n = 2a_{n-1} + 2^{n-1} , a_0 = 3$$
Workings:
$a_n = 2a_{n-1} + \frac{1}{2} 2^n, a_o = 3$
$a_n^{(h)} = 2a_{n-1}$
The characteristic equation is:
$ch(x) = (x-2)$
$a_n^{(h)} = c(2)^n$
We have a particular solution of the form cn(2)^n.
$cn2^n = c(2)^{n-1} + 2^n$
$2cn = c + 2$
Now I'm not too sure if what I did so far is correct and I'm not sure on what to do next.
Any help will be appreciated.

A: To make your life easier look at
$$
a_{k+1} = 2 a_k +2 ^k
$$
Divide through $2^k$ to get $b_{k+1} = \frac{a_{k+1}}{2^k}$. You have
$$
b_{k+1}  = b_k + 1 \\
b_k = b_{k-1} + 1\\
\Delta b_{k+1} = \Delta b_k = \ldots  = \Delta b_1\\
$$
Now sum on both sides (telescoping sum on LHS) and plug in back expression for $a_n$.


text:
Q: About string datatype in vb.net I have a String variable in VB.NET and it contains a value like
"Date of    9/23/2012  Tot Sec_sale Amt = 29,22,696RM's Wise  ,  Gunadeep=15,83,876 ,  Purushothaman C.S.=1,12,829 ,  P.madhusudhanreddy=4,63,933 ,  Sunil vakayil=6,31,120 ,  Girish Varghese=33,019 ,  Debarun Chakraborty=79,288 ,  Rajiv Varma=18,630, RM's DT Count 1,342"

In application side I am able to view this value. I stored this value in MySQL table column. That column contains a longtext datatype. But I am not able to view the full content. Not able to view the last part RM's DT Count 1,342. It shows like Rm's....
My table structure:
fld_msg longtext
fld_phone   varchar(20)
fld_date    date
fld_status  varchar(45)
fld_type    varchar(45)
fld_name    varchar(50)

My VB.NET code:
Dim bh_msg As String =
    "Date of    " + Convert.ToDateTime(txt1.Text).Date +
    "  Tot Sec_sale Amt = " + strdmy_bh_sec_amt.ToString +
    "RM's Wise " + bh_amt_frmt1.ToString + "," +
    " RM's DT Count " + str_bh_dt_count.ToString

A: Most DB Viewer truncate long texts fields (blob, clob, ...) in order to maintain performances. But that's just debug view. The real data, and your program, should use the entire value.
Try to retrieve those values using your VB code. It should work


text:
Q: my matching game does not work properly I am learning JS and I'm making a game where I have to find the intruder.
my matching game does not work properly, because the faces on the left side must be incremetate of 5, because my code increases by 10?

<!DOCTYPE html>

    <title>Matching Game</title>
 <meta name="author" content="Aurora Ruggieri">

Matching Game

Click on the extra smiling face on the left

Thanks in advance

A: If you're trying to add 5 more faces each round, remove the following line of code:
numberOfFaces += 5;

How it works currently is, first round has 5 faces, next round will add 10 more, then 15 more, then 20 more, etc..
Run this provided snippet and you will see that removing that one line of code makes it work how you want.

    var numberOfFaces = 5;
    var theLeftSide = document.getElementById("leftSide");
 var theRightSide = document.getElementById("rightSide");

 function generateFaces(){
   for (i= 0; i < numberOfFaces; i++) {
     var top_position= Math.floor(Math.random() * 401);
     var left_position= Math.floor(Math.random() * 401);
  var leftSideImage = document.createElement("img");
        leftSideImage.setAttribute("src", "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png");
  leftSideImage.style.top = top_position + "px";
        leftSideImage.style.left = left_position + "px";
     theLeftSide.appendChild(leftSideImage);
  var leftImages = theLeftSide.cloneNode(true);
  leftImages.removeChild(leftImages.lastChild);
  theRightSide.appendChild(leftImages);
 }
        var theBody = document.getElementsByTagName("body")[0];

  theLeftSide.lastChild.onclick = function nextLevel(event){
        event.stopPropagation();
        while(theLeftSide.firstchild) {
   theLeftSide.removeChild(theLeftSide.firstchild);
  }
  while(theRightSide.firstchild) {
   theRightSide.removeChild(theRightSide.firstchild);
  }
        generateFaces();
    };

     theBody.onclick = function gameOver() {
        alert("Game Over!");
        theBody.onclick = null;
        theLeftSide.lastChild.onclick = null;
    };
   }

   generateFaces();
  img{
     position: absolute;
     height: 100px;
  width: 100px;
 }

  div{
     position: absolute;
  width: 500px;
  height: 500px;
    }

 #rightSide {
     left: 500px;
        border-left: 1px solid black;
 }

Matching Game

Click on the extra smiling face on the left

A: Kyle Richardson, thanks for the reply. The game has to increase by 5 faces whenever you find the intruder,next round will add 5 more, then 5 more...


text:
Q: Layer backed controls and vibrancy? So I did the thing where I put an NSButton inside a NSVisualEffectsView and set the blending mode to "in window". Before I put the button in, I got an error about setting wantsLayer on the visual effects view. I set it to true and it ran the next time. After putting the NSButton on the view however, I got an error, specifically Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Vibrant controls require layer-backing when blurring inside the window.
I decided it must be a similar thing so I tried setting the wantsLayer property of the NSButton to true but I still got that error. Does anyone more familiar with Core Animation know the solution to this?


text:
Q: Android WifiManager getConnectionInfo requires CHANGE_WIFI_STATE? I'm getting a user report on an error about missing the CHANGE_WIFI_STATE permission:
Error:
java.lang.SecurityException: WifiService: Neither user 10137 nor current process has android.permission.CHANGE_WIFI_STATE.
    at android.net.wifi.WifiManager.getConnectionInfo(WifiManager.java:642)

This is the code block:
WifiManager wifiMan = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (wifiMan != null) {
    WifiInfo wifiInfo = wifiMan.getConnectionInfo();

I thought this only required ACCESS_WIFI_STATE, since I'm not doing any enabling/disabling of wifi? Haven't been able to replicate in testing.


text:
Q: Group data from CSV (D3.js & Chart.js) I have a csv file like that:
id,Annee,Origine,Pax_Total
1,2014,AJACCIO,27494
2,2019,AJACCIO,57525
3,2014,ANGERS,1724
4,2019,ANGERS,4725
...

And I want to group per Origine and have the sum of Pax_Total.
The aim is to create a bar chart with Chart.js.
There is my code:
d3.csv("https://raw.githubusercontent.com/gflowiz/mapathon/master/DGAC_flux.csv")
.then(makeChart);

function makeChart(ville) {

  var sumPaxTotal = d3.rollups(ville, v => d3.sum(v, d => d.Pax_Total), d => d.Origine)
  var villeOrigine =  d3.groups(ville, d => d.Origine)

  var ctx = document.getElementById('chart').getContext('2d');
  var chart = new Chart(ctx, {
      type: 'horizontalBar',
      option:{
          maintainAspectRatio: true,
          legend: {
              display: false
            }
      },
      data: {
        labels: villeOrigine,
        datasets: [
          {
            data: sumPaxTotal,
            backgroundColor: '#F15F36'
          }
        ]
      }
    });
console.log(sumPaxTotal)
}

Here is the console log for sumPaxTotal.

I think there is an "array" problem and after lot of research, it's not clear for me...
Thanks for your help.

A: Using Arrays.map(), this could be done as follows:
data: {
  labels: sumPaxTotal.map(v => v[0]),
  datasets: [{
    label: 'DGAC-Flux',
    data: sumPaxTotal.map(v => v[1]),
    backgroundColor: '#F15F36'
  }]
}

Please take a look at your amended code below:

d3.csv("https://raw.githubusercontent.com/gflowiz/mapathon/master/DGAC_flux.csv").then(makeChart);

function makeChart(ville) {
  let sumPaxTotal = d3.rollups(ville, v => d3.sum(v, d => d.Pax_Total), d => d.Origine);
  let chart = new Chart('chart', {
    type: 'horizontalBar',
    data: {
      labels: sumPaxTotal.map(v => v[0]),
      datasets: [{
        label: 'DGAC-Flux',
        data: sumPaxTotal.map(v => v[1]),
        backgroundColor: '#F15F36'
      }]
    },
    options: {
      legend: {
        display: false
      }
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="chart" height="250"></canvas>


text:
Q: How to Replace Strings in a Text File VB6 i have a problem right now. Im using textfile as my database. Here is the format of my Strings inside the textfile.
01/Alarm1/01:00:00
01/Alarm2/02:00:00
01/Alarm3/03:00:00
For example i just want to rename the Alarm2 but it will keep the 01 on the beginning and the time on it. Thanks for help guys

A: Please find an example on which you can rely on in order to:

*

*read a text file

*update its content

*write it back

Hope this will help you.
Dim FSO As FileSystemObject
Dim TS As TextStream
Dim TempS As String
Dim Final As String
Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile("mydata.txt", ForReading)
Do Until TS.AtEndOfStream
    TempS = TS.ReadLine
    'if TempS contains Alarm2 => rename Alarm
    Final = Final & TempS & vbCrLf
Loop
TS.Close

Set TS = FSO.OpenTextFile("mydata.txt", ForWriting, True)
    TS.Write Final
TS.Close
Set TS = Nothing
Set FSO = Nothing

A: *

*open txt file;

loop begin

*

*get the string(by rows) - lets consider it is 'someStr'

*you can use NewStr = Replace(someStr,"Alarm","Warning")

*write NewStr to a new file

loop end
close both files


text:
Q: Register A Module in Drupal Website I have a module name twitter_widget and i used drupal 7 ,I want to register my module on drupal website.Please some one help me I am beginner with drupal
Thanks in advance

A: You can contribute your module by registering your account in Drupal.org. Visit here for more details to contribute to Drupal:
http://drupal.org/contribute/development

A: Just put the module inside the folder sites/all/modules.
E.g. your module's absoulte path would be http://YOUR_DOMAIN/sites/all/modules/twitter_widget/.
That's all :)


text:
Q: Ansible AWX : playbook run successfully for create directory in localhost but when go and check to that location that directory not available I new with ansible AWX I wanted to create directory on my localhost for that create playbook as given below when I run playbook it shows that successful massage and changed on localhost but when i go to that
location the Directory isn't available there.
playbook:
---
- hosts: localhost
  tasks:
   - name: Create Directory
     file:
       path: ~/newDir1
       mode: "0755"
       state: directory

output:
TASK [Create Directory] ********************************************************
20:16:58
10
changed: [localhost]
PLAY RECAP *********************************************************************
20:17:00
localhost : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

location got through output:
{
    "path": "/var/lib/awx/newDir1",
    "changed": true,
    "diff": {
        "before": {
            "path": "/var/lib/awx/newDir1",
            "state": "absent"
        },
        "after": {
            "path": "/var/lib/awx/newDir1",
            "state": "directory"
        }
    },
    "uid": 975,
    "gid": 975,
    "owner": "awx",
    "group": "awx",
    "mode": "0755",
    "state": "directory",
    "secontext": "system_u:object_r:tmp_t:s0",
    "size": 6,
    "invocation": {
        "module_args": {
            "path": "/var/lib/awx/newDir1",
            "mode": "0755",
            "state": "directory",
            "recurse": false,
            "force": false,
            "follow": true,
            "modification_time_format": "%Y%m%d%H%M.%S",
            "access_time_format": "%Y%m%d%H%M.%S",
            "_original_basename": null,
            "_diff_peek": null,
            "src": null,
            "modification_time": null,
            "access_time": null,
            "owner": null,
            "group": null,
            "seuser": null,
            "serole": null,
            "selevel": null,
            "setype": null,
            "attributes": null,
            "content": null,
            "backup": null,
            "remote_src": null,
            "regexp": null,
            "delimiter": null,
            "directory_mode": null,
            "unsafe_writes": null
        }
    },
    "_ansible_no_log": false
}

A: If you are using awx docker image then you need to check created directory inside that container.
Get inside container and search. :)


text:
Q: How to make an interface a struct constrained type parameter I used google translate
When I wrote the following code in C #, CS0453 occurred.
// This interface cannot be modified.
public interface InterfaceA {
    void Method ();
}

public struct StructA: InterfaceA {
    public void Method () {
        Console.WriteLine ("StructA");
    }
}

public struct StructB: InterfaceA {
    public void Method () {
        Console.WriteLine ("StructB");
    }
}

public class Wrapper {
    public InterfaceA abc;
}

public class InterfaceGenericTest {
    List <Wrapper> list;

    public void Main () {
        list = new List <Wrapper> ();
        list.Add (new Wrapper () {abc = new StructA ()});
        list.Add (new Wrapper () {abc = new StructA ()});
        list.Add (new Wrapper () {abc = new StructB ()});

        foreach (var item in list) {
            CallMethod <InterfaceA> (item.abc); // CS0453
        }
    }

    // This function cannot be modified.
    public void CallMethod <T> (T t)
        where T: struct, InterfaceA {
        t.Method ();
    }
}

Details of the error
Error CS0453: The type'InterfaceA' must be a non-nullable value type in order to use it as parameter'T' in the generic type or method'InterfaceGenericTest.CallMethod  (T)' (CS0453)
Therefore, I did a null check so that the CallMethod argument would not be null, but CS0453 occurred.
foreach (var item in list) {
    if (item.abc! = null) {
        CallMethod <InterfaceA> (item.abc); // CS0453
    }
}

I wondered if the compiler didn't realize it wasn't null, so I tried using the null conditional operator, but CS0453 occurred.
foreach (var item in list) {
    if (item.abc! = null) {
 // Made CallMethod an extension method.
        item.abc?. CallMethod <InterfaceA> (); // CS0453
    }
}

So when I set the class that implements InterfaceA as the argument of CallMethod, CS0453 occurred.
public class ClassA: InterfaceA {
    public void Method () {
        Console.WriteLine ("ClassA");
    }
}

CallMethod <ClassA> (new ClassA ()); // CS0453

From this, I thought that the error could have occurred because the interface could be implemented in both the class and the struct, which could pass the class as an argument to CallMethod.
If the reason for the error is correct, how do I write the above code?


text:
Q: Acyclicity of the sheaf of real analytic differential forms Let $M$ be a real analytic manifold. In the book "Sheaves on Manifolds" by Kashiwara and Schapira it is claimed on p. 127 (without reference or proof) that

*

*the Poincare lemma holds for the de Rham complex of real analytic differential forms,

*the cohomology of the sheaves of real analytic analytic differential $p$-forms vanishes in degree $\geq 1$ and for all $p \geq 0$.
Is there a reference for 1.? Why does 2. hold?
Ad 1.: As far as I see, one can prove the first claim as for the de Rham complex of smooth differential forms. More precisely, for $M$ contractible the usual homotopy to $0$ of the smooth de Rham complex restricts to a homotopy of the real analytic de Rham complex. The key point is that one can differentiate analytic functions under an integral sign and that the derivative is analytic again. But to use this result a reference would be appreciated.
Ad 2.: In an other place the authors mention Grauert's result that every real analytic manifolds $M$ can be embedded into a Stein space $X$. For Stein spaces one knows that the higher cohomology of any coherent sheaf vanishes. This might to be a starting point for proving 2. But of course this result cannot applied directly because the sheaves of differentials on $M$ will not even be modules over $\mathcal{O}_X$. Maybe one can work with real analytic forms that have complex coefficients? I am just fishing in murky waters...

A: Regarding question 2 :This is answered in the paper of Henri Cartan Bulletin SMF vol 85 yr 1957 pages 77-99 .It is essentially as outlined by user74230 .Question 1:If you look at the proof of Poincare lemma in Narasimhan's book Analysis on Real and Complex manifolds pages 128 to 129 it is clear that the proof works for real analytic forms .We just need to observe that the coefficients are given locally by
convergent power series and the operations involved in the proof preserve them.


text:
Q: Вернуть уникальные значения в domBuilder есть домбилд в нем фильтры и сохраненные значения фильтров. Я подключил эти фильтры к модальному окну. При нажатии на кнопку эти фильтры переносятся в открывающееся модальное окно. При повторном нажатии на кнопку фильтры сжимаются и должно закрываться модальное окно фильтры а возвращаться на сайт.
Dialog: function() {
        if (this.dom.classList.contains('short')){
            this.dialog.onCancel();
            return this.dom;
        } else {
            this.dialog.set('content', this.dom);
            this.dialog.show();
        }
        },

dom- это те самые фильтры. присваиваю их с помощью set. Как после закрытии окна вернуть значения обратно в dom. чтобы они выбрались из модального окна. Щас происходит я нажимаю на кнопку выходит модальное окно, с фильтрами, при повторном нажатии на кнопку окно пропадает вместе с фильтрами и этой кнопкой. Уже целый день пытаюсь решить проблему не выходит,не нашел как приделать скрины но фильтры выглядят как форма с кучей инпутов и чекбоксов, помогите плз.
Переделал немного функцию
Dialog: function () {
        if (this.dom.classList.contains('short')) {
            this.dialog.onCancel();
        } else {
            this.dialog.set('content', this.dom);
            this.dialog.show();
        }
        this.repeatDom();
    },
    repeatDom: function () {
        if (this.dom.classList.contains('short')) {
            this.instaniateDom();
    }

    },

Только не могу понять как заставить выполняться repeatDom после закрытия this.dialog.onClose(); он повторяет дом еще в модальном окне а потом закрывает его.


text:
Q: Retrieve primary key value of table when search for values in other column I am using this snippet to find a specific string in any table of the database!
DECLARE @searchstring  NVARCHAR(255)
SET @searchstring = '%foo%'

DECLARE @sql NVARCHAR(max)

SELECT @sql = STUFF((
    SELECT ' UNION ALL SELECT ' + COLUMN_NAME + ' ' +
    ' FROM ' + TABLE_NAME +
    ' WHERE ' + COLUMN_NAME + ' LIKE ''' + @searchstring + ''''
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE DATA_TYPE in ('nvarchar', 'varchar', 'char','nchar')
    FOR XML PATH('')
) ,1, 11, '')

exec (@sql)

But I would like to get the Primary Key Value of these entries!
To get the primary key of a specific table I use
SELECT ccu.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
    INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu ON tc.CONSTRAINT_NAME = ccu.Constraint_name
    WHERE tc.CONSTRAINT_TYPE = 'Primary Key'
    AND tc.TABLE_NAME = 'tbl_table'

but I can't combine both?!

A: Some tables may have more than one column in the primary key and other may have no primary key. That makes this task a bit harder and the resulting column needs to be a list of primary key values in one column.
SELECT @sql = STUFF((
    SELECT ' UNION ALL SELECT ' + QUOTENAME(C.COLUMN_NAME) + ', ' +
               ISNULL(STUFF((SELECT '+'', ''+CAST('+QUOTENAME(COLUMN_NAME)+' AS VARCHAR(MAX))'
                             FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
                               INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS CU
                                 ON TC.CONSTRAINT_NAME = CU.CONSTRAINT_NAME AND
                                    TC.TABLE_NAME = CU.TABLE_NAME
                             WHERE CU.TABLE_NAME = C.TABLE_NAME AND
                                   TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
                             FOR XML PATH('')), 1, 6, ''), '''''')+' AS PrimaryKeys'+
    ' FROM ' + QUOTENAME(C.TABLE_NAME) +
    ' WHERE ' + QUOTENAME(C.COLUMN_NAME) + ' LIKE ''' + @searchstring + ''''
    FROM INFORMATION_SCHEMA.COLUMNS AS C
    WHERE C.DATA_TYPE in ('nvarchar', 'varchar', 'char','nchar')
    ORDER BY C.TABLE_NAME
    FOR XML PATH('')
) ,1, 11, '')

SQL Fiddle
Using the tables in the fiddle the generated query will look like this.
SELECT [Col],
       CAST([ID] AS VARCHAR(MAX)) AS PrimaryKeys
FROM [T1]
WHERE [Col] LIKE '%foo%'
UNION ALL
SELECT [Col],
       CAST([Col] AS VARCHAR(MAX))+', '+CAST([ID] AS VARCHAR(MAX)) AS PrimaryKeys
FROM [T2]
WHERE [Col] LIKE '%foo%'
UNION ALL
SELECT [Col],
       '' AS PrimaryKeys
FROM [T3]
WHERE [Col] LIKE '%foo%'


text:
Q: git create new non-tracking branch based on remote branch Situation: open-source project with multiple branches, and my fork of it for contributions.
I want to create a new branch for pull requests on github. I want to base this branch on one of the existing branches on the open-source project, BUT I do NOT want my commits to go into that original branch.
As per my experience, if I clone my fork, execute git checkout -b my-branch origin/some-branch and then commit+push to my-branch, in Github the commits will go to some-branch and not my-branch. Obviously, this is problematic if I want to make multiple branches for multiple pull requests on the same branch.
The workaround that I've found for this is the following:
git checkout -b some-branch origin/some-branch
git checkout -b my-branch (new branch based on some-branch, but not tracking it)
after that - commit+push, first push will create my-branch on Github.
However, this leaves me with an extra local copy of some-branch. I can delete it later, obviously, but is there a way to avoid creating it at all? Is there a way to create my-branch, based on origin/some-branch, but not tracking it, in one command, without the extra branch in the middle?

A: Use the SHA1 hash of the same commit instead of origin/some-branch. Example:
git checkout -b my-branch 92fc7a2

Remember, a branch is just a label on a commit, nothing more. It's a 41-byte file, containing a SHA1 hash name of a commit and a linefeed.


text:
Q: Github community edition installed but not open properly I am trying the install the Github lab community edition in our centos server by using steps that mentioned in the below link
https://about.gitlab.com/install/#centos-6
The installation successfully completed while we trying the access the URL its shows "404" found. I need to access the GitHub using a relative path (http://IP/githublab. Also tried to configure the relative path by using methods that mentioned below link. But still not working.
https://docs.gitlab.com/omnibus/settings/configuration.html#loading-external-configuration-file-from-non-root-user
Please anyone guide me to address this issue.


text:
Q: LaTeXTools + Sublime Text 3 does not compile (after installing Yosemite public beta) I have been using LaTeXTools + Sublime Text 3 for a while, and they work fine. After installing the public beta of Yosemite, Sublime Text + LaTeXTools stops working: the build command brings up output window showing NO errors:
Compiling /Users/.../sometexfile.tex

TraditionalBuilder: Invoking latexmk... done.

No errors. Warnings:

It generates .aux and .fdb_latexmk files, but not others, in particular not the PDF.
Fortunately TexShop works fine, and if I compile with TexShop to generate a PDF, the forward/backward sync still works in Sublime Text.
I wonder is there any fix?

A: Click Sublime Text on menu bar, and then navigate to Preferences > Package Settings > LaTeXTools > Settings - User.
On around line 91, change builder from "traditional" to "simple".
See: https://github.com/SublimeText/LaTeXTools/issues/401


text:
Q: FormatString on WPF-DataGrid has no effect i have a small problem with FormatString in my WPF-DataGrid. I use DataGridTextColumn for the column. My DataSource is a IList<IDictionary<string, string>>
My problem is, that if i set StringFormat, it doesn't have any effect on the column.
This is my binding code:
cColumn.Binding = new Binding("[" + Config.InternName.ToLower() + "]");

And this is how i set my FormatString:
    #region [Date-Time Formating]
    if (Config.DateTimeFormat.Trim() != "")
    {
        string cDateTimeFormat = Config.DateTimeFormat.Trim();
        (cColumn.Binding as Binding).StringFormat = cDateTimeFormat;
    }
    #endregion

I have tried a lot DateTime-StringFomrats, but nothing solve my problem.
Thank you!

A: Here is my solution:
I can't simple use FormatString, without binding a datetime. So i wrote an IValueconverter:
public class StringDateTimeValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        DateTime cOutDateTime = DateTime.Now;

        if (DateTime.TryParse(value.ToString(), out cOutDateTime))
        {
            return cOutDateTime;
        }
        else
        {
            return DependencyProperty.UnsetValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value.ToString();
    }
}


text:
Q: Stat and file not modified in last minutes I need to get with stat unix command (or similar like find) possibly on one line of command all file in a folder that ARE NOT changed in the last 5 minutes for example.
I found a lot of examples with opposite: search file in a dir modified in last 3 minutes or similar.
What I need is to find files that are NOT changed (using modification time os size in bytes) in last x minutes.
Is possible to do that?
Stefano

A: find supports the -not operator for any option.
So use the most appropriate find command you've found and put -not in there.
Try this:
find . -maxdepth 1 -not -mmin -5


text:
Q: Merge array into object properties in JavaScript I have a trivial issue where I have two simple objects like this
var state = {
    Value1: "Something",
    Value2: "Else"
};

var claims = [
    "Viewing",
    "Editing",
    "Delete"
];

and I would like to create an object that looks like this.
var newState = {
    Value1: "Something",
    Value2: "Else",

    /* Array merged into properties with defaults. */
    Viewing: true,
    Editing: true,
    Delete: true
};

I considered using jQuery $.map() and alternatively Object.assign() (which seems to be closer to what I want) but I cant seem to work out exactly how to achieve the result I need.
So as the heading states, how do I merge an array into an existing object as properties while also setting default values?

A: For the simple given example try the following:

var state  = {Value1:"Something",Value2:"Else"};
    claims = ["Viewing","Editing","Delete"];

let res = Object.assign(state, claims.reduce((a,c) => {a[c] = true; return a},{}))
console.log(res)

A: You can add a property using variable name with obj[myStringAsName] = value

var state = {
    Value1: "Something",
    Value2: "Else"
};

var claims = [
    "Viewing",
    "Editing",
    "Delete"
];

var newState = state;
claims.forEach(function(item){
 newState[item] = true;
})

console.log(newState)

A: I converted the array to object using reduce and merged both objects

var state = {
    Value1: "Something",
    Value2: "Else"
};

var claims = [
    "Viewing",
    "Editing",
    "Delete"
];
var obj = claims.reduce(function(acc, cur) {
            acc[cur] = true;
            return acc;
          }, {});

var returnedData = Object.assign(state, obj);

console.log(returnedData)

A: You could use destructuring and a simple Array#forEach

const state = {
    Value1: "Something",
    Value2: "Else"
};

const claims = [
    "Viewing",
    "Editing",
    "Delete"
];

const newState = {
  ...state
}

claims.forEach(prop => newState[prop] = true);

console.log(newState)