text:
Q: Programmatically setting instance name with the OpenStack Nova API I have resigned myself to the fact that many of the features that EC2 users are accustomed to (in particular, tagging) do not exist in OpenStack. There is, however, one piece of functionality whose absence is driving me crazy.
Although OpenStack doesn't have full support for instance tags (like EC2 does), it does have the notion of an instance name. This name is exposed by the Web UI, which even allows you to set it:

This name is also exposed through the nova list command line utility.
However (and this is my problem) this field is not exposed through the nova-ec2 API layer. The cleanest way for them to integrate this with existing EC2 platform tools would be to simulate an instance Tag with name "Name", but they don't do this. What's more, I can't figure out which Nova API endpoint I can use to read and write the name (it doesn't seem to be documented on the API reference); but of course it must be somehow possible since the web client and nova-client can both somehow do it.
At the moment, I'm forced to change it manually from the website every time I launch a new instance. (I can't do it during instance creation because I use the nova-ec2 API, not the nova command line client).
My question is:

*

*Is there a way to read/write the instance name through the EC2 API layer?

*Failing that, what is the REST endpoint to set it programmatically?

*(BONUS): What is Nova's progress on supporting general instance tagging?

A: The Python novaclient.v1_1 package has a method on the server object:
def update(self, server, name=None):
    """
    Update the name or the password for a server.

    :param server: The :class:`Server` (or its ID) to update.
    :param name: Update the server's name.
    """
    if name is None:
        return

    body = {
        "server": {
            "name": name,
        },
    }

    self._update("/servers/%s" % base.getid(server), body)

This indicates that you can update the name of a server by POST-ing
the following JSON to http://nova-api:port/v2.0/servers/{server-id}:
{
  "server": {
      "name": "new_name"
  }
}

Of course, all of the usual authentication headers (namely X-Auth-Token
from your Keystone server) are still required, so it is probably easier to
use a client library for whatever language you prefer to manage all that.


text:
Q: Where should cross-platform apps keep their data? I'm building an application that is targeting Windows, Mac and Linux soon. I was wondering where should I keep application data such as settings, etc.
Application's installation folder is the easiest choice, but I think that might be a problem with new Vista security model. Besides, users might want different settings.
Is it C:\Documents and Settings\username\MyApp good for both Vista and XP?
Is it /home/username/.MyApp good for Linux and Macs?
Any ideas and/or links to best practices much appreciated.
Thanks!
Juan

A: In regards to best practices, Jeff posted an article on polluting user space that you might find useful: Don't Pollute User Space

A: As a general point, I'd recommend abstracting the implementation of your settings into a 'Settings Provider' and provide different providers for each platform. That way, you can implement the storage of the settings in the manner that best suits the target platforms (for example, a file on Linux or the Windows Registry).
Don't simply adopt the 'lowest common denominator'. Where you have content that must be explicity stored in files, have your settings provider expose the platform-specific location for those files.

A: I'm not :)
I'm using USERPROFILE in Windows and HOME in Mac/Linux. But even so, I need to know that those are the right places.
Thanks!

A: In windows you need to go another level deep than just the user profile.  Use the Application Data folder.

A: On Windows I use APPDATA,and on Linux I use HOME.

A: For Linux/BSD/Solaris:
http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html

A: Each platform has its own API for finding the user's home folder, or documents folder, or preferences folder.

*

*Windows: SHGetFolderPath() or SHGetKnownFolderPath()

*Mac OS X and iPhone OS: NSSearchPathForDirectoriesInDomains()

*Unix: $HOME environment variable

Don't hardcode specific paths or just tack a prefix and suffix on the user's name.  Also, try to follow whatever conventions there are for the platform for naming the files.

A: Never, ever store user data in the application folder.  It's just a bad idea.
Most operating systems have a $HOME (or %HOME%) environment variable.  That would be the first place to look.
If you want to cleanly support multiple operating systems, though, you're going to have to have some OS-specific code for each that figures out exactly where things need to go.  (~/Library for Mac OS, ~/.config for GNOME-based systems, %HOME%/Application Data for Windows, etc.).

A: What language are you planning to use? Java, for example, has a dedicated Preference API.

redpajama_set_name: RedPajamaStackExchange


text:
Q: UITextField set cursor to start text position I need to move cursor to start text position on set focus on the textfield.  Is it possible tot do?

A: self.selectedTextRange = [self textRangeFromPosition:newPos toPosition:newPos];

Check this Finding the cursor position in a UITextField

A: If anyone's looking for the answer in Swift:
let desiredPosition = textField.beginningOfDocument
textField.selectedTextRange = textField.textRangeFromPosition(desiredPosition, toPosition: desiredPosition)

But I believe this only works if the cursor is already in the text field. You can use this to do that:
textField.becomeFirstResponder()
let desiredPosition = textField.beginningOfDocument
textField.selectedTextRange = textField.textRangeFromPosition(desiredPosition, toPosition: desiredPosition)

A: Set your view controller (or some other appropriate object) as the text field's delegate and implement the textFieldDidBeginEditing: method like this:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    UITextPosition *beginning = [textField beginningOfDocument];
    [textField setSelectedTextRange:[textField textRangeFromPosition:beginning
                                                          toPosition:beginning]];
}

Note that setSelectedTextRange: is a protocol method of UITextInput (which UITextField implements), so you won't find it directly in the UITextField documentation.


text:
Q: ck editor adding html tags on the browser while showing to the user Current Requirenment :
I am having a form if users fill the form there will be a button to export form  as word and if he clicks the form will get downloaded as word.

Issue:
I am using ck editor in one field to the form ,  I am  entering the text and using the tools that is provided in the ckeditor such as bold italics, bullets [B,I] etc while I am exporting the form to pdf I am seeing html tags appended in the exported word docs.
Needed:
I need the exported document to be viewed as plain text without any html tags

A: Found the solution for this issue , the main mistake in the word template i gave the same variable name for two place which over rides and provide html tags(not parsing) , if the name is changed to two different names the probem is solved


text:
Q: Simple way to fit large number of single factor logistic regression models in R - automatically I have a dataset with one binary target variable called "target" and many many factors "F1", F2"… "F200". I'm trying to come up with code to fit 200 single factor logistic regression models and return the model summaries. Here is what I have so far
single <- function(df, factor){
    s <- summary(glm(as.formula(paste('target ~ ', factor, sep='')), family=binomial, data=df));
return(s);
}
single(data, c("F1", "F2", "F2"));

but this gives me only a summary of the first model. Am I missing something obvious here?

A: Here's a solution using lapply. It will return a list of model summary objects.
lapply(c("F1", "F2", "F3"),
       function(x) summary(glm(df[["target"]] ~ df[[x]], family=binomial)))

Your codes does not work because you run paste('target ~ ', c("F1", "F2", "F2"), sep='') which results in "target ~ F1" "target ~ F2" "target ~ F2". Converted to a formula, it returns target ~ F1.
Update
A solution which returns a matrix of regression results.
An example data frame:
set.seed(42)
df <- data.frame(target = sample(0:1, 10, TRUE),
                 F1 = rnorm(10), F2 = rnorm(10), F3 = rnorm(10))

predictors <- c("F1", "F2", "F3")
fits <- sapply(predictors,
               function(x) {
                 tmp <- try(coef(summary(glm(as.formula(paste("target", x, sep = "~")),
                                             family=binomial, data = df)))[2, ], TRUE)
                 if (class(tmp) == "try-error") NULL else tmp})

The result (fits):
                   F1         F2        F3
Estimate   -0.1864527 -1.2242511 0.6751601
Std. Error  0.8259677  1.0915999 0.8770035
z value    -0.2257384 -1.1215200 0.7698488
Pr(>|z|)    0.8214049  0.2620666 0.4413896


text:
Q: Prediction path for the ball getting hit by another ball I'm creating a pool game. What I need right now is a trajectory prediction path for the ball getting hit by another ball. When the ball is hit by the raycast of the main cue ball it will show it's trajectory path. I have created the raycast part what I need is a trajectory path for the ball(the green ball) getting hit by another ball(white ball)

A: You don't only need to calculate the direction. Consider that the path of the ball is not a line but has a radius. In fact, the point of impact of the ball is on the perimeter of the circle, so use a spherecast.
if (Physics.SphereCast(m_ball.transform.position, m_ball.radius, localDirection, out var hit, length, ballLayer.value))
{
    newDirection = hit.transform.position - hit.point;
}

Here I showed the difference between raycast and spherecast, which is the correct spherecast result due to the difference in their hit points.

A: Raycast from the ball object you are hitting in a direction.
Let the ball game object be myBall which shall be shot in the direction direction and the direction of the ball that's going to be hit be newDirection.
if(Physics.Raycast(myBall.transform.position, direction, out RaycastHit hit))
{
    newDirection = hit.transform.position - hit.point;
}

Explaining the code a little bit, when an object collides with another object, it moves in the direction through its normal and the point at which the collision has happened.
Note: This only gives the direction of the ball that's hit, to know the velocity and other properties, the mass and velocity of the ball that's projected should be specified.


text:
Q: How to convert a Task into a Task? I'm sure this has been asked before but I can't seem to phrase the question right to get any answers that solve my question.
I've got a base class that implements an interface with a Save method that returns a Task:
public interface ICanSave
{
    Task Save();
}

public class Base : ICanSave
{
    public Task Save()
    {
        return Task.CompletedTask;
    }
}

Of course the Save method will actually do something, like saving to a database, which is why it's a Task, so it can be awaited. If I have a Foo class that inherits from the base class:
public class Foo : Base { }

Currently, you'd have to do the instantiation and save in two distinct steps:
var foo = new Foo();

await foo.Save();

However I'd like to be able to do the instantiation and the save as an expression and return a Task also. I've come up with this helper:
public static class Helper<T> where T : ICanSave
{
    public static Task<T> Save(T obj)
    {
        var source = new TaskCompletionSource<T>();

        ThreadPool.QueueUserWorkItem(_ =>
        {
            obj.Save();
            source.SetResult(obj);
        });

        return source.Task;
    }
}

Which could then be used to do:
var foo = await Helper<Foo>.Save(new Foo());

Which is more like the result I'm trying to achieve, but it seems pretty cumbersome, plus the helper seems to be pushing the Save to a Task twice (once for the original Task and a second time in the helper).
Is there a more simple way to do this conversion from a Task to a Task of T?

A: I don't see a point of such helper method, but if you really want you can like this:
public static class Helper<T> where T : ICanSave {
    public static async Task<T> Save(T obj) {
        await obj.Save();
        return obj;
    }
}


text:
Q: how to decrease a number in machine language I want to add -1 and a number which is placed at memory address 0x36.
First, I loaded memory address bit pattern which is in 0x36 in a register and I loaded memory address ff (two's complement notation=-1) and add them. But my tutor said this solution is not true.
So, how can I decrease a number by -1 with only addition and bring them registers?


text:
Q: Rebuilding indexes does not change the fragmentation % for nonclustered indexes For starters, I am no DBA and I am working on rebuilding the indexes.
I made use of the amazing TSQL script from msdn to alter index based onthe fragmente percent returned by dm_db_index_physical_stats and if the fragment percent is more than 30 then do a REBUILD or do a REORGANISE.
What I found out was, in the first iteration, there were 87 records which needed defrag.I ran the script and all the 87 indexes (clustered & nonclustered) were rebuilt or reindexed. When I got the stats from dm_db_index_physical_stats , there were still 27 records which needed defrag and all of theses were NON CLUSTERED Indexes. All the Clustered indexes were fixed.
No matter how many times I run the script to defrag these records, I still have the same indexes to be defraged and most of them with the same fragmentation %. Nothing seems to change after this.
Note: I did not perform any inserts/ updates/ deletes to the tables during these iterations. Still the Rebuild/reorganise did not result in any change.
More information:  Using SQL 2008
Script as available in msdn  http://msdn.microsoft.com/en-us/library/ms188917.aspx
Could you please explain why these 27 records of non clustered indexes are not being changed/ modified ?
Any help on this would be highly appreciated.
Nod

A: SQL Server will not rebuild indexes that are not large enough.  Have a look a the fragment_count (that's one of the fields in the sys.dm_db_index_physical_stats view), it's probably quite low for those 27 indexes.


text:
Q: Javascript RegEx failing I am trying to write a regular expression that will ONLY accept files with JPEG, JPG or PDF format.  My attempt has been:
/^image|\/(jpe?g|pdf)$/i
But, as it stands, it won't accept PDF format (because of the 'image/*' portion).
Any help would be appreciated.  Thank you.

A: That expression doesn't make a lot of sense. You have an alternation there saying either match ^image or match /(jpe?g|pdf)$.
If you want to match image/jpg, image/jpeg, and application/pdf, then:
/^(?:image\/jpe?g|application\/pdf)$/

Note, though, that PDFs can have a few other MIME types. Perhaps:
/^(?:image\/jpe?g|application\/(?:pdf|x-pdf|x-bzpdf|x-gzpdf))$/

...would be more inclusive.

A: Not everything needs to be a regular expression:
function isValidMimeType(type) {
    return [
        'image/jpg',
        'image/jpeg',
        'application/pdf',
        'application/x-pdf',
        'application/x-bzpdf',
        'application/x-gzpdf'
    ].indexOf(type) > -1;
}

If you insist on using regular expressions, I recommend using multiple so that the code is still readable:
function isValidMimeType(type) {
    if (/^image\/jpe?g$/.test(type)) {
        return true;
    } else if (/^application\/(?:x-|x-bz|x-gz)?pdf$/.test(type)) {
        return true;
    }
    return false;
}

Of course, this code could be written shorter. There's no reason to though. You sacrifice readability when you condense it down to:
function isValidMimeType(type) {
    return /^(?:image\/jpe?g|application\/(?:x-(?:bz|gz)?)?pdf)$/.test(type);
}

Good luck ever adding another mime type to that.


text:
Q: PHP readfile() which preserves mime-type I am trying to set up a PHP script which can pull files (for validated users) from a folder outside of the live webroot. The problem is that when doing this, even if I use a proper "Content-Type" header, the file is downloaded as application/octet-stream. This has security implications if the user later tries to re-upload the downloaded file as it will be detected as an application even when it is really a pdf (my application only allows certain mime-types to be uploaded).
This is what I am using to pull the file into the browser:
$secret_file = "../attach/1/test.pdf";

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: ".mime_content_type($secret_file));
header("Content-Disposition: inline; filename=\"test.pdf\";");
header("Content-Transfer-Encoding: binary");
readfile($secret_file);

Interestingly, if I download the file this way through a browser and view its properties in linux, it shows up as "application/pdf". However, if I check the same file using PHP's mime_content_type() function, it reads as application/octet-stream.
I did confirm that checking the original file this way (before it is pulled through readfile) shows it as application/pdf.
Is there any way to use readfile() without changing mime types? Or, is there perhaps a better alternative?
EDIT
Answering some questions from the comments:

*

*Developer Tools in Firefox reports that the inline file has a Content-Type: application/pdf header.

*sha256sum of downloaded file does not match the original file. But how could readfile() (or similar) be used without changing the file?


text:
Q: Is subprocess.Popen() expected to be threadsafe in python 3.x >= 3.2? From Is subprocess.Popen not thread safe? it's clear that prior to 3.2, subprocess.Popen() had serious threading issues, and 3.2 improved the situation significantly. However, AFAICT the Python documents do not state one way or the other whether subprocess is currently thread safe or not. I'd like to chuck some Popen() invocations on a ThreadPoolExecutor (for executing shell commands which I need to send stdin to), but not if there's any potential for nasty concurrency surprises in doing so.
Is subprocess.Popen() thread safe now, or is it still appreciably dangerous?


text:
Q: Looking for enterprise web application design inspiration I've checked many websites to be inspired about what the look and feel of a serious enterprise web-application should look like. But the whole I saw were designed for being used by single users and not serious corporate users. The designs I saw were mostly happy-colored, and looked like being developed by a small team of eager young passionate developers.
But what I'm looking for, are showcases of serious web apps' designs (e.g. web apps developed by large corporations) that are developed for being used by a large number of corporate uses.
Can you suggest me sources for this kind of inspiration?

A: If you want to see what corporate look and feel that's been designed by a committee and tweaked over a number of years, I can think of no better example than Microsoft's online version of Outlook.
Failing that, take a look at Salesforce.com or QuickBooks Online.
Use TMN's advice to see these if you don't have access.
These are all example of well-designed, but very boring and to the point interfaces, which is what you seem to be after.

A: Go to Google image search and enter  "${product} screenshots" where "${product}" is something like "peoplesoft" or "sap financials" or "baan".  Not sure how inspiring they'll be (enterprise-class systems are rarely sexy) but they'll be real-world examples.

A: I don't know if I'd use the phrase "serious web apps" to describe the typical enterprise app - most consumer facing apps/sites these days are built to be more scalable than the typical multi-tier "enterprise" app.  Different apps, different challenges.
That being said, an enterprise application is usually less focused around messaging/content (etc.) and more focused on the ability to view and/or manipulate data.  It's usually the ability to view and manipulate data that good enterprise design allows users to do.
A good example (and possibly a solution for you) in terms of enterprise design is Oracle's "Application Development Framework" (ADF), specifically the "ADF Rich Faces" components.
(There's a version you can freely experiment with here:  http://www.oracle.com/technetwork/developer-tools/adf/overview/adfessentials-1719844.html  You might also want to grab a copy of JDeveloper for simple exploration.)
Compare the design of the data-driven components (tables, components designed for data display) versus the design of other JSF libraries like PrimeFaces; while both can be comparable, the ADF Rich Faces libraries are designed with mass data views and manipulations in mind.


text:
Q: Return multiple values python flask I am trying to return a file and changing the template in Flask.
return send_file(myfile, as_attachment=True), return render_template("template.html")

But it gives me an error.
If I try to make 2 returns like this:
return send_file(myfile, as_attachment=True)
return render_template("template.html")

or
return render_template("template.html")
return send_file(myfile, as_attachment=True)

It doesn't work eitherway.
How do I fix this?
Thanks

A:

You only get one response per request. You can either send a file, or send a new page.

Bear the above in mind by @Tim Roberts.

How do I send the file and then send the new page?.

A long possible ride I suggest you do something like this (Note you use another view for sending the file too).
    # ...
    if request.GET.get("send", None):
        return send_file(myfile, as_attachment=True)
    return render_template("template.html")

In the template use ajax to make GET request to the view
ajax.get({
    "/the-view-url/?send=file",
    success: function(data) {
    // do whatever you want with data (file)
    }

Tada !! you can now return a response or a file.
I suggest you consider this:

It seems like you need to learn Python's fundamentals. –
mac13k

A: You only get one response per request.  You can either send a file, or send a new page.


text:
Q: Where do I find the "Amazon Cognito Identity ID" referred to in the Amplify Storage documentation? The Amplify Storage documentation describes the rubric for S3 paths to files including user_identity_id for private and protect files. Where can I find the value of that for a given users, and for all users of my app? For example, how would I reconstruct the path to files stored in S3 by Storage.put in another context such as a Python notebook?

A: You can retrieve identityId from:
const { identityId } = await Auth.currentCredentials();

see https://docs.amplify.aws/lib/storage/configureaccess/q/platform/js/
The afterwards to reconstruct the the path you would concatenate the identityId and the prefix used from protected, public or private. See the code from the Amplify library how it's implemented:
https://github.com/aws-amplify/amplify-js/blob/main/packages/storage/src/providers/AWSS3Provider.ts
const privatePath =
            (customPrefix.private !== undefined ? customPrefix.private : 'private/') +
            identityId +
            '/';
        const protectedPath =
            (customPrefix.protected !== undefined
                ? customPrefix.protected
                : 'protected/') +
            identityId +
            '/';
        const publicPath =
            customPrefix.public !== undefined ? customPrefix.public : 'public/';


text:
Q: Codeigniter $this->input->post() returning NULL I'm trying to use the inbuilt this->input->post('name') function when creating the Sign Up API in CodeIgniter, but this->input->post() returns an empty array.
I am using the same url on the browser and it works perfectly fine there but when I try to use it on Postman, it is returning null
I had tried:

print_r($_POST).

I had also used POST And GET Method but show nothing.

which also gives null
For testing purpose I created a function in which I used the form and post method to send data that worked fine on the browser but showed nothing on Postman.
**TESTING Function**
public function test()
{
    echo '<form method="POST"> <input name="name" ><input type="submit"> </form>';
    // print_r($_POST);
    die(var_dump($_POST));
}

A: Verify your Postman request body: Make sure that you are sending the correct data in the request body. You can check this by opening the "Body" tab in Postman and checking the "form-data" key-value pairs or "raw" body.
Check your CodeIgniter code: Make sure that your CodeIgniter code is correctly configured to accept POST requests. In CodeIgniter, you can use the $this->input->post() function to retrieve data from a POST request. Make sure that you are using this function correctly and that your CodeIgniter controller is correctly set up.
Check your Postman request headers: Make sure that your request headers include Content-Type: application/x-www-form-urlencoded or Content-Type: multipart/form-data. This tells the server that you are sending form data.
Debug your CodeIgniter code: You can add var_dump($_POST) or var_dump($this->input->post()) in your CodeIgniter controller to see if the data is being sent and received correctly. If you are still having trouble, you can use CodeIgniter's debugging tools to help you diagnose the issue.

A: CodeIgniter sometimes acts crazy while getting application/json post values.  You can use
$_POST = file_get_contents('php://input');

You will get an array of post values received from Postman with Content-type: application/json header.


text:
Q: Set quick doc duration in Android Studio In Android Studio, I can enable "Show quick doc on mouse move" so that when I hover my mouse on an item, it display its documentation (like in Eclipse):

However, this quick doc only displays for about 2 seconds then automatically disappears. How can I make it stay there and only disappear when I click somewhere else?

A: Bring you mouse cursor on any of the method/variable and press :
Ctrl+Q

For Mac Users:
Ctrl+J

A: It seems this is a bug of Android Studio: if you open logcat, when a new log line appears, the quick doc window will automatically disappear. I've filed a bug report.

A: I found Android Issue 180447 for this, which is still open. I added the following additional info as a comment to it:

This is probably an issue in IntelliJ. I see similar behavior
  (IntelliJ CE 14.1.4).
FYI: My (imperfect) workaround is to "Hide" the "Android" tab (which
  stops displaying the tab's contents, but keeps the tab). That causes
  the Quick Doc popups to stay around. (Clicking on the "Android" tab
  re-displays its contents.)


text:
Q: Permission denied (publickey,gssapi-keyex,gssapi-with-mic) Ok, so I have tried this quite a few times and I'm sure this is very trivial but: I am trying to SSH via command line on Ubuntu into my VM (Centos6) with an RSA key-pair I created using key-gen.
I have created the key-pair and appended the public key to authorized_keys file and changed the permissions to 600. After I SCP'ed the private key to Ubuntu and tried to SSH using it and I always get:
Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

I have tried this 3x already and no luck. I can ping it but I can't seem to figure out why it's not taking the key I made. Any suggestions?

A: First generate the key-pair on your Ubuntu machine.
After, copy the contents of the generated .pub file in your ssh folder (~/.ssh/id_rsa) and paste it to the username/.ssh/id_rsaauthorized_keys file, on a new line, on your CentOS for the specific user you are logging in with.

A: I just had the same problem on ClearOS 7.2 while trying to login through SSH using RSA from OSX.
Turns out I had to add the filename of my private key (the one that resides on the client system, OSX in this case) on the client system to the /etc/ssh/ssh_config file (this is the ssh client config file on the client machine). Otherwise it just wouldn't look in that file eventhough it starts with id_rsa.
The line added was:
IdentityFile ~/.ssh/id_rsa.somecomputer

"somecomputer" is whatever the rest of the filename you might have is.

A: I had the same problem, I solved it like this:
On the ssh server, I uncommented, and put at yes the following values in /etc/ssh/sshd_config
 RSAAuthentication yes
 PubkeyAuthentication yes

And then:
sudo service sshd restart

A: Run ssh with verbose mode (add as many -v as you need) and try to find out the reason.
For example
ssh -vvv user@host

You will get a debug output that helps you to find out the reason.

A: If you tailf /var/log/auth.log on the server and login again, you should see the reason for the failure get logged. If not, kick up the verbosity in the SSH daemon config file to DEBUG and retry again. Often times it's related to file permissions.

A: I've had the same issue before - my key was moved to a different folder and I did not update the ssh_config file.


text:
Q: How to make jQuery callback like .done in AJAX? How to make jQuery callback like .done in AJAX?
I need to do like it:
myMethod(args)
    .done(function(args) {
        console.log(true);
    });

Thanks in advance.

A: A bit unclear what you're asking. Is this what you want?
function myMethod(){

    var dfd = $.Deferred();

    // simulate something async:
    setTimeout(function(){
        dfd.resolve({foo: true}); // pass some dummy data
    }, 500);

    return dfd.promise();
}

myMethod().done(function(args){
    console.log(args.foo);
});

http://jsfiddle.net/9MRr9/1/
Read more about deferred objects here: http://api.jquery.com/category/deferred-object/

A: Not really clear what you want to do exactly. You can use $.ajax to make the ajax call and provide a function after the request is done.
Create your own function and pass in a callback.
Sample
function doRequest(callback) {
    $.ajax({
      url: "yourUrl",
    }).done(callback));
}

doRequest(function(data) {
  // do something
});

More Information:

*

*jQuery.ajax()


text:
Q: Drawing stones and pebbles under seafloor in order to do some technical drawings, I intend to reproduced a (schematized) pebbled sea floor. I could manage to do a MWE, but this is as far as I can possibly get.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{%
decorations.pathreplacing,%
decorations.pathmorphing%
}
\newcommand\irregularcircle[1]{% radius, irregularity
  let \n1 = {(#1)+rand*(0.1*#1)} in
  +(0:\n1)
  \foreach \a in {10,20,...,350}{
    let \n1 = {(#1)+rand*(0.2*#1)} in
    -- +(\a:\n1)
  } -- cycle
}

 \begin{document}
  \thispagestyle{empty}
  \begin{tikzpicture}[
                media/.style={font={\footnotesize\sffamily}},
                wave/.style={
                decorate,decoration={snake,post length=1.4mm,amplitude=2mm,
                segment length=2mm},thick},
                interface/.style={
                % The border decoration is a path replacing decorator.
                % For the interface style we want to draw the original path.
                % The postaction option is therefore used to ensure that the
                % border decoration is drawn *after* the original path.
                    postaction={draw,decorate,decoration={border,angle=-135,
                    amplitude=0.3cm,segment length=2mm}}
                }
                ]
 \begin{scope}
  \draw [draw=none, fill=cyan!10, rounded corners=2mm] (-2,0) rectangle
   (10,2);
    \draw [interface, thick, black] (-2,0)--(10,0);
    \draw[draw=none, fill=brown!10, rounded corners=1mm, opacity=0.5]
     (-2,0)rectangle (10,-1);
      \clip (-2,0) rectangle (10,-2);
      \foreach \a in {0,1,...,100}
       {
          \draw[black!50,ultra thin,rounded corners=.5mm, fill=brown!20]
              (8*rand, rand) \irregularcircle{0.21cm};

        }
     \end{scope}
     \end{tikzpicture}
   \end{document}

Now, i have following questions:

*

*any better way to draw stones (I used an available function on tikz to draw circle with addded noise)

*How could I (equally?) distribute the stones below the water? Ideally bounded between xmin,xmax AND ymin, ymax

Thank you!
Marco

A: Conceptually the problem of drawing the stones is very similar to what has been done in this answer, which I am recycling here. This allows you to avoid overlaps.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{%
decorations.pathreplacing,%
decorations.pathmorphing%
}
\newcommand\irregularcircle[1]{% radius, irregularity
  +(0:#1)
  \foreach \a in {30,60,...,330}{
    let \n1 = {(#1)+rand*(0.2*#1)} in
    -- +(\a:\n1)
  } -- cycle
}
%from https://tex.stackexchange.com/a/87518/121799
\def\xlist{4}
\def\ylist{4}
\newcommand{\fillrandomly}[7][]{
    \pgfmathsetmacro\diameter{#6*2}
    \foreach \i in {1,...,#7}{
        \pgfmathsetmacro\x{0.5*(#4+#2+(2*rnd-1)*(#4-#2))}
        \pgfmathsetmacro\y{0.5*(#5+#3+(2*rnd-1)*(#5-#3))}
        \xdef\collision{0}
        \foreach \element [count=\i] in \xlist{
            \pgfmathtruncatemacro\j{\i-1}
            \pgfmathsetmacro\checkdistance{ sqrt( ({\xlist}[\j]-(\x))^2 + ({\ylist}[\j]-(\y))^2 ) }
            \ifdim\checkdistance pt<\diameter pt
                \xdef\collision{1}
                \breakforeach
            \fi
        }
        \ifnum\collision=0
            \xdef\xlist{\xlist,\x}
            \xdef\ylist{\ylist,\y}
             \draw[black!50,ultra thin,rounded corners=.5mm,
             top color=brown!20,bottom color=brown!20!gray,
             shading angle={(0.5+rand)*20}]
              (\x,\y) \irregularcircle{0.21cm};
        \fi

    }
}

 \begin{document}
  \thispagestyle{empty}
  \begin{tikzpicture}[
                media/.style={font={\footnotesize\sffamily}},
                wave/.style={
                decorate,decoration={snake,post length=1.4mm,amplitude=2mm,
                segment length=2mm},thick},
                interface/.style={
                % The border decoration is a path replacing decorator.
                % For the interface style we want to draw the original path.
                % The postaction option is therefore used to ensure that the
                % border decoration is drawn *after* the original path.
                    postaction={draw,decorate,decoration={border,angle=-135,
                    amplitude=0.3cm,segment length=2mm}}
                }
                ]
 \begin{scope}
  \draw [draw=none, fill=cyan!10, rounded corners=2mm] (-2,0) rectangle
   (10,2);
    \draw [interface, thick, black] (-2,0)--(10,0);
    \draw[draw=none, fill=brown!10, rounded corners=1mm, opacity=0.5]
     (-2,0)rectangle (10,-1);
      \clip (-2,0) rectangle (10,-2);
      \fillrandomly{-2+0.21}{-0.21}{10-0.21}{-1+0.21}{0.21}{37}
     \end{scope}
\end{tikzpicture}
\end{document}

As for your second question: do you have a rough idea how the stones should look like? I made a proposal but it may be very different from what you're hoping to get.
It might be nicer to have the stones on the background.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{%
decorations.pathreplacing,%
decorations.pathmorphing
}
\newcommand\irregularcircle[1]{% radius, irregularity
  +(0:#1)
  \foreach \a in {30,60,...,330}{
    let \n1 = {(#1)+rand*(0.2*#1)} in
    -- +(\a:\n1)
  } -- cycle
}
%from https://tex.stackexchange.com/a/87518/121799
\def\xlist{4}
\def\ylist{4}
\newcommand{\fillrandomly}[7][]{
    \pgfmathsetmacro\diameter{#6*2}
    \foreach \i in {1,...,#7}{
        \pgfmathsetmacro\x{0.5*(#4+#2+(2*rnd-1)*(#4-#2))}
        \pgfmathsetmacro\y{0.5*(#5+#3+(2*rnd-1)*(#5-#3))}
        \xdef\collision{0}
        \foreach \element [count=\i] in \xlist{
            \pgfmathtruncatemacro\j{\i-1}
            \pgfmathsetmacro\checkdistance{ sqrt( ({\xlist}[\j]-(\x))^2 + ({\ylist}[\j]-(\y))^2 ) }
            \ifdim\checkdistance pt<\diameter pt
                \xdef\collision{1}
                \breakforeach
            \fi
        }
        \ifnum\collision=0
            \xdef\xlist{\xlist,\x}
            \xdef\ylist{\ylist,\y}
             \draw[black!50,ultra thin,rounded corners=.5mm,
             top color=brown!20,bottom color=brown!20!gray,
             shading angle={(0.5+rand)*20}]
              (\x,\y) \irregularcircle{0.21cm};
        \fi

    }
}

 \begin{document}
  \thispagestyle{empty}
  \begin{tikzpicture}[
                media/.style={font={\footnotesize\sffamily}},
                wave/.style={
                decorate,decoration={snake,post length=1.4mm,amplitude=2mm,
                segment length=2mm},thick},
                interface/.style={
                % The border decoration is a path replacing decorator.
                % For the interface style we want to draw the original path.
                % The postaction option is therefore used to ensure that the
                % border decoration is drawn *after* the original path.
                    postaction={draw,decorate,decoration={border,angle=-135,
                    amplitude=0.3cm,segment length=2mm}}
                }
                ]
  \draw [draw=none, fill=cyan!10, rounded corners=2mm] (-2,0) rectangle
   (10,2);
  \begin{scope}
   \clip (-2,0) rectangle (10,-2);
   \draw[draw=none, fill=brown!10, rounded corners=1mm, opacity=0.5]
     (-2,0)rectangle (10,-1);
   \fillrandomly{-2+0.21}{-0.21}{10-0.21}{-1+0.21}{0.21}{37}
   \draw [interface, thick, black] (-2,0)--(10,0);
  \end{scope}
\end{tikzpicture}
\end{document}

A: Another two options, first using \pgfdeclarepatternformonly within tikzpicture environment to enable to use basic tikz code instructions like \draw instead \pgfpath..., the issue is that only accept paths, so filling with shades is not available; for this reason the second option is done using basic tikz code in drawing definitions to not repeat the code many times and creating another definition like a pattern helped with clip and foreach statement.
RESULT:

MWE:
\documentclass[tikz,border=5pt]{standalone}
\usetikzlibrary{calc}
\usetikzlibrary{patterns,shapes.geometric,decorations.pathmorphing,decorations.pathreplacing}

\begin{document}
    \begin{tikzpicture}[
    myshade/.style={
        black!50,
        draw,
        ultra thin,
        rounded corners=.5mm,
        top color=brown!20,
        bottom color=brown!20!gray
    },
    interface/.style={
                % The border decoration is a path replacing decorator.
                % For the interface style we want to draw the original path.
                % The postaction option is therefore used to ensure that the
                % border decoration is drawn *after* the original path.
                    postaction={draw,decorate,decoration={border,angle=-135,
                    amplitude=0.3cm,segment length=2mm}}
       }
    ]
    \def\stone(#1)[#2][#3]{%Drawing manually some shape
        \begin{scope}[shift={(#1)},rotate=#2,scale=#3,transform shape]
            \draw[line width=0.25pt,rounded corners=1pt]
                (15:3pt) -- (45:4pt) -- (89:5pt)--(135:6pt) -- (150:3pt) -- (182:4pt)--(235:6pt) -- (280:3pt) -- (330:2pt) -- cycle;

        \end{scope}
    }
    %Declare a new pattern ¿form only?
    \pgfdeclarepatternformonly{pebless under sea floor}{\pgfqpoint{0pt}{0pt}}{\pgfqpoint{15pt}{15pt}}{\pgfqpoint{15pt}{15pt}}%
    {
         \stone(8pt,6pt)[-15][1]
         \stone(0pt,0pt)[45][0.7]
         \stone(15pt,15pt)[45][0.7]
         \stone(0pt,15pt)[45][0.7]
         \stone(15pt,0pt)[45][0.7]
         \stone(0pt,7.5pt)[180][0.7]
         \stone(15pt,7.5pt)[180][0.7]
         \stone(7.5pt,0pt)[90][0.7]
         \stone(7.5pt,15pt)[90][0.7]
         \draw[line width=0.25pt,rotate=-45] (5.5pt,10pt) ellipse (1pt and 2pt);
         \draw[line width=0.25pt] (12pt,10pt) circle (0.7pt);
    }
    %Create a second shape to create a brute force pattern...
    \def\stone2(#1)[#2][#3]{
        \begin{scope}[shift={(#1)},rotate=#2,scale=#3,transform shape]
            \draw[myshade]
                (15:3pt) -- (45:4pt) -- (89:5pt)--(135:6pt) -- (150:3pt) -- (182:4pt)--(235:6pt) -- (280:3pt) -- (330:2pt) -- cycle;
        \end{scope}
    }
    \def\stonepattern(#1){%Brute force pattern
        \begin{scope}[shift={(#1)}]
            \clip (0,0) rectangle ++(15pt,15pt);
            \stone2(8pt,6pt)[-15][1]
            \stone2(0pt,0pt)[45][0.7]
            \stone2(15pt,15pt)[45][0.7]
            \stone2(0pt,15pt)[45][0.7]
            \stone2(15pt,0pt)[45][0.7]
            \stone2(0pt,7.5pt)[180][0.7]
            \stone2(15pt,7.5pt)[180][0.7]
            \stone2(7.5pt,0pt)[90][0.7]
            \stone2(7.5pt,15pt)[90][0.7]
         \draw[line width=0.25pt,rotate=-45,myshade] (5.5pt,10pt) ellipse (1pt and 2pt);
         \draw[line width=0.25pt,myshade] (12pt,10pt) circle (0.7pt);
        \end{scope}
    }

    %Start drawing the thing
    \clip[rounded corners=0.2cm] (0,2) rectangle ++(12,-3);
    \fill [cyan!10] (0,0) rectangle ++(12,2);
    \fill[fill=brown!25, rounded corners=1mm, opacity=0.5]
    (0,0) rectangle ++(12,-1);
    %Drawing sea floor using pattern
    \fill[pattern=pebless under sea floor] (0,0) rectangle ++(6,-1);
    %Dragind sea floor using brute force...
    \begin{scope}
        \clip(6,0) rectangle ++(6,-1);
        \foreach \x in {0,...,11}{
            \foreach \y in{0,...,2}{
                \stonepattern(6cm+\x*15pt,-1cm+\y*15pt)
            }
        }
    \end{scope}
    \draw [thick, black,interface] (0,0)--(13,0);

    \end{tikzpicture}
\end{document}


text:
Q: 32 bit exec fails to start but works when started through ltrace/strace I have a 32 bits binary (running on a 64 bits host) that fails to start when started alone, returning an error when loading a shared library (cannot open shared object file: No such file or directory).
But it runs perfectly when I start it using ltrace or strace (I tried to find the point of failure)...
What's wrong? I checked the library exist, I tried to add it to the LD_LIBRARY_PATH, I also checked /lib/ld-linux.so.2 exists...
The host is running RedHat-EL 5.6...

A: You need 32-bit version of libraries to run 32-bit applications on 64-bit system. Unfortunately Redhat doesn't have package like ia32-libs which would install most of them, it is supposed that you should install all 32-bit applications with yum and it will install the appropriate libraries for you. If your application is third-party, try installing 32-bit version of each library it needs, they usually have .i586 suffix, so you execute something like "yum install libusb.i586".


text:
Q: Implementing MultiDex results in compiling for so long, and finally heap space error I have a big Android project where I got the Unable to execute dex: method ID not in [0, 0xffff]: 65536 error; I believe some of you guys have definitely gone through this issue before. This is an error due to too many methods referenced in the app.
I have looked for different sources online and found this might be the best solution.
And I did the following:

*

*Added multiDexEnabled = true in the defaultConfig block of build.gradle.

*Added the following dependency:
dependencies {
  compile 'com.android.support:multidex:1.0.0'
}

*Overrided the following code inside my App class.
@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}

Now, the error is gone, but I have a new problem. When I run the app, the compiler takes more than 3 minutes for compiling and running the app, finally giving me this error:
UNEXPECTED TOP-LEVEL ERROR:
java.lang.OutOfMemoryError: Java heap space

I understand this error occurs due to heavy memory usage, but I don't know how to solve it. I am using Android Studio 1.0.2, and Android API 21.
Thanks!
EDIT:
I already checked How to fix "OutOfMemoryError: java heap space" while compiling MonoDroid App in MonoDevelop, but this does not cover the reason of the problem, and moreover, I am not using Xamarin Studio.
EDIT2:
The exact symptom is like this:
When I compile the code, the gradle console shows me hundreds of warnings saying "Ignoring InnerClasses attribute for an anonymous inner class" (which some other stackoverflow answers suggest that are not serious warnings), and then shows nothing but a blinking cursor for a while, and after about one minute, it gives me the error.

A: Have you tried adding the heap size adjustment to your build.gradle file? For example this will set the max heap size for dexing to 4GB.
android {
    ...
    dexOptions {
        javaMaxHeapSize "4g"
    }
}

A: Try this in build gradle
android {
compileSdkVersion 21
buildToolsVersion "21.1.1"

defaultConfig {
           minSdkVersion 14 //lower than 14 doesn't support multidex
           targetSdkVersion 21
// Enabling multidex support.
           multiDexEnabled true
    }
 }
dependencies {
   compile 'com.android.support:multidex:1.0.0'
  }


text:
Q: How can I generate encrypted key in apex same as generated by the below java class package com.fivestar.crypto;
//of Encryption with Java AES
import java.security.NoSuchAlgorithmException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.Cipher;
import java.security.SecureRandom;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.util.Base64;
import java.security.InvalidKeyException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;

public class Encrypt {
    static Logger log = LogManager.getLogger(Encrypt.class.getName());
    public static byte[] generateIV() throws IllegalArgumentException {
            log.info("generateIV function started");
            SecureRandom random = new SecureRandom();
            byte[] salt = new byte[16];
            random.nextBytes(salt);
            log.info("generateIV function ended");
            return salt;
    }
    // This method use to encrypt to string
    public static String encrypt(String strToEncrypt, String secretKey) {
        try {
            log.info("Encrypt block start");
            byte[] ivGen = generateIV();
            IvParameterSpec iv = new IvParameterSpec(ivGen);
            String ivValue = Base64.getEncoder().encodeToString(ivGen);
            SecretKeySpec skeySpec = new SecretKeySpec(secretKey.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(strToEncrypt.getBytes("UTF-8"));
            log.info("Encrypt block ended");
            return Base64.getEncoder().encodeToString(encrypted)+"."+ ivValue;
        } catch(NoSuchAlgorithmException e) {
            log.error("Error!", e);
            throw new RuntimeException("Error as no such algorithm exists",e);
        } catch(NoSuchPaddingException e){
            log.error("Error!", e);
            throw new RuntimeException("Error as no such padding exists",e);
        } catch(InvalidKeyException e){
            log.error("Error!", e);
            throw new RuntimeException("Error as invalid key",e);
        } catch(IllegalBlockSizeException e){
            log.error("Error!", e);
            throw new RuntimeException("Error as illegal block size",e);
        } catch(BadPaddingException e){
            log.error("Error!", e);
            throw new RuntimeException("Error due to bad padding",e);
        } catch (Exception e) {
            log.info("Error while encrypting: " + e.toString());
            throw new RuntimeException("Error while encrypting",e);
        }
    }
}


text:
Q: How to alter a column to accept values in some specific format? My table has a column that shows the phone number and I want to add a constraint where this number must be in a specific format like +cod.country-cod.local-num.local. For example: '+54-351-4350114'.
And later I want to add a constraint where num.local must have at least 7 digits.

A: I guess that you are looking for a Postgres CHECK constraint: such constraint does accept a regexp, with the SIMILAR TO operator:
ALTER TABLE mytable ADD CONSTRAINT phone_number_check CHECK(
    phone_number SIMILAR TO '\+\d+-\d+-\d{7,}'
)

Regexp explanation:
\+        the + sign
\d+       at least one digit
-         the - sign
\d+       at least one digit
-         the - sign
\d{7,}    at least 7 digits

This will allow values like '+54-351-1234567', while, for example rejecting '+54-351-123456'. You can freely adapt the regexp to your exact requirement, using Postgres Regular Expressions.
Demo on DB Fiddle


text:
Q: copying data from a webpage to string in cpp using cURL I got a function off of a friend that he found on the net. Problem is, neither of us understand how it works. It copies the contents of the webpage to the string.
We're using cURL to connect to a php page.
The function in question is:
std::string contents;

size_t handle_data(void *ptr, size_t size, size_t nmemb, void *stream)
        {
                    int numbytes = size*nmemb;
                    char lastchar = *((char *) ptr + numbytes - 1);
                    *((char *) ptr + numbytes - 1) = '\0';
                    contents.append((char *)ptr);
                    contents.append(1,lastchar);
                    *((char *) ptr + numbytes - 1) = lastchar;  // Might not be necessary.
                    return size*nmemb;
        }

Its called in this function:
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,handle_data);

Any explanations into how this works would be great.
Cheers.

A: I think this is correct:
std::string contents;

size_t handle_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
  // The number of bytes to transfer is simply the
  // number of elements (nmemb) times the size of
  // each element (size).
  int numbytes = size*nmemb;

  // Remember the last character of the data we'll
  // be appending to 'contents', because we're about
  // to overwrite it with a zero C-string nul terminator.
  char lastchar = *((char *) ptr + numbytes - 1);

  // Overwrite the last character of ptr's data block
  // with zero, which is a C-string's nul-terminator.
  *((char *) ptr + numbytes - 1) = '\0';

  // Append the C-string which begins at 'ptr' to
  // 'contents'.
  contents.append((char *)ptr);

  // Now tack on the last character that we remembered above.
  contents.append(1,lastchar);

  // Restore the original data buffer's last character
  // in case the caller expects it to still be the same.
  *((char *) ptr + numbytes - 1) = lastchar;  // Might not be necessary.

  // Return the number of bytes  that were appended
  // to 'contents'.
  return size*nmemb;
}

Having said all that, I'm not sure why the whole guts of handle_data() isn't simply this:
size_t handle_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
    contents.append((char*)ptr, size*nmemb);
    return size*nmemb;
}

...which I think would accomplish the exact same thing, only more correctly, since the published version will stop early if the buffer at 'ptr' contains an embedded null character.  (Of course that's probably not a use case for this function anyway.)

A: If I had to describe how it works, I'd say: "not particularly well".
int numbytes = size*nmemb;

This computes the size of the buffer -- number of items * size of each item.
char lastchar = *((char *) ptr + numbytes - 1);

This saves the last character in the buffer for later use.
*((char *) ptr + numbytes - 1) = '\0';

This adds a NUL terminator to the buffer, overwriting what's currently the last character (which is why the preceding saved it).
contents.append((char *)ptr);

This appends the (truncated) buffer to the string.
contents.append(1,lastchar);

This adds the saved last character to the string.
*((char *) ptr + numbytes - 1) = lastchar;  // Might not be necessary.

This restores the last character back into the buffer.
return size*nmemb;

And this returns the buffer size.
I suppose I should explain why I say this doesn't work very well. It's not that the end result appears to be wrong, but because all the gyration with the final character in the buffer is entirely unnecessary. Instead of NUL terminating the buffer, you can just specify the amount to append to the string:
size_t numbytes = size * nmemb;
contents.append((char *)ptr, numbytes);
return numbytes;

...or, if you prefer a more iterator-like usage:
size_t numbytes = size * nmemb;
char *p = (char *)ptr;
contents.append(p, p+numbytes);
return numbytes;

I'm guessing that if you'd found one like these, you wouldn't have had to post a question about how it worked.


text:
Q: Using Multiple Profile Providers with Overlapping Properties I am working with a site that needs to use two different asp.net profile providers. They are both added in the web.config and the properties of each of them are listed there as well. I run into a problem when I try to enable a property that has the same name in each provider. Comment one out, and the site will at least load. Leave both in, and I get an error like:
Item has already been added. Key in dictionary: 'myfieldname'  Key being added: 'MyFieldName'
The properties are entirely different (different types even), but I am missing how I would allow both to be used.
There must be some way I am missing as this seems like it could be a common problem.

A: I've only ever implemented a single profile system with a Web Application project. With the Website template, the functionality is out of the box. Profiles allow you to store some extra information per user when using the ASP.NET membership system. Profiles are stored in the database automatically when we add this extra information to our web.config file.
It makes sense that there would be a clash if you are using profile properties with the same names - a possible solution would be to create your own table mapping - for example, give 'MyFieldName' an alias in the web.config but map it to the real property name in your code. Since much of the functionality is out-of-the-box with the website template, you may be limited in the amount of customization you can perform.
The following links may help:
http://code.msdn.microsoft.com/WebProfileBuilder
http://weblogs.asp.net/joewrobel/archive/2008/02/03/web-profile-builder-for-web-application-projects.aspx
http://weblogs.asp.net/jgalloway/archive/2008/01/19/writing-a-custom-asp-net-profile-class.aspx


text:
Q: How close to P1dB can I go? I'm trying to decide on a safe input power to a power amplifier. The amplifier in question is SE5004L. The datasheet specifies that the amplifier output 1-dB compression point has a minimum value of 30dBm and a typical value of 34dBm. The small-signal gain is 32dBm. Without making any further adjustments in my design, the input power to it would be -1dBm, putting the output power at about 31dBm. However, this is close to the 1-dB compression point and the datasheet specifies a 26dBm output power at 3% EVM. I have a 6dB attenuator that I can use, which would bring the output power about to the typical range in the datasheet. I'd like to get as much output power as possible, but not if it significantly distorts my signal. Is it generally ok to operate near the 1-dB compression point, or is it better to stay 5-10dBm below? This is for a FMCW radar operating at around 6GHz.

A: It all depends on how much distortion you can tolerate, and any other side effects that may occur when saturating the amplifier (harmonics, etc.). You might be fine running several dB over the P1dB point. Or maybe you need to stay several dB below. You might just need to experiment. If your FMCW radar can tolerate some distortion, then you might be able to hit it pretty hard. On the other hand, if you're using a digital modulation like high order QAM, you might need to stay well below the P1dB point.


text:
Q: Round Product Price In magento 2 I want to modification in the product price. For example, if the product has priced $13.45 then it should display $13 but the price is more than $13.50 it should be $14.
So how to modify product price?

A: First you need to override Magento\Catalog\Model\Product using di.xml
Path of di.xml: Vendor/Module/etc/di.xml
<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
  <type name="Magento\Catalog\Model\Product">
    <plugin name="productpricechange" type=" Vendor\Module\Plugin\Product" sortOrder="1" />
  </type>
</config>

Now create a plugin file path should be: Vendor/Module/Plugin/Product.php
<?php

namespace Vendor\Module\Plugin;

    class Product
    {
        public function afterGetPrice(\Magento\Catalog\Model\Product $subject, $result)
        {
            return round($result);
        }
    }

I hope this will help

A:
round Function

<?php
$price = 13.45;
echo(round($price)); //output 13

$price_change = 13.50;
echo(round($price_change)); //output 13
?>

A: First, you need to create di.xml for create plugin :

/app/code/Vendor/Module/etc/di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Magento\Directory\Model\Currency">
    <plugin name="vendor_module" type="Vendor\Module\Model\Plugin\Currency" />
</type>

Now, create plugin file

/app/code/Vendor/Module/Model/Plugin/Currency.php

<?php
namespace Vendor\Module\Model\Plugin;
use Magento\Framework\Exception\InputException;

class Currency
{
    public function aroundConvert($subject, $proceed, $price, $toCurrency = null)
    {
        $price = $proceed($price, $toCurrency);
        // Your logic
        return $price; // It will be affect in price of shipping also.
    }
}

It will be rounding price with Multi-Currency Stores.
For reference : click here


text:
Q: Redrawed inset NSShadow on a Custom View using -setClip method I have and odd problem, related with the answer of this question:
Draw an Inset NSShadow and Inset Stroke
I use this code into the drawRect method of a custom view. I have exactly this:
- (void)drawRect:(NSRect)rect
{
    // Create and fill the shown path
    NSBezierPath *path = [NSBezierPath
                          bezierPathWithRoundedRect:[self bounds]
                          xRadius:4.0f
                          yRadius:4.0f];

    [[NSColor colorWithCalibratedWhite:0.8f alpha:0.2f] set];

    [path fill];

    // Save the graphics state for shadow
    [NSGraphicsContext saveGraphicsState];

    // Set the shown path as the clip
    [path setClip];

    // Create and stroke the shadow
    NSShadow * shadow = [[[NSShadow alloc] init] autorelease];
    [shadow setShadowColor:[NSColor colorWithCalibratedWhite:0.0f alpha:0.8f]];
    [shadow setShadowBlurRadius:2.0];
    [shadow set];
    [path stroke];

    // Restore the graphics state
    [NSGraphicsContext restoreGraphicsState];

    if ( highlight && [[self window] firstResponder] == self ) {
        NSSetFocusRingStyle(NSFocusRingOnly);
        [[NSBezierPath bezierPathWithRect:[self bounds]] fill];
    }
}

The problem comes when I add a Multiline Label (either sibling or child of my custom view).
When my program window loses the focus and I come back to it, my inner shadow / stroke go darker. It seems that the shadows superimpose. It's strange because as said, if my window only have this custom view, it goes well.
If I comment the line
[path setClip];

the shadow isn't superimposed anymore, but I don't get the desired effect of rounded corners (similar than NSBox).
I tried what happens with a Push Button instead of a Multiline Label, and by losing / getting the window focus it has no problems, but when I click the button the shadow gets superimposed.
I find the problem is similar than here, but in Cocoa instead of Java:
Java setClip seems to redraw
Thanks for your help!

A: You should never use -setClip unless you know what you're doing. You should use -addClip instead, which respects the existing clipping paths.


text:
Q: Remove Hex Code from String in R I have converted a .doc document to .txt, and I have some weird formatting that I cannot remove (from looking at other posts, I think it is in Hex code, but I'm not sure).
My data set is a data frame with two columns, one identifying a speaker and the second column identifying the comments. Some strings now have weird characters. For instance, one string originally said (minus the quotes):
"Why don't we start with a basic overview?"

But when I read it in R after converting it to a .txt, it now reads:
"Why don<92>t we start with a basic overview?"

I've tried:
df$comments <- gsub("<92>", "", df$comments)

However, this doesn't change anything. Furthermore, whenever I do any other substitutions within a cell (for instance, changing "start" to "begin", it changes that special character into a series of weird ? that're surrounded in boxes.
Any help would be very appreciated!
EDIT:
I read my text in like this:
df <- read_delim("file.txt", "\n", escape_double = F, col_names = F, trim_ws = T)

It has 2 columns; the first is speaker and the second is comments.

A: I found the answer here: R remove special characters from data frame
This code worked: gsub("[^0-9A-Za-z///' ]", "", a)


text:
Q: File is read-only while picking from android storage access framework I'm trying to append a text to a file using the URI which i receive from an intent. When I pick the file directly from the storage, everything works perfectly fine. Nevertheless, the problem occurs when I pick the file from categorized selectors like Pictures, Videos, Musics and etc... It throws an IllegalArgumentException and says that the file is read-only.
private fun alterDocument(uri: Uri) {

    try {

        val subject = subjectField.editText!!.text.toString()
        val message = messageField.editText!!.text.toString()
        contentResolver.openFileDescriptor(uri, "wa")?.use { it ->
            // use{} lets the document provider know you're done by automatically closing the stream
            FileOutputStream(it.fileDescriptor).use {
                it.write("\n".toByteArray())
                it.write(
                    generateJSON(subject, message).toByteArray()
                )
            }
        }

    } catch (e: FileNotFoundException) {
        e.printStackTrace()
    } catch (e: IOException) {
        e.printStackTrace()
    }

}

Does anyone knows any way to solve this problem? Thanks in advance.

A: A DocumentsProvider does not have to grant read-write access to its content. In particular, MediaDocumentsProvider does not.
Unfortunately, we do not have a way to limit the user to read-write content. So, you are going to need to gracefully handle this error and suggest to the user that they pick from a different documents provider.
Or, to detect the problem more positively, you would need to check the document's flags to see if FLAG_SUPPORTS_WRITE is among them.
I blogged a bit more about this situation.


text:
Q: Vue router single page app, should the page reload? I have a question I have vue router set up which works, however I have a question about how is it a single page app. When I click on the link, page is reloading therefore it is not really a single page app is it?
Here's my nginx configuration:
# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/webuilder.co.uk/before/*;

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name webuilder.co.uk;
    root /home/forge/webuilder.co.uk/current;

    # FORGE SSL (DO NOT REMOVE!)
    ssl_certificate /etc/nginx/ssl/webuilder.co.uk/279163/server.crt;
    ssl_certificate_key /etc/nginx/ssl/webuilder.co.uk/279163/server.key;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-$
    ssl_prefer_server_ciphers on;
    ssl_dhparam /etc/nginx/dhparams.pem;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    # FORGE CONFIG (DOT NOT REMOVE!)
    include forge-conf/webuilder.co.uk/server/*;

    location / {
        try_files $uri $uri/ /index.html;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;

Routes:
import Create from '../vue/components/homepage/create.vue';
import How from '../vue/components/homepage/how.vue';
import About from '../vue/components/homepage/about.vue';
import Youtube from '../vue/components/homepage/youtube.vue';
import Login from '../vue/components/auth/login.vue';
import Register from '../vue/components/auth/register.vue';

export default [
    { path: '/', component: Create },
    { path: '/how', component: How },
    { path: '/about', component: About},
    { name: 'youtube', path: '/youtube', component: Youtube},
    { path: '/login', component: Login},
    { path: '/register', component: Register},
];

Vue.use(VueRouter);
Vue.component('homenav', Navigation);
Vue.component('mainav', Navigation2);

const router = new VueRouter({
  mode: 'history',
  routes: Router
});

new Vue({
  el: '#nav',
  data: {
    nav: 'homeNav'
  },
  methods: {
    switchNav: function (nav) {
      this.nav = nav;
    }
  }
});

new Vue({
  el: '#app',
  router,
  updated: function () {
    Pace.restart()
  },
});

and it can be seen at:
https://webuilder.co.uk
Can someone just explain and clarify if that is a expected behaviour of SPA? I thought it will not reload but change the component itself which it does if i turn history mode off and add '#'...

A: You need to use <router-link> instead of <a> when you want to route to a particular router page:

In HTML5 history mode, router-link will intercept the click event so that the browser doesn't try to reload the page.


text:
Q: Error with admob ads, android-studio compiler I downloaded all the files that were needed according to the admob website.
I had some issues along the way, but i found ways to deal with each of them.
But i cannot get past this one and i do not know why?
when I tried to compile my app, it failed and showed the following code in the "message" area
Error:The number of method references in a .dex file cannot exceed 64K.
Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html

I do not have ANY idea how to get past this, if ANYONE can help please do!
sorry if this question is badly asked or something!

A:
Android application (APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app. The Dalvik Executable specification limits the total number of methods that can be referenced within a single DEX file to 65,536—including Android framework methods, library methods, and methods in your own code. In the context of computer science, the term Kilo, K, denotes 1024 (or 2^10). Because 65,536 is equal to 64 X 1024, this limit is referred to as the '64K reference limit'.
Getting past this limit requires that you configure your app build process to generate more than one DEX file, known as a multidex configuration

Change your Gradle build configuration to enable multidex
    android {
    compileSdkVersion 21
    buildToolsVersion "21.1.0"

    defaultConfig {
        ...
        minSdkVersion 14
        targetSdkVersion 21
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.0'
}

In your manifest add the MultiDexApplication class from the multidex support library to the application element.
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>


text:
Q: MVC .net core : response type always json not xml with ICollection I use this contribution for return json or xml depending "Accept" header.
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/formatting
services.AddMvc(options =>
{
    options.RespectBrowserAcceptHeader = true;
    options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});

My object
public partial class Cartes
{
    public Cartes()
    {

    }

    public string CartNumero { get; set; }
    public int? CartConsId { get; set; }
    public int CartLotcaId { get; set; }
    public int CartTypcaId { get; set; }
    public string CartCrc { get; set; }
    public DateTime? CartDateAttribution { get; set; }
    public DateTime? CartDateClotureCarte { get; set; }
    public DateTime? CartDateSaisie { get; set; }
}

It's Work !
But when I add an ICollection property to Cartes the return is always in JSON !
public virtual ICollection<UtilisationsCriteres> UtilisationsCriteres { get; set; }

UtilisationsCriteres class :
public partial class UtilisationsCriteres
{
    public int UtcriConsId { get; set; }
    public int UtcriCrsupId { get; set; }
    public string UtcriValeur { get; set; }
    public int UtcriPartclieId { get; set; }
    public DateTime UtcriDateInsert { get; set; }
    public DateTime UtcriDateUpdate { get; set; }
    public string UtcriUserUpdate { get; set; }
}

The return type of the controller is IActionResult.
Any idea why ?

A: I can confirm that (weird) behaviour. The collection can be null (or empty) and the content changes from application/xml to application/json.
XML serializator seems to be lost when using an interface instead of a concrete type. Maybe you should create a new issue on https://github.com/aspnet/Mvc/issues.
The workaround is to use concrete classes. Changing ICollection<UtilisationsCriteres> to System.Collections.ObjectModel.Collection<UtilisationsCriteres> or List<UtilisationsCriteres> seems to work.


text:
Q: How to subclass QGLWidget to use glew? I'm struggling to get a subclass of QGLWidget compiled that uses glew. I'm running Qt 5.0.1 + MinGW 4.7 on Windows 7. Glew 1.7.0 has been compiled with said MinGW.
I have subclassed QGLWidget with UGGLWidget and included "GL/glew.h" before the QGLWidget includes. When compiling I get 200 Errors about:

*

*'function' redeclared as different kind of symbol

*conflicting declaration 'typedef'

So my Question:
How do I get a subclass of QGLWidget that uses glew compiled under Qt5?

Edit: I tried the same approach with another setup (Qt4.7 + MinGW4.4). It compiles and runs just fine. I have also tried using a more recent version of glew (Qt5.0.1 + MinGW4.7 + glew1.9.0) this doesn't compile either and gives the same compilation errors.

Here's a messy snippet of the compiler output:
> In file included from
> ..\..\..\..\..\..\Qt\Qt5.0.1\5.0.1\mingw47_32\include/QtGui/qopengl.h:55:0,
>                  from ..\..\..\..\..\..\Qt\Qt5.0.1\5.0.1\mingw47_32\include\QtOpenGL/qgl.h:47,
>                  from ..\..\..\..\..\..\Qt\Qt5.0.1\5.0.1\mingw47_32\include\QtOpenGL/QGLWidget:1,
>                  from src\UGGLWidget.h:4,
>                  from src\UGGLWidget.cpp:2: ..\..\..\..\..\..\Qt\Qt5.0.1\5.0.1\mingw47_32\include/GLES2/gl2.h:614:153:
> error: 'void __glewVertexAttribPointer(GLuint, GLint, GLenum,
> GLboolean, GLsizei, const GLvoid*)' redeclared as different kind of
> symbol In file included from src\UGGLWidget.cpp:1:0:
> ..\3rdPartyLibs\glew\include/GL/glew.h:13609:46: error: previous
> declaration of 'void (__attribute__((__stdcall__)) *
> __glewVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid*)'

Last but not least the header and source file of the subclass. It's really just empty for now.
Source:
//UGGLWidget.cpp
#include "GL/glew.h"
#include "UGGLWidget.h"

UGGLWidget::UGGLWidget(QWidget *parent) : QGLWidget(parent) { ... }

Header:
//UGGLWidget.h
#ifndef UGGLWIDGET_H
#define UGGLWIDGET_H
#include <QGLWidget>

class UGGLWidget : public QGLWidget
{
    Q_OBJECT
public:
    explicit UGGLWidget(QWidget *parent = 0);
};
#endif // UGGLWIDGET_H

Oh, and maybe relevant parts from the .pro file
QT       += core gui opengl
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
LIBS += -L$$quote(../3rdPartyLibs/glew/lib/) -lglew32
LIBS += -lopengl32 -lglu32
INCLUDEPATH += $$quote(../3rdPartyLibs/glew/include)

A: The following fixed my problem, this goes everywhere, where I include glew:
#include "GL/glew.h"
#define QT_NO_OPENGL_ES_2

Another option: building Qt5.0.1 from source with -opengl desktop during the configure step.

For some reason QT_OPENGL_ES_2 is defined in my Qt5.0.1 installation. Looking through the inlcudes from QGLWidget.h I found the following in QtCore/qconfig.h
#if defined(QT_OPENGL_ES_2) && defined(QT_NO_OPENGL_ES_2)
# undef QT_OPENGL_ES_2
#elif !defined(QT_OPENGL_ES_2)
# define QT_OPENGL_ES_2
#endif

This leads to inclusion of GLES2/gl2.h which doesn't get along with glew. Knowing that the issue was related to GLES2 I came across a bug report and a QtProject post.
If I understand correctly, then the provided QtSDK installer for Qt5.0.1 has been built such that GLES is enabled.
Have a good day,
~Moritz

A: Note that QT 4.8RC release notes say:
 Including QtOpenGL will not work in combination with GLEW, as QGLFunctions will undefine GLEW's defines.


text:
Q: @RequestAttribute in a Spring MVC project does not fetch the value @RequestAttribute in a Spring MVC project doesn't fetch the value.
I use a @ModelAttribute. Here foo attribute is set a value of bar
@ModelAttribute
void beforeInvokingHandlerMethod(HttpServletRequest request)
{
    request.setAttribute("foo", "bar");
}

I try to invoke the request attribute value for foo using @RequestAttribute("foo"). But value is null.
Then I try using request.getAttribute("foo") and the value is printed. I don't know what is wrong in the following code:
@RequestAttribute("foo").
@RequestMapping(value="/data/custom", method=RequestMethod.GET)
public @ResponseBody String custom(@RequestAttribute("foo") String foo, HttpServletRequest request) {
    System.out.println("foo value : " + foo);    //null printed
    System.out.println("request.getAttribute : " + request.getAttribute("foo"));    //value printed

    return foo;
}

A: @RequestAttribute is not a Spring annotation.  If you want to pass a value a request param you can do
@RequestMapping(value="/data/custom", method=RequestMethod.GET)
public @ResponseBody String custom(@RequestParam("foo") String foo) {
    System.out.println("foo value : " + foo);    //null printed
    return foo;
}

Or if you want to pass values in the path you can do
@RequestMapping(value="/data/custom/{foo}", method=RequestMethod.GET)
public @ResponseBody String custom(@PathVariable("foo") String foo) {
    System.out.println("foo value : " + foo);    //null printed
    return foo;
}


text:
Q: Can the same-origin request policy be disabled in Microsoft Edge? The same-origin request policy can be disabled in Chrome using the --disable-web-security flag and in Internet Explorer by changing the security/zone settings.
Is it possible to temporarily disable the same-origin policy in Microsoft Edge?
NOTE: I'm not interested in answers/comments about why this policy exists, why I shouldn't disable it, how to use CORS headers (access-control-allow-origin and the like). I only want to know if there's a way to disable the policy in Edge like you can in other browsers.

A: Edge now exposes experimental flags, including CORS functionality. Try typing edge:\\flags in the address bar, then searching for CORS. Making a change requires restarting the browser.

A: No. The concept of security zones is completely gone in Edge; it doesn't respect the Internet Options dialog from IE11 either. Edge has no command-line parameters (though it can be launched from the command line either with shell: followed by its app ID or with microsoft-edge: followed by the URL). The advanced options don't produce anything useful either.
However, there is a workaround, kind of: Edge has a few Group Policy settings. You can open the Local Group Policy Editor by running gpedit.msc if you don't have a domain. Navigate to the Configure the Enterprise Mode Site List policy (in Computer Configuration → Administrative Templates → Windows Components → Microsoft Edge). Sites you put in the "URI" box will be automatically opened in Internet Explorer 11 when you navigate to them in Edge. You can then, of course, configure security settings just as before.
This workaround is really quite sad, and I am always disappointed when rewrites of programs are missing huge chunks of configurability. As has been mentioned in the comments, it may be better to adjust (or even intercept and change via proxy, if you have to) the headers on the appropriate pages.

A: If you need to do this on Edge for Mac, the options mentioned in the accepted answer don't exist.
You can disable CORS on Edge for Mac: https://add0n.com/access-control.html


text:
Q: cannot show header text of primefaces datatable I have the below code, but find that the headerText doesn't show. Any advice?
<p:dataTable var="toDoList" value="#{dtView}" tableStyle="width:auto" >
    <p:columnGroup type="header">
        <p:row><p:column  headerText="#{toDoList.schoolScrn}">
            <p:outputLabel value="#{toDoList.schoolScrn}" />
        </p:column></p:row>
    </p:columnGroup>
    <p:column>
        <p:dataTable var="info" value="#{toDoList.infoList}" >
            <p:column >
                <h:outputText value="#{info}" />
            </p:column>
        </p:dataTable>
    </p:column>
</p:dataTable>


text:
Q: pscp between linux and windows I am trying to scp file(s) from window to linux.
user is windows system, we are executing pscp from linux command
Command used :
pscp user@ip:source dest

It shows :
unable to identify source: permission denied

If I use it in this way,
pscp source user@ip:dest

It works fine and copy the files to windows.
Am I using correct format?
We need to copy from remote windows, but the commands needs to be invoked from local linux system.

A: Here is an example of how I copy a file from my windows machine to my linux machine

C:\Users...\Downloads>pscp -i "DEV_IRM.ppk"
  product-sp-4.2.0-rc2.tar.gz
  prvclouduser@10.149.137.26:/home/prvclouduser/sp420

Make sure that you are in the directory where the file you want to copy is located. In my case 'Downloads' directory.
Private key for access: DEV_IRM.ppk
My linux server: prvclouduser@10.149.137.26
The landing directory in linux: /home/prvclouduser/sp420 (make sure this exists; do pwd to confirm full path)


text:
Q: Prevent listening events on certain DOM elements Besides the new Shadow Dom and the old HTML iframe element, is there a way to prevent users from listening for [delegated] events on DOM elements inside my widget?
P.S. I heard Firefox had XBL which has features similar to Shadow DOM. Is it currently supported?

A: Read how delegating event handling works.
So, I don't think that it's possible. Until you block event propagating on root level (e.g. document).
Or you can override (HTMLElement||Element).prototype.addEventListener method.
But why do you need it?


text:
Q: Find PMF of $U=X+Y$ Let $X$ and $Y$ be two independent discrete random variables such that:
P$(y)=1/3,\; y=-1,0,1$
$P(x)=1/2,\; x=2,4$
Let $U=X+Y$
Find the probability mass function of $U.$
I currently have the sum of all $y, x$ of the probability of $X$ multiplied by the probability of $Y$ but it feels wrong :S.
Thanks, any help would be appreciated.

A: I believe I was able to answer this myself. I calculated the MGF of X and Y then the MGF of U using those and I used the coefficients from the MGF of U and ended up with:
$P$($U$=1)=1/6
$P$($U$=2)=1/6
$P$($U$=3)=1/3
$P$($U$=4)=1/6
$P$($U$=5)=1/6
If anyone could confirm this for me or tell me why it is wrong or maybe a better way to go about it then that would be greatly appreciated. Thanks!


text:
Q: javascript missing ) argument I'm getting this error with this javascript can anyone help me figure out what i'm doing wrong?
$(this).prepend('Check availability »');

It's giving me the error
missing ) after argument list

Can anyone help?
Thanks
Jamie

A: It looks like you need to escape some single quotes in there:
... __doPostBack(\'SetSess\',\'\') ...

A: You need to escape enclosed quotes like this:
__doPostBack(\'SetSess\',\'\')

A: Just for your information, but there is a better syntax then to prepend the whole thing as a huge HTML fragment. You can construct the whole thing with jQuery from scratch:
var anchor = $('', {
    'class': 'booknow2 sidelink sidelinkNew',
    // Try to use event handlers instead - inline event handlers are *bad*
    href: "javascript:__doPostBack('SetSess','')"
}).prependTo(this);

$('', {
    'width': '4',
    'height': '35',
    'alt': 'book now',
    'src': '../../images1/button/rightEdge.png'
}).css({
    // Try to use CSS instead - add a class
    // and define the CSS in a separate stylesheet
    'float': 'left',
    'margin': 0,
    'padding': 0,
}).appendTo(anchor);

$('', {
    html: 'Check availability »'
}).appendTo(anchor);


text:
Q: Javascript: Transform array of object response via lodash or underscore or corejavascript I am working with highChart to create a column chart. Any how I reached to creating following arrayofObj via communicating with database.
Now, I require to transform following source array of object to below output.
var source = [
{data: 258, name: '2014'}
{data: 18, name: '2016'}
{data: 516, name: '2014'}
{data: 0, name: '2014'}
{data: 354, name: '2014'}
{data: 18, name: '2016'}
]`

Convert this array of object to
Output

[{
    name: '2014',
    data: [258, 516, 354]
  }, {
    name: '2016',
    data: [18, 0, 18]
}]

Basically, I want my array to group by name (year) and data should be in array
Here is the solutions which i have applied.
var source = [];
_.each(source, function(singlerec) {
      source.push({
        name: singlerec.name,
        data: singlerec.data  // Here It only assign single record
      });
    });

A: In Lodash, I always use _.groupBy and then _.map to the output format.

var source = [{"data":258,"name":"2014"},{"data":18,"name":"2016"},{"data":516,"name":"2014"},{"data":0,"name":"2014"},{"data":354,"name":"2014"},{"data":18,"name":"2016"}];

var output = _(source)
  .groupBy('name')
  .map(function(v, k) { return { name: k, data: _.map(v, 'data') } })
  .value();

console.log(output);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

A: I use a pure javascript function:
const pick = (obj, paths) => ({...paths.reduce((a, k) => ({...a, [k]: obj[k]}), {})})

function groupByAndConcat(data, groupBy, sums) {
    return data.reduce((results, r) => {
        const e = results.find((x) => groupBy.every((g) => x[g] === r[g]));
        if (e) {
            sums.forEach((k) => e[k] = [].concat(e[k], r[k]));
        } else {
            results.push(pick(r, groupBy.concat(sums)));
        }
        return results;
    }, []);
}

So given your sample source:
const source = [
    {data: 258, name: '2014'},
    {data: 18, name: '2016'},
    {data: 516, name: '2014'},
    {data: 0, name: '2014'},
    {data: 354, name: '2014'},
    {data: 18, name: '2016'},
];

console.log(groupByAndConcat(source, ["name"], ["data"]))

outputs:
[{ name: "2014", data: Array [258, 516, 0, 354] }, { name: "2016", data: Array [18, 18] }]

It is also possible to group by or do operations on several props:
groupByAndConcat(source, ["name","month"], ["data","data2"])

A: there's a way to iterate array once with reduce and even without lodash.
source.reduce((p, n) => {
    (p[n.name] || (p[n.name] = [])).push(n.data);
    return p
}, {})


text:
Q: Variant Rouche's theorem Set $\mathbb{D}=D_1(0)$. Let $f$ & $g$ holomorphic functions in a neighborhood of the disc $\mathbb{D}$ such that $f(z)\not=0$ and $\frac{g(z)}{f(z)}\notin(-\infty,0]$ for all $z\in\partial\mathbb{D}$. Then $f$ & $g$ have the same zeros (multiplicity counting) on $\mathbb{D}$

A: Let $\displaystyle h(z)=\frac{g(z)}{f(z)}$ and $\gamma(t)=e^{it}$ , $t\in [0,2\pi]$
$Z_h=Z_g$ , $P_h=Z_f$ (we can assume that $f$ and $g$ have no common zeros)
The argument principle states that
$\displaystyle Z_h-P_h=\frac{1}{2\pi i}\int_{\gamma}\frac{h'(t)}{h(t)}dt=\frac{1}{2\pi i}\int_{h\circ \gamma}\frac{1}{w}dw=0$ , $\displaystyle\frac{1}{w}$ has primitive on $\mathbb{C}-(-\infty,0]$
Therefore $Z_f=Z_g$ on $B(0,1)$.


text:
Q: Unique elements in each file

I have 4 files and would like to know elements which are non overlapping (per file) compared to the elements in other files.
File A
Vincy
ruby
rome

File B
Vincy
rome
Peter

File C
Vincy
Paul
alex

File D
Vincy
rocky
Willy

Any suggestion for one liner in perl, python, shell, bash. The expected output is:
File A: ruby, File B: Peter, File C: Paul, Alex File D: rocky, Willy.

A: Here is a quick python script that will do what you ask over an arbitrary number of files:
from sys import argv
from collections import defaultdict

filenames = argv[1:]
X = defaultdict(list)
for f in filenames:
    with open(f,'r') as FIN:
        for word in FIN:
            X[word.strip()].append(f)

for word in X:
    if len(X[word])==1:
        print "Filename: %s word: %s" % (X[word][0], word)

This gives:
Filename: D word: Willy
Filename: C word: alex
Filename: D word: rocky
Filename: C word: Paul
Filename: B word: Peter
Filename: A word: ruby

A: Edit after question clarified: Unique elements across all files, and the file in which it occurs:
cat File_A File_B File_C File_D |sort | uniq -u | while read line ; do file=`grep -l $line File*` ; echo "$file $line" ; done

Edit:
perly way of doing it, will be faster if the files are large:
#!/usr/bin/perl

use strict;
use autodie;

my $wordHash ;

foreach my $arg(@ARGV){
    open(my $fh, "<", $arg);
    while(<$fh>){
        chomp;
        $wordHash->{$_}->[0] ++;
        push(@{$wordHash->{$_}->[1]}, $arg);
    }
}

for my $word ( keys %$wordHash ){
    if($wordHash->{$word}->[0] eq 1){
        print $wordHash->{$_}->[1]->[0] . ": $word\n"
    }
}

execute as:
    myscript.pl filea fileb filec ... filezz
stuff from before clarification:
Easy enough with shell commands.  Non repeating elements across all files
cat File_A File_B File_C File_D |sort | uniq -u

Unique elements across all files
cat File_A File_B File_C File_D |sort | uniq

Unique elements per file
(edit thanks to @Dennis Williamson)
for line in File* ; do echo "working on $line" ; sort $line | uniq ; done

A: Hot needle:
import sys
inputs = {}
for inputFileName in sys.args[1:]:
  with open(inputFileName, 'r') as inputFile:
    inputs[inputFileName] = set([ line.strip() for line in inputFile ])
for inputFileName, inputSet in inputs.iteritems():
  print inputFileName
  result = inputSet
  for otherInputFileName, otherInputSet in inputs.iteritems():
    if otherInputFileName != inputFileName:
      result -= otherInputSet
  print result

Didn't try it though ;-)

A: Perl one-liner, readable version with comments:
perl -nlwe '
    $a{$_}++;     # count identical lines with hash
    push @a, $_;  # save lines in array
    if (eof) { push @b,[$ARGV,@a]; @a=(); }   # at eof save file name and lines
    }{ # eskimo operator, executes rest of code at end of input files
    for (@b) {
        print shift @$_;                      # print file name
        for (@$_) { print if $a{$_} == 1 };   # print unique lines
    }
' file{A,B,C,D}.txt

Note: eof is for each individual input file.
Copy/paste version:
perl -nlwe '$a{$_}++; push @a, $_; if (eof) { push @b,[$ARGV,@a]; @a=(); } }{ for (@b) { print shift @$_; for (@$_) { print if $a{$_} == 1 } }' file{A,B,C,D}.txt

Output:
filea.txt
ruby
fileb.txt
Peter
filec.txt
Paul
alex
filed.txt
rocky
Willy

Notes: This was trickier than expected, and I'm sure there's a way to make it prettier, but I'll post this for now and see if I can clean it up.


text:
Q: Table View not showing all 20 items in my list Making a project for school everything is working except when i ran my project i was getting a duplicate of my items in my list after 10. (i.e. items 1,2,3,4 will show up again as 11,12,13,14) Only i have console displaying the rows, like 2013-05-08 23:29:27.059 ToolBox[42792:c07] row=16 name=Flashlight but the UI shows it as a Putty Knife, an object that was already displayed on row 6 2013-05-08 23:30:22.913 ToolBox[42792:c07] row=6 name=Putty knife. I'm sorry this is kind of hard to explain. Ive stretched the view of the Table View past the bottom of the Frame screen and it does show the correct object but when i hit my screen edge it bounces back up. Someone told me that maybe my If stament is re running its self but i just have an Array that counts and displays what it finds. Here is a bit of code for the viewController. After @"Combination square", the list will repeat with @"Philips screwdriver", and continue on.
#import "ViewController.h"
#import "DetailViewController.h"
#import "TableViewController.h"

@interface ViewController ()

@end

@implementation ViewController

  - (void)viewDidLoad
   {
     //hide done button at load
doneBtn.hidden = true;
toolBoxArray = [[NSMutableArray alloc] initWithObjects:
                @"Philips screwdriver",
                @"Flathead screwdriver",
                @"Tape measure",
                @"Level",
                @"Utility knife",
                @"Hammer",
                @"Putty knife",
                @"Nail set",
                @"Combination square",
                @"Pliers",
                @"Crescent wrench",
                @"Wire stripper",
                @"Hex key tool (or Allen key)",
                @"Power drill",
                @"Electrical cord",
                @"C-clamp",
                @"Flashlight",
                @"Ladder or step stool",
                @"Broom and dustpan",
                @"Music Box", nil];
toolKindArray = [[NSMutableArray alloc] initWithObjects:
                 @"Hand",
                 @"Hand",
                 @"Hand",
                 @"Hand",
                 @"Hand",
                 @"Hand",
                 @"Hand",
                 @"Hand",
                 @"Hand",
                 @"Hand",
                 @"Hand",
                 @"Hand",
                 @"Hand",
                 @"Power",
                 @"Extension",
                 @"Hand",
                 @"Hand",
                 @"Extension",
                 @"Hand",
                 @"Atmospheric", nil];
infoArray = [[NSMutableArray alloc] initWithObjects:
             @"A Philips or X-shape screwdriver is probably one of the most common tools in any toolbox. If you have a have a handle that accepts interchangeable tips, you can cover a wide range of screw types and sizes.",

             @"A flathead or straight screwdriver is invaluable; most light switch plates use straight screws, for example. Having the right size flathead can make a difference, so start with at least a set of three (small, medium and large) to be able to handle most jobs.",

             @"Your tape measure is indispensable for estimating material quantities, figuring out placement of objects, and calculating floor plans and furniture sizes. It's always a good idea to measure more than once to make sure you've got it right.",

             @"Some people are good at eyeballing whether something is level or not, but this tool takes all the guesswork away. It takes only a slight error to make objects look off-kilter.",

             @"From cutting paint around windows that are stuck closed to opening boxes, scoring drywall or even trimming the edges of carpet, the uses are so many that you'll be surprised how you ever got by without one.",

             @"Pounding nails, pulling nails, crowbar action, tapping things into place — it almost goes without saying why you need hammer. An expensive hammer is long and lightweight; its leverage can assist you when you take that wall down.",

             @"A putty knife is great for scraping dry glues and paints and for spreading putty, paste and spackle. Having a 1½-inch size for scraping and a 5- or 6-inch one for spreading is helpful.",

             @"A nail set is used for sinking nail heads below the surface of the wood, so that you can then fill the hole with wood putty and sand it, to make the nail disappear. This way the hammer never has to make an ugly dent in the surface you are pounding.",

             @"This multiuse tool can verify 90- and 45-degree angles for miter cuts, measure depths and short distances, and is great for scribing a straight line. It also has a vial to make sure your project is level or plumb.",

             @"The serrated jaws of pliers assist with holding objects firmly, as well as with pulling, pinching or bending metal.",

             @"There is a screw built into the head of this wrench; turning it adjusts the size of the opening, so that it fits onto most any hexagonal nut. Turning a nut with pliers just strips the edges, making it harder and harder to get a good grip when tightening or loosening it.",

             @"This wire stripper has a blade for cutting wire to the proper length and several notches for scoring the insulation around wires of varying sizes, which can then be pulled off. Wire has to be exposed without the plastic coating to make electrical connections.",

             @"Some screws, especially bicycles and assemble-it-yourself furniture for which a flush screw is necessary, use hexagonal sockets. Multiple hex key sizes can be purchased separately and the leverage on these is better, but a jackknife-style set such as this provides everything you need in one tool.",

             @"Drilling implies creating holes, and a power drill is the ultimate luxury when tired hands have turned too many screws. It adapts not only to drill bits to bore holes, but also to every kind of screw-head bit, making larger projects go quickly and with less muscle. Just be careful to stop when the fastener is tight so you don't strip the screw head. Don't skimp on this tool — you will appreciate having a lot of power.",

             @"A rugged, well-insulated indoor-outdoor power cord for high-amp tools will help you extend the limited cord of your tools to your job site — and it's suitable for yard work too.",

             @"This tool can hold pieces of wood, metal, or plastic together when you need to glue, saw or file them. Use a thin shim between the clamp and the object you are working on so the clamp doesn't mar the surface.",

             @"Necessary repairs can happen in dark, cramped spaces and even when the power is out. Plus, everyone loves to help by holding the flashlight for you. They don't work without batteries, so have extras on hand.",

             @"Painting, reaching the lightbulb, changing fixtures, trimming the hedge, stringing lights, getting into the attic and many more activities require the aid of a ladder.",

             @"When projects get messy, save your household broom from harsh debris by having a dedicated set.",

             @"Every job is made easier with music or talk radio. This is why hardware stores sell radios, although those are more rugged, with rechargeable battery packs that can also be used in your cordless tools. More rugged means when you drop your hammer on it, you just pick it up and get back to work.", nil];

[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
 - (void)viewDidAppear:(BOOL)animated
{

[super viewDidAppear:animated];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [toolBoxArray count];
}

//on click of delete button
-(IBAction)onClick:(id)sender
{
UIButton *button = (UIButton*)sender;
//if delete button is clicked
if(button.tag == 0)
{
    //display done button
    doneBtn.hidden = false;
    //in edit mode
    [toolTable setEditing:true];

}
//if done button is clicked
else if(button.tag == 1)
{
    //get out edit mode
    [toolTable setEditing:false];
    //hide done button
    doneBtn.hidden = true;
}

}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView   editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
//In editing mode
if (editingStyle == UITableViewCellEditingStyleDelete)
{
    NSLog(@"we want to delete row= %d name= %@", indexPath.row, [toolBoxArray objectAtIndex:indexPath.row]);

    //Delete row from array
    [toolBoxArray removeObjectAtIndex:indexPath.row];
    //Delete row from tableView
    [toolTable deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:true];

    NSLog(@"We have successfully deleted row = %d", indexPath.row);
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";

TableViewController *cell = [toolTable dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{

    NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"TableViewController" owner:nil options:nil];
    for(UIView *view in views)
    {
        if([view isKindOfClass:[TableViewController class]])
        {

            cell = (TableViewController*)view;
            //add arrays to rows
            cell.toolName.text = (NSString *)[toolBoxArray objectAtIndex:indexPath.row];
            cell.kindLabel.text = (NSString *)[toolKindArray objectAtIndex:indexPath.row];
        }
    }
 }
 return cell;
}
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath  *)indexPath
{
//catches what row is selected
NSLog(@"row=%d name=%@", indexPath.row, [toolBoxArray objectAtIndex:indexPath.row]);

//open second view
DetailViewController *secondView = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
if(secondView != nil)
{
    //secondView.delegate = self;
    [self presentViewController:secondView animated:true completion:nil];
    secondView.toolLabel.text = [toolBoxArray objectAtIndex:indexPath.row];
    secondView.kind.text = [toolKindArray objectAtIndex:indexPath.row];
    secondView.info.text = [infoArray objectAtIndex:indexPath.row];
}

}
- (void)dealloc {
[toolTable release];
[super dealloc];
}
@end

A: Removed
if(cell == nil)

Works perfectly now.