Programs & Examples On #Email bounces

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),
};

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);

EDIT

a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),
            };

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
            {
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
            }
            Console.WriteLine("END");
            Console.ReadLine();
        }
    }

    public static class Extenions
    {
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
        {
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
            {
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                {
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)
                    {
                        l.Add(list[j]);
                    }
                }

                yield return l;
            }
        }
    }
}

How to center images on a web page for all screen sizes

Try something like this...

<div id="wrapper" style="width:100%; text-align:center">
<img id="yourimage"/>
</div>

HTTP Request in Swift with POST method

Swift 4 and above

@IBAction func submitAction(sender: UIButton) {

    //declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid

    let parameters = ["id": 13, "name": "jack"]

    //create the url with URL
    let url = URL(string: "www.thisismylink.com/postName.php")! //change the url

    //create the session object
    let session = URLSession.shared

    //now create the URLRequest object using the url object
    var request = URLRequest(url: url)
    request.httpMethod = "POST" //set http method as POST

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
    } catch let error {
        print(error.localizedDescription)
    }

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

        guard error == nil else {
            return
        }

        guard let data = data else {
            return
        }

        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print(json)
                // handle json...
            }
        } catch let error {
            print(error.localizedDescription)
        }
    })
    task.resume()
}

How to find length of digits in an integer?

Well, without converting to string I would do something like:

def lenDigits(x): 
    """
    Assumes int(x)
    """

    x = abs(x)

    if x < 10:
        return 1

    return 1 + lenDigits(x / 10)

Minimalist recursion FTW

There is no argument given that corresponds to the required formal parameter - .NET Error

I got the same error but it was due to me not creating a default constructor. If you haven't already tried that, create the default constructor like this:

public TestClass() {

}

How can I change the color of my prompt in zsh (different from normal text)?

To get a prompt with the color depending on the last command’s exit status, you could use this:

PS1='%(?.%F{green}.%F{red})%n@%m:%~%# %f'

Just add this line to your ~/.zshrc.

The documentation lists possible placeholders.

Entity framework self referencing loop detected

The message error means that you have a self referencing loop.

The json you produce is like this example (with a list of one employee) :

[
employee1 : {
    name: "name",
    department : {
        name: "departmentName",
        employees : [
            employee1 : {
                name: "name",
                department : {
                    name: "departmentName",
                    employees : [
                        employee1 : {
                            name: "name",
                            department : {
                                and again and again....
                            }
                    ]
                }
            }
        ]
    }
}

]

You have to tell the db context that you don't want to get all linked entities when you request something. The option for DbContext is Configuration.LazyLoadingEnabled

The best way I found is to create a context for serialization :

public class SerializerContext : LabEntities 
{
    public SerializerContext()
    {
        this.Configuration.LazyLoadingEnabled = false;
    }
}

Sublime Text 2 - View whitespace characters

To view whitespace the setting is:

// Set to "none" to turn off drawing white space, "selection" to draw only the
// white space within the selection, and "all" to draw all white space
"draw_white_space": "selection",

You can see it if you go into Preferences->Settings Default. If you edit your user settings (Preferences->Settings - User) and add the line as per below, you should get what you want:

{
    "color_scheme": "Packages/Color Scheme - Default/Slush & Poppies.tmTheme",
    "font_size": 10,
    "draw_white_space": "all"
}

Remember the settings are JSON so no trailing commas.

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

I'm kind of late to the party, but this works perfectly in IE11, Chrome, Firefox, without messing up mouseup (and without JQuery).

inputElement.addEventListener("focus", function (e) {
    var target = e.currentTarget;
    if (target) {
        target.select();
        target.addEventListener("mouseup", function _tempoMouseUp(event) {
            event.preventDefault();
            target.removeEventListener("mouseup", _tempoMouseUp);
        });
    }
});

What does int argc, char *argv[] mean?

int main();

This is a simple declaration. It cannot take any command line arguments.

int main(int argc, char* argv[]);

This declaration is used when your program must take command-line arguments. When run like such:

myprogram arg1 arg2 arg3

argc, or Argument Count, will be set to 4 (four arguments), and argv, or Argument Vectors, will be populated with string pointers to "myprogram", "arg1", "arg2", and "arg3". The program invocation (myprogram) is included in the arguments!

Alternatively, you could use:

int main(int argc, char** argv);

This is also valid.

There is another parameter you can add:

int main (int argc, char *argv[], char *envp[])

The envp parameter also contains environment variables. Each entry follows this format:

VARIABLENAME=VariableValue

like this:

SHELL=/bin/bash    

The environment variables list is null-terminated.

IMPORTANT: DO NOT use any argv or envp values directly in calls to system()! This is a huge security hole as malicious users could set environment variables to command-line commands and (potentially) cause massive damage. In general, just don't use system(). There is almost always a better solution implemented through C libraries.

LoDash: Get an array of values from an array of object properties

If you are using native javascript then you can use this code -

let ids = users.map(function(obj, index) {

    return obj.id;
})

console.log(ids); //[12, 14, 16, 18]

How to display (print) vector in Matlab?

You can use

x = [1, 2, 3]
disp(sprintf('Answer: (%d, %d, %d)', x))

This results in

Answer: (1, 2, 3)

For vectors of arbitrary size, you can use

disp(strrep(['Answer: (' sprintf(' %d,', x) ')'], ',)', ')'))

An alternative way would be

disp(strrep(['Answer: (' num2str(x, ' %d,') ')'], ',)', ')'))

How do I get user IP address in django?

The reason the functionality was removed from Django originally was that the header cannot ultimately be trusted. The reason is that it is easy to spoof. For example the recommended way to configure an nginx reverse proxy is to:

add_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header X-Real-Ip       $remote_addr;

When you do:

curl -H 'X-Forwarded-For: 8.8.8.8, 192.168.1.2' http://192.168.1.3/

Your nginx in myhost.com will send onwards:

X-Forwarded-For: 8.8.8.8, 192.168.1.2, 192.168.1.3

The X-Real-IP will be the IP of the first previous proxy if you follow the instructions blindly.

In case trusting who your users are is an issue, you could try something like django-xff: https://pypi.python.org/pypi/django-xff/

How to automatically crop and center an image

Try this:

#yourElementId
{
    background: url(yourImageLocation.jpg) no-repeat center center;
    width: 100px;
    height: 100px;
}

Keep in mind that width and height will only work if your DOM element has layout (a block displayed element, like a div or an img). If it is not (a span, for example), add display: block; to the CSS rules. If you do not have access to the CSS files, drop the styles inline in the element.

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

To re-cap the question in the OP:

I am connecting [to a WCF service] using WCFStorm which is able to retrieve all the meta data properly, but when I call the actual method I get:

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

The WCFStorm tutorials addresses this issue in Working with IIS and SSL.

Their solution worked for me:

  1. To fix the error, generate a client config that matches the wcf service configuration. The easiest way to do this is with Visual Studio.

    • Open Visual Studio and add a service reference to the service. VS will generate an app.config file that matches the service

    • Edit the app.config file so that it can be read by WCFStorm. Please see Loading Client App.config files. Ensure that the endpoint/@name and endpoint/@contract attributes match the values in wcfstorm.

  2. Load the modified app.config to WCFStorm [using the Client Config toobar button].

  3. Invoke the method. This time the method invocation will no longer fail

Item (1) last bullet in effect means to remove the namespace prefix that VS prepends to the endpoint contract attribute, by default "ServiceReference1"

<endpoint ... contract="ServiceReference1.ListsService" ... />

so in the app.config that you load into WCFStorm you want for ListsService:

<endpoint ... contract="ListsService" ... />

Adding Image to xCode by dragging it from File

Add the image to Your project by clicking File -> "Add Files to ...".

Then choose the image in ImageView properties (Utilities -> Attributes Inspector).

Python JSON dump / append to .txt with each variable on new line

Your question is a little unclear. If you're generating hostDict in a loop:

with open('data.txt', 'a') as outfile:
    for hostDict in ....:
        json.dump(hostDict, outfile)
        outfile.write('\n')

If you mean you want each variable within hostDict to be on a new line:

with open('data.txt', 'a') as outfile:
    json.dump(hostDict, outfile, indent=2)

When the indent keyword argument is set it automatically adds newlines.

Programmatically change the height and width of a UIImageView Xcode Swift

let screenSize: CGRect = UIScreen.mainScreen().bounds
image.frame = CGRectMake(0,0, screenSize.height * 0.2, 50)

Scala best way of turning a Collection into a Map-by-key?

In addition to @James Iry's solution, it is also possible to accomplish this using a fold. I suspect that this solution is slightly faster than the tuple method (fewer garbage objects are created):

val list = List("this", "maps", "string", "to", "length")
val map = list.foldLeft(Map[String, Int]()) { (m, s) => m(s) = s.length }

How can I generate UUID in C#

I have a GitHub Gist with a Java like UUID implementation in C#: https://gist.github.com/rickbeerendonk/13655dd24ec574954366

The UUID can be created from the least and most significant bits, just like in Java. It also exposes them. The implementation has an explicit conversion to a GUID and an implicit conversion from a GUID.

Enable IIS7 gzip

Try Firefox with Firebug addons installed. I'm using it; great tool for web developer.

I have enable Gzip compression as well in my IIS7 using web.config.

How can I install Apache Ant on Mac OS X?

Use Brew is always good way to install ANT and other needs. To install type below command on terminal.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

after Brew installation , type

brew install ant

This will install Ant on your system. Also you will not need to worry about setting up the path.

Also i have documented on the same - How to Install ANT on Mac OS?

T-SQL Substring - Last 3 Characters

Because more ways to think about it are always good:

select reverse(substring(reverse(columnName), 1, 3))

How do I create the small icon next to the website tab for my site?

It is called favicon.ico and you can generate it from this site.

http://www.favicon.cc/

Cookie blocked/not saved in IFRAME in Internet Explorer

I got it to work, but the solution is a bit complex, so bear with me.

What's happening

As it is, Internet Explorer gives lower level of trust to IFRAME pages (IE calls this "third-party" content). If the page inside the IFRAME doesn't have a Privacy Policy, its cookies are blocked (which is indicated by the eye icon in status bar, when you click on it, it shows you a list of blocked URLs).

the evil eye
(source: piskvor.org)

In this case, when cookies are blocked, session identifier is not sent, and the target script throws a 'session not found' error.

(I've tried setting the session identifier into the form and loading it from POST variables. This would have worked, but for political reasons I couldn't do that.)

It is possible to make the page inside the IFRAME more trusted: if the inner page sends a P3P header with a privacy policy that is acceptable to IE, the cookies will be accepted.

How to solve it

Create a p3p policy

A good starting point is the W3C tutorial. I've gone through it, downloaded the IBM Privacy Policy Editor and there I created a representation of the privacy policy and gave it a name to reference it by (here it was policy1).

NOTE: at this point, you actually need to find out if your site has a privacy policy, and if not, create it - whether it collects user data, what kind of data, what it does with it, who has access to it, etc. You need to find this information and think about it. Just slapping together a few tags will not cut it. This step cannot be done purely in software, and may be highly political (e.g. "should we sell our click statistics?").

(e.g. "the site is operated by ACME Ltd., it uses anonymous per-session identifiers for its operation, collects user data only if explicitly permitted and only for the following purposes, the data is stored only as long as necessary, only our company has access to it, etc. etc.").

(When editing with this tool, it's possible to view errors/omissions in the policy. Also very useful is the tab "HTML Policy": at the bottom, it has a "Policy Evaluation" - a quick check if the policy will be blocked by IE's default settings)

The Editor exports to a .p3p file, which is an XML representation of the above policy. Also, it can export a "compact version" of this policy.

Link to the policy

Then a Policy Reference file (http://example.com/w3c/p3p.xml) was needed (an index of privacy policies the site uses):

<META>
  <POLICY-REFERENCES>
    <POLICY-REF about="/w3c/example-com.p3p#policy1">
      <INCLUDE>/</INCLUDE>
      <COOKIE-INCLUDE/>
    </POLICY-REF>
  </POLICY-REFERENCES>
</META>

The <INCLUDE> shows all URIs that will use this policy (in my case, the whole site). The policy file I've exported from the Editor was uploaded to http://example.com/w3c/example-com.p3p

Send the compact header with responses

I've set the webserver at example.com to send the compact header with responses, like this:

HTTP/1.1 200 OK 
P3P: policyref="/w3c/p3p.xml", CP="IDC DSP COR IVAi IVDi OUR TST"
// ... other headers and content

policyref is a relative URI to the Policy Reference file (which in turn references the privacy policies), CP is the compact policy representation. Note that the combination of P3P headers in the example may not be applicable on your specific website; your P3P headers MUST truthfully represent your own privacy policy!

Profit!

In this configuration, the Evil Eye does not appear, the cookies are saved even in the IFRAME, and the application works.

Edit: What NOT to do, unless you like defending from lawsuits

Several people have suggested "just slap some tags into your P3P header, until the Evil Eye gives up".

The tags are not only a bunch of bits, they have real world meanings, and their use gives you real world responsibilities!

For example, pretending that you never collect user data might make the browser happy, but if you actually collect user data, the P3P is conflicting with reality. Plain and simple, you are purposefully lying to your users, and that might be criminal behavior in some countries. As in, "go to jail, do not collect $200".

A few examples (see p3pwriter for the full set of tags):

  • NOI : "Web Site does not collected identified data." (as soon as there's any customization, a login, or any data collection (***** Analytics, anyone?), you must acknowledge it in your P3P)
  • STP: Information is retained to meet the stated purpose. This requires information to be discarded at the earliest time possible. Sites MUST have a retention policy that establishes a destruction time table. The retention policy MUST be included in or linked from the site's human-readable privacy policy." (so if you send STP but don't have a retention policy, you may be committing fraud. How cool is that? Not at all.)

I'm not a lawyer, but I'm not willing to go to court to see if the P3P header is really legally binding or if you can promise your users anything without actually willing to honor your promises.

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

It is because of CASCADE TYPE

if you put

@OneToOne(cascade=CascadeType.ALL)

You can just save your object like this

user.setCountry(country);
session.save(user)

but if you put

 @OneToOne(cascade={    
            CascadeType.PERSIST,
            CascadeType.REFRESH,
            ...
})

You need to save your object like this

user.setCountry(country);
session.save(country)
session.save(user)

vertical-align image in div

If you have a fixed height in your container, you can set line-height to be the same as height, and it will center vertically. Then just add text-align to center horizontally.

Here's an example: http://jsfiddle.net/Cthulhu/QHEnL/1/

EDIT

Your code should look like this:

.img_thumb {
    float: left;
    height: 120px;
    margin-bottom: 5px;
    margin-left: 9px;
    position: relative;
    width: 147px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 3px;
    line-height:120px;
    text-align:center;
}

.img_thumb img {
    vertical-align: middle;
}

The images will always be centered horizontally and vertically, no matter what their size is. Here's 2 more examples with images with different dimensions:

http://jsfiddle.net/Cthulhu/QHEnL/6/

http://jsfiddle.net/Cthulhu/QHEnL/7/

UPDATE

It's now 2016 (the future!) and looks like a few things are changing (finally!!).

Back in 2014, Microsoft announced that it will stop supporting IE8 in all versions of Windows and will encourage all users to update to IE11 or Edge. Well, this is supposed to happen next Tuesday (12th January).

Why does this matter? With the announced death of IE8, we can finally start using CSS3 magic.

With that being said, here's an updated way of aligning elements, both horizontally and vertically:

.container {
    position: relative;
}

.container .element {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
}

Using this transform: translate(); method, you don't even need to have a fixed height in your container, it's fully dynamic. Your element has fixed height or width? Your container as well? No? It doesn't matter, it will always be centered because all centering properties are fixed on the child, it's independent from the parent. Thank you CSS3.

If you only need to center in one dimension, you can use translateY or translateX. Just try it for a while and you'll see how it works. Also, try to change the values of the translate, you will find it useful for a bunch of different situations.

Here, have a new fiddle: https://jsfiddle.net/Cthulhu/1xjbhsr4/

For more information on transform, here's a good resource.

Happy coding.

File to byte[] in Java

ReadFully Reads b.length bytes from this file into the byte array, starting at the current file pointer. This method reads repeatedly from the file until the requested number of bytes are read. This method blocks until the requested number of bytes are read, the end of the stream is detected, or an exception is thrown.

RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);

Cannot find Microsoft.Office.Interop Visual Studio

If you're using Visual Studio 2015 and you're encountering this problem, you can install MS Office Developer Tools for VS2015 here.

What is the scope of variables in JavaScript?

Just to add to the other answers, scope is a look-up list of all the declared identifiers (variables), and enforces a strict set of rules as to how these are accessible to currently executing code. This look-up may be for the purposes of assigning to the variable, which is an LHS (lefthand-side) reference, or it may be for the purposes of retrieving its value, which is an RHS (righthand-side) reference. These look-ups are what the JavaScript engine is doing internally when it's compiling and executing the code.

So from this perspective, I think that a picture would help that I found in the Scopes and Closures ebook by Kyle Simpson:

image

Quoting from his ebook:

The building represents our program’s nested scope ruleset. The first floor of the building represents your currently executing scope, wherever you are. The top level of the building is the global scope. You resolve LHS and RHS references by looking on your current floor, and if you don’t find it, taking the elevator to the next floor, looking there, then the next, and so on. Once you get to the top floor (the global scope), you either find what you’re looking for, or you don’t. But you have to stop regardless.

One thing of note that is worth mentioning, "Scope look-up stops once it finds the first match".

This idea of "scope levels" explains why "this" can be changed with a newly created scope, if it's being looked up in a nested function. Here is a link that goes into all these details, Everything you wanted to know about javascript scope

Checking if a variable is defined?

Leaving an incredibly simple example in case it helps.

When variable doesn't exist:

if defined? a then "hi" end
# => nil

When variable does exist:

a = 2
if defined? a then "hi" end
# => "hi"

'Use of Unresolved Identifier' in Swift

Sometimes the compiler gets confused about the syntax in your class. This happens a lot if you paste in source from somewhere else.

Try reducing the "unresolved" source file down to the bare minimum, cleaning and building. Once it builds successfully add all the complexity back to your class.

This has made it go away for me when re-starting Xcode did not work.

NUnit vs. MbUnit vs. MSTest vs. xUnit.net

Nunit doesnt work well with mixed-mode projects in C++ so I had to drop it

What is the difference between a JavaBean and a POJO?

In summary: similarities and differences are:

   java beans:                          Pojo:
-must extends serializable              -no need to extends or implement.
 or externalizable.                     
-must have public class .               - must have public class
-must have private instance variables.      -can have any access specifier variables.
-must have public setter and getter method. - may or may not have setter or getter method.
-must have no-arg constructor.           - can have constructor with agruments.

All JAVA Beans are POJO but not all POJOs are JAVA Beans.

Close a div by clicking outside

You need

$('body').click(function(e) {
    if (!$(e.target).closest('.popup').length){
        $(".popup").hide();
    }
});

Java, How to add values to Array List used as value in HashMap

String courseID = "Comp-101";
List<String> scores = new ArrayList<String> ();
scores.add("100");
scores.add("90");
scores.add("80");
scores.add("97");

Map<String, ArrayList<String>> myMap = new HashMap<String, ArrayList<String>>();
myMap.put(courseID, scores);

Hope this helps!

module.exports vs. export default in Node.js and ES6

You need to configure babel correctly in your project to use export default and export const foo

npm install --save-dev @babel/plugin-proposal-export-default-from

then add below configration in .babelrc

"plugins": [ 
       "@babel/plugin-proposal-export-default-from"
      ]

Error :The remote server returned an error: (401) Unauthorized

The answers did help, but I think a full implementation of this will help a lot of people.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Dom
{
    class Dom
    {
        public static string make_Sting_From_Dom(string reportname)
        {
            try
            {
                WebClient client = new WebClient();
                client.Credentials = CredentialCache.DefaultCredentials;
                // Retrieve resource as a stream               
                Stream data = client.OpenRead(new Uri(reportname.Trim()));
                // Retrieve the text
                StreamReader reader = new StreamReader(data);
                string htmlContent = reader.ReadToEnd();
                string mtch = "TILDE";
                bool b = htmlContent.Contains(mtch);

                if (b)
                {
                    int index = htmlContent.IndexOf(mtch);
                    if (index >= 0)
                        Console.WriteLine("'{0} begins at character position {1}",
                        mtch, index + 1);
                }
                // Cleanup
                data.Close();
                reader.Close();
                return htmlContent;
            }
            catch (Exception)
            {
                throw;
            }
        }

        static void Main(string[] args)
        {
            make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
        }
    }
}

Python: access class property from string

x = getattr(self, source) will work just perfectly if source names ANY attribute of self, including the other_data in your example.

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

In my case the issue was with SendKeys() and Remote Desktop. Posting the workaround I have so far:

I had a Selenium test which would fail when run as part of a Jenkins job on a node hosted in vSphere and administered through RDP. After some troubleshooting it turned out it succeeds if Remote Desktop is connected and focused but fails with the exception if Remote Desktop is disconnected or even minimized.

As a workaround, I logged through vSphere Console instead of RDP and then even after closing vSphere the test didn't fail anymore. This is a workaround but I would have to be careful never to login through RDP and always to administer only through vSphere Console.

MySQL IF ELSEIF in select query

For your question :

SELECT id, 
   IF(qty_1 <= '23', price,
   IF(('23' > qty_1 && qty_2 <= '23'), price_2,
   IF(('23' > qty_2 && qty_3 <= '23'), price_3,
   IF(('23' > qty_2 && qty_3<='23'), price_3,
   IF('23' > qty_3, price_4, 1))))) as total 
FROM product;

You can use the if - else control structure or the IF function in MySQL.

Reference:
http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/

JQuery: Change value of hidden input field

Seems to work

$(".selector").change(function() {

    var $value = $(this).val();

    var $title = $(this).children('option[value='+$value+']').html();

    $('#bacon').val($title);

});

Just check with your firebug. And don't put css on hidden input.

How can I convert a string to an int in Python?

>>> a = "123"
>>> int(a)
123

Here's some freebie code:

def getTwoNumbers():
    numberA = raw_input("Enter your first number: ")
    numberB = raw_input("Enter your second number: ")
    return int(numberA), int(numberB)

Using unset vs. setting a variable to empty

So, by unset'ting the array index 2, you essentially remove that element in the array and decrement the array size (?).

I made my own test..

foo=(5 6 8)
echo ${#foo[*]}
unset foo
echo ${#foo[*]}

Which results in..

3
0

So just to clarify that unset'ting the entire array will in fact remove it entirely.

ArrayBuffer to base64 encoded string

There is another asynchronous way use Blob and FileReader.

I didn't test the performance. But it is a different way of thinking.

function arrayBufferToBase64( buffer, callback ) {
    var blob = new Blob([buffer],{type:'application/octet-binary'});
    var reader = new FileReader();
    reader.onload = function(evt){
        var dataurl = evt.target.result;
        callback(dataurl.substr(dataurl.indexOf(',')+1));
    };
    reader.readAsDataURL(blob);
}

//example:
var buf = new Uint8Array([11,22,33]);
arrayBufferToBase64(buf, console.log.bind(console)); //"CxYh"

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

INSERT INTO AM_PROGRAM_TUNING_EVENT_TMP1 
VALUES(TO_DATE('2012-03-28 11:10:00','yyyy/mm/dd hh24:mi:ss'));

http://www.sqlfiddle.com/#!4/22115/1

SVN 405 Method Not Allowed

My "disappeared" folder was libraries/fof.

If I deleted it, then ran an update, it wouldn't show up.

cd libaries
svn up

(nothing happens).

But updating with the actual name:

svn update fof

did the trick and it was updated. So I exploded my (manually tar-archived) working copy over it and recommitted. Easiest solution.

How do I create/edit a Manifest file?

In Visual Studio 2019 WinForm Projects, it is available under

Project Properties -> Application -> View Windows Settings (button)

enter image description here

How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place?

The URL syntax is the same regardless of the platform in use

String url = "https://www.google.com/maps/search/?api=1&query=" + latitude + ","+ 
longitude;

In Android or iOS the URL launches Google Maps in the Maps app, If the Google Maps app is not installed, the URL launches Google Maps in a browser and performs the requested action.

On any other device, the URL launches Google Maps in a browser and performs the requested action.

here's the link for official documentation https://developers.google.com/maps/documentation/urls/guide

Changing background color of ListView items on Android

Take a look at List14 example. In getView() you can call convertView.setBackgroundDrawable() for each entry. You could have a class member counter to decide which background to call it with to get alternating backgrounds, for example.

Routing with Multiple Parameters using ASP.NET MVC

Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:

public ActionResult GetImages(string artistName, string apiKey)

MVC will auto-populate the parameters when given a URL like:

/Artist/GetImages/?artistName=cher&apiKey=XXX

One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:

public ActionResult GetImages(string id, string apiKey)

would be populated correctly with a URL like the following:

/Artist/GetImages/cher?apiKey=XXX

In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:

routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

If you wanted to support a url like

/Artist/GetImages/cher/api-key

you could add a route like:

routes.MapRoute(
            "ArtistImages",                                              // Route name
            "{controller}/{action}/{artistName}/{apikey}",                           // URL with parameters
            new { controller = "Home", action = "Index", artistName = "", apikey = "" }  // Parameter defaults
        );

and a method like the first example above.

HTML Agility pack - parsing tables

The most simple what I've found to get the XPath for a particular Element is to install FireBug extension for Firefox go to the site/webpage press F12 to bring up firebug; right select and right click the element on the page that you want to query and select "Inspect Element" Firebug will select the element in its IDE then right click the Element in Firebug and choose "Copy XPath" this function will give you the exact XPath Query you need to get the element you want using HTML Agility Library.

Center align a column in twitter bootstrap

I tried the approaches given above, but these methods fail when dynamically the height of the content in one of the cols increases, it basically pushes the other cols down.

for me the basic table layout solution worked.

// Apply this to the enclosing row
.row-centered {
  text-align: center;
  display: table-row;
}
// Apply this to the cols within the row
.col-centered {
  display: table-cell;
  float: none;
  vertical-align: top;
}

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

First, you need to convert your URI object to URL object, and then use File object to retrieve a file name:

try
    {
        URL videoUrl = uri.toURL();
        File tempFile = new File(videoUrl.getFile());
        String fileName = tempFile.getName();
    }
    catch (Exception e)
    {

    }

That's it, very easy.

In C, how should I read a text file and print all strings

Instead just directly print the characters onto the console because the text file maybe very large and you may require a lot of memory.

#include <stdio.h>
#include <stdlib.h>

int main() {

    FILE *f;
    char c;
    f=fopen("test.txt","rt");

    while((c=fgetc(f))!=EOF){
        printf("%c",c);
    }

    fclose(f);
    return 0;
}

Stop jQuery .load response from being cached

Try this:

$("#Search_Result").load("AJAX-Search.aspx?q=" + $("#q").val() + "&rnd=" + String((new Date()).getTime()).replace(/\D/gi, ''));

It works fine when i used it.

How do I get the key at a specific index from a Dictionary in Swift?

From https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/CollectionTypes.html:

If you need to use a dictionary’s keys or values with an API that takes an Array instance, initialize a new array with the keys or values property:

let airportCodes = [String](airports.keys) // airportCodes is ["TYO", "LHR"]   
let airportNames = [String](airports.values) // airportNames is ["Tokyo", "London Heathrow"]

z-index issue with twitter bootstrap dropdown menu

Ran into the same bug here. This worked for me.

.navbar {
    position: static;
}

By setting the position to static, it means the navbar will fall into the flow of the document as it normally would.

Any implementation of Ordered Set in Java?

IndexedTreeSet from the indexed-tree-map project provides this functionality (ordered/sorted set with list-like access by index).

git repo says it's up-to-date after pull but files are not updated

Try this:

 git fetch --all
 git reset --hard origin/master

Explanation:

git fetch downloads the latest from remote without trying to merge or rebase anything.

Please let me know if you have any questions!

Change the "From:" address in Unix "mail"

On Debian 7 I was still unable to correctly set the sender address using answers from this question, (would always be the hostname of the server) but resolved it this way.

Install heirloom-mailx

apt-get install heirloom-mailx

ensure it's the default.

update-alternatives --config mailx

Compose a message.

mail -s "Testing from & replyto" -r "sender <[email protected]>" -S replyto="[email protected]" [email protected] < <(echo "Test message")

Github "Updates were rejected because the remote contains work that you do not have locally."

You may refer to: How to deal with "refusing to merge unrelated histories" error:

$ git pull --allow-unrelated-histories
$ git push -f origin master

apache server reached MaxClients setting, consider raising the MaxClients setting

When you use Apache with mod_php apache is enforced in prefork mode, and not worker. As, even if php5 is known to support multi-thread, it is also known that some php5 libraries are not behaving very well in multithreaded environments (so you would have a locale call on one thread altering locale on other php threads, for example).

So, if php is not running in cgi way like with php-fpm you have mod_php inside apache and apache in prefork mode. On your tests you have simply commented the prefork settings and increased the worker settings, what you now have is default values for prefork settings and some altered values for the shared ones :

StartServers       20
MinSpareServers    5
MaxSpareServers    10
MaxClients         1024
MaxRequestsPerChild  0

This means you ask apache to start with 20 process, but you tell it that, if there is more than 10 process doing nothing it should reduce this number of children, to stay between 5 and 10 process available. The increase/decrease speed of apache is 1 per minute. So soon you will fall back to the classical situation where you have a fairly low number of free available apache processes (average 2). The average is low because usually you have something like 5 available process, but as soon as the traffic grows they're all used, so there's no process available as apache is very slow in creating new forks. This is certainly increased by the fact your PHP requests seems to be quite long, they do not finish early and the apache forks are not released soon enough to treat another request.

See on the last graphic the small amount of green before the red peak? If you could graph this on a 1 minute basis instead of 5 minutes you would see that this green amount was not big enough to take the incoming traffic without any error message.

Now you set 1024 MaxClients. I guess the cacti graph are not taken after this configuration modification, because with such modification, when no more process are available, apache would continue to fork new children, with a limit of 1024 busy children. Take something like 20MB of RAM per child (or maybe you have a big memory_limit in PHP and allows something like 64MB or 256MB and theses PHP requests are really using more RAM), maybe a DB server... your server is now slowing down because you have only 768MB of RAM. Maybe when apache is trying to initiate the first 20 children you already reach the available RAM limit.

So. a classical way of handling that is to check the amount of memory used by an apache fork (make some top commands while it is running), then find how many parallel request you can handle with this amount of RAM (that mean parallel apache children in prefork mode). Let's say it's 12, for example. Put this number in apache mpm settings this way:

<IfModule prefork.c>
  StartServers       12
  MinSpareServers    12
  MaxSpareServers    12
  MaxClients         12
  MaxRequestsPerChild  300
</IfModule>

That means you do not move the number of fork while traffic increase or decrease, because you always want to use all the RAM and be ready for traffic peaks. The 300 means you recyclate each fork after 300 requests, it's better than 0, it means you will not have potential memory leaks issues. MaxClients is set to 12 25 or 50 which is more than 12 to handle the ListenBacklog queue, which can enqueue some requests, you may take a bigger queue, but you would get some timeouts maybe (removed this strange sentende, I can't remember why I said that, if more than 12 requests are incoming the next one will be pushed in the Backlog queue, but you should set MaxClient to your targeted number of processes).

And yes, that means you cannot handle more than 12 parallel requests.

If you want to handle more requests:

  • buy some more RAM
  • try to use apache in worker mode, but remove mod_php and use php as a parallel daemon with his own pooler settings (this is called php-fpm), connect it with fastcgi. Note that you will certainly need to buy some RAM to allow a big number of parallel php-fpm process, but maybe less than with mod_php
  • Reduce the time spent in your php process. From your cacti graphs you have to potential problems: a real traffic peak around 11:25-11:30 or some php code getting very slow. Fast requests will reduce the number of parallel requests.

If your problem is really traffic peaks, solutions could be available with caches, like a proxy-cache server. If the problem is a random slowness in PHP then... it's an application problem, do you do some HTTP query to another site from PHP, for example?

And finally, as stated by @Jan Vlcinsky you could try nginx, where php will only be available as php-fpm. If you cannot buy RAM and must handle a big traffic that's definitively desserve a test.

Update: About internal dummy connections (if it's your problem, but maybe not).

Check this link and this previous answer. This is 'normal', but if you do not have a simple virtualhost theses requests are maybe hitting your main heavy application, generating slow http queries and preventing regular users to acces your apache processes. They are generated on graceful reload or children managment.

If you do not have a simple basic "It works" default Virtualhost prevent theses requests on your application by some rewrites:

  RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
  RewriteRule .* - [F,L]

Update:

Having only one Virtualhost does not protect you from internal dummy connections, it is worst, you are sure now that theses connections are made on your unique Virtualhost. So you should really avoid side effects on your application by using the rewrite rules.

Reading your cacti graphics, it seems your apache is not in prefork mode bug in worker mode. Run httpd -l or apache2 -l on debian, and check if you have worker.c or prefork.c. If you are in worker mode you may encounter some PHP problems in your application, but you should check the worker settings, here is an example:

<IfModule worker.c>
  StartServers           3
  MaxClients           500
  MinSpareThreads       75
  MaxSpareThreads      250 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

You start 3 processes, each containing 25 threads (so 3*25=75 parallel requests available by default), you allow 75 threads doing nothing, as soon as one thread is used a new process is forked, adding 25 more threads. And when you have more than 250 threads doing nothing (10 processes) some process are killed. You must adjust theses settings with your memory. Here you allow 500 parallel process (that's 20 process of 25 threads). Your usage is maybe more:

<IfModule worker.c>
  StartServers           2
  MaxClients           250
  MinSpareThreads       50
  MaxSpareThreads      150 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

How do I make a relative reference to another workbook in Excel?

I had a similar problem that I solved by using the following sequence:

  1. use the CELL("filename") function to get the full path to the current sheet of the current file.

  2. use the SEARCH() function to find the start of the [FileName]SheetName string of your current excel file and the sheet.

  3. use the LEFT function to extract the full path name of the directory that contains your current file.

  4. Concatenate the directory path name found in step #3 with the name of the file, the name of the worksheet, and the cell reference that you want to access.

  5. use the INDIRECT() function to access the CellPathName that you created in step #4.

Note: these same steps can also be used to access cells in files whose names are created dynamically. In step #4, use a text string that is dynamically created from the contents of cells, the current date or time, etc. etc.

A cell reference example (with each piece assembled separately) that includes all of these steps is:

=INDIRECT("'" & LEFT(CELL("filename"),SEARCH("[MyFileName]MySheetName",CELL("filename")) - 1) & "[" & "OtherFileName" & "]" & "OtherSheetName" & "'!" & "$OtherColumn$OtherRow" & "'")

Note that LibreOffice uses a slightly different CellPatnName syntax, as in the following example:

=INDIRECT(LEFT(CELL("filename"),SEARCH("[MyFileName]MySheetName",CELL("filename")) - 1) & "OtherFileName" & "'#$" & "OtherSheetName" & "." & "$OtherColumn$OtherRow")

Separation of business logic and data access in django

First of all, Don't repeat yourself.

Then, please be careful not to overengineer, sometimes it is just a waste of time, and makes someone lose focus on what is important. Review the zen of python from time to time.

Take a look at active projects

  • more people = more need to organize properly
  • the django repository they have a straightforward structure.
  • the pip repository they have a straigtforward directory structure.
  • the fabric repository is also a good one to look at.

    • you can place all your models under yourapp/models/logicalgroup.py
  • e.g User, Group and related models can go under yourapp/models/users.py
  • e.g Poll, Question, Answer ... could go under yourapp/models/polls.py
  • load what you need in __all__ inside of yourapp/models/__init__.py

More about MVC

  • model is your data
    • this includes your actual data
    • this also includes your session / cookie / cache / fs / index data
  • user interacts with controller to manipulate the model
    • this could be an API, or a view that saves/updates your data
    • this can be tuned with request.GET / request.POST ...etc
    • think paging or filtering too.
  • the data updates the view
    • the templates take the data and format it accordingly
    • APIs even w/o templates are part of the view; e.g. tastypie or piston
    • this should also account for the middleware.

Take advantage of middleware / templatetags

  • If you need some work to be done for each request, middleware is one way to go.
    • e.g. adding timestamps
    • e.g. updating metrics about page hits
    • e.g. populating a cache
  • If you have snippets of code that always reoccur for formatting objects, templatetags are good.
    • e.g. active tab / url breadcrumbs

Take advantage of model managers

  • creating User can go in a UserManager(models.Manager).
  • gory details for instances should go on the models.Model.
  • gory details for queryset could go in a models.Manager.
  • you might want to create a User one at a time, so you may think that it should live on the model itself, but when creating the object, you probably don't have all the details:

Example:

class UserManager(models.Manager):
   def create_user(self, username, ...):
      # plain create
   def create_superuser(self, username, ...):
      # may set is_superuser field.
   def activate(self, username):
      # may use save() and send_mail()
   def activate_in_bulk(self, queryset):
      # may use queryset.update() instead of save()
      # may use send_mass_mail() instead of send_mail()

Make use of forms where possible

A lot of boilerplate code can be eliminated if you have forms that map to a model. The ModelForm documentation is pretty good. Separating code for forms from model code can be good if you have a lot of customization (or sometimes avoid cyclic import errors for more advanced uses).

Use management commands when possible

  • e.g. yourapp/management/commands/createsuperuser.py
  • e.g. yourapp/management/commands/activateinbulk.py

if you have business logic, you can separate it out

  • django.contrib.auth uses backends, just like db has a backend...etc.
  • add a setting for your business logic (e.g. AUTHENTICATION_BACKENDS)
  • you could use django.contrib.auth.backends.RemoteUserBackend
  • you could use yourapp.backends.remote_api.RemoteUserBackend
  • you could use yourapp.backends.memcached.RemoteUserBackend
  • delegate the difficult business logic to the backend
  • make sure to set the expectation right on the input/output.
  • changing business logic is as simple as changing a setting :)

backend example:

class User(db.Models):
    def get_present_name(self): 
        # property became not deterministic in terms of database
        # data is taken from another service by api
        return remote_api.request_user_name(self.uid) or 'Anonymous' 

could become:

class User(db.Models):
   def get_present_name(self):
      for backend in get_backends():
         try:
            return backend.get_present_name(self)
         except: # make pylint happy.
            pass
      return None

more about design patterns

more about interface boundaries

  • Is the code you want to use really part of the models? -> yourapp.models
  • Is the code part of business logic? -> yourapp.vendor
  • Is the code part of generic tools / libs? -> yourapp.libs
  • Is the code part of business logic libs? -> yourapp.libs.vendor or yourapp.vendor.libs
  • Here is a good one: can you test your code independently?
    • yes, good :)
    • no, you may have an interface problem
    • when there is clear separation, unittest should be a breeze with the use of mocking
  • Is the separation logical?
    • yes, good :)
    • no, you may have trouble testing those logical concepts separately.
  • Do you think you will need to refactor when you get 10x more code?
    • yes, no good, no bueno, refactor could be a lot of work
    • no, that's just awesome!

In short, you could have

  • yourapp/core/backends.py
  • yourapp/core/models/__init__.py
  • yourapp/core/models/users.py
  • yourapp/core/models/questions.py
  • yourapp/core/backends.py
  • yourapp/core/forms.py
  • yourapp/core/handlers.py
  • yourapp/core/management/commands/__init__.py
  • yourapp/core/management/commands/closepolls.py
  • yourapp/core/management/commands/removeduplicates.py
  • yourapp/core/middleware.py
  • yourapp/core/signals.py
  • yourapp/core/templatetags/__init__.py
  • yourapp/core/templatetags/polls_extras.py
  • yourapp/core/views/__init__.py
  • yourapp/core/views/users.py
  • yourapp/core/views/questions.py
  • yourapp/core/signals.py
  • yourapp/lib/utils.py
  • yourapp/lib/textanalysis.py
  • yourapp/lib/ratings.py
  • yourapp/vendor/backends.py
  • yourapp/vendor/morebusinesslogic.py
  • yourapp/vendor/handlers.py
  • yourapp/vendor/middleware.py
  • yourapp/vendor/signals.py
  • yourapp/tests/test_polls.py
  • yourapp/tests/test_questions.py
  • yourapp/tests/test_duplicates.py
  • yourapp/tests/test_ratings.py

or anything else that helps you; finding the interfaces you need and the boundaries will help you.

Check for internet connection with Swift

here my solution for swift 2.3 with the lib (Reachability.swift)

Go into your Podfile and add :

pod 'ReachabilitySwift', '~> 2.4' // swift 2.3

Then into your terminal :

pod install

Then create a new file ReachabilityManager and add code below :

import Foundation
import ReachabilitySwift

enum ReachabilityManagerType {
    case Wifi
    case Cellular
    case None
}

class ReachabilityManager {
    static let sharedInstance = ReachabilityManager()

    private var reachability: Reachability!
    private var reachabilityManagerType: ReachabilityManagerType = .None


    private init() {
        do {
            self.reachability = try Reachability.reachabilityForInternetConnection()
        } catch {
            print("Unable to create Reachability")
            return
        }

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ReachabilityManager.reachabilityChanged(_:)),name: ReachabilityChangedNotification,object: self.reachability)
        do{
            try self.reachability.startNotifier()
        }catch{
            print("could not start reachability notifier")
        }
    }

    @objc private func reachabilityChanged(note: NSNotification) {

        let reachability = note.object as! Reachability

        if reachability.isReachable() {
            if reachability.isReachableViaWiFi() {
                self.reachabilityManagerType = .Wifi
            } else {
                self.reachabilityManagerType = .Cellular
            }
        } else {
            self.reachabilityManagerType = .None
        }
    }
}

extension ReachabilityManager {

    func isConnectedToNetwork() -> Bool {
        return reachabilityManagerType != .None
    }

}

How use it:

go into your AppDelegate.swift and add the code below :

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
     ReachabilityManager.sharedInstance
}

Then when you want to check if the device is connected to internet do :

if ReachabilityManager.sharedInstance.isConnectedToNetwork() {
   // Connected
} else {
  // Not connected
}

Substring in VBA

Shorter:

   Split(stringval,":")(0)

How to prevent SIGPIPEs (or handle them properly)

You generally want to ignore the SIGPIPE and handle the error directly in your code. This is because signal handlers in C have many restrictions on what they can do.

The most portable way to do this is to set the SIGPIPE handler to SIG_IGN. This will prevent any socket or pipe write from causing a SIGPIPE signal.

To ignore the SIGPIPE signal, use the following code:

signal(SIGPIPE, SIG_IGN);

If you're using the send() call, another option is to use the MSG_NOSIGNAL option, which will turn the SIGPIPE behavior off on a per call basis. Note that not all operating systems support the MSG_NOSIGNAL flag.

Lastly, you may also want to consider the SO_SIGNOPIPE socket flag that can be set with setsockopt() on some operating systems. This will prevent SIGPIPE from being caused by writes just to the sockets it is set on.

SQL Server equivalent to MySQL enum data type?

IMHO Lookup tables is the way to go, with referential integrity. But only if you avoid "Evil Magic Numbers" by following an example such as this one: Generate enum from a database lookup table using T4

Have Fun!

TCPDF output without saving file

Use I for "inline" to send the PDF to the browser, opposed to F to save it as a file.

$pdf->Output('name.pdf', 'I');

Visual Studio 2015 or 2017 does not discover unit tests

This happened to me because my test project contained an app.config. It was automatically added by NuGet packages for assembly redirection, but my tests seemed to run fine without it.

See: https://developercommunity.visualstudio.com/comments/42858/view.html.

Loop in react-native

renderItem(item)
  {
    const width = '80%';
    var items = [];

    for(let i = 0; i < item.count; i++){

        items.push( <View style={{ padding: 10, borderBottomColor: "#f2f2f2", borderBottomWidth: 10, flexDirection: 'row' }}>
    <View style={{ width }}>
      <Text style={styles.name}>{item.title}</Text>
      <Text style={{ color: '#818181', paddingVertical: 10 }}>{item.taskDataElements[0].description + " "}</Text>
      <Text style={styles.begin}>BEGIN</Text>
    </View>

    <Text style={{ backgroundColor: '#fcefec', padding: 10, color: 'red', height: 40 }}>{this.msToTime(item.minTatTimestamp) <= 0 ? "NOW" : this.msToTime(item.minTatTimestamp) + "hrs"}</Text>
  </View> )
  }

  return items;
}

render() {
return (this.renderItem(this.props.item)) 
}

Performing a query on a result from another query?

You just wrap your query in another one:

SELECT COUNT(*), SUM(Age)
FROM (
    SELECT availables.bookdate AS Count, DATEDIFF(now(),availables.updated_at) as Age
    FROM availables
    INNER JOIN rooms
    ON availables.room_id=rooms.id
    WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
    GROUP BY availables.bookdate
) AS tmp;

OSX - How to auto Close Terminal window after the "exit" command executed.

I 've been using ctrl + d. It throws you out into the destination where You've started the sqlite3 command in the first place.

How to compare dates in Java?

This method worked for me:

 public static String daysBetween(String day1, String day2) {
    String daysBetween = "";
    SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {
        Date date1 = myFormat.parse(day1);
        Date date2 = myFormat.parse(day2);
        long diff = date2.getTime() - date1.getTime();
        daysBetween = ""+(TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return daysBetween;
}

What is the command to truncate a SQL Server log file?

Since the answer for me was buried in the comments. For SQL Server 2012 and beyond, you can use the following:

BACKUP LOG Database TO DISK='NUL:'
DBCC SHRINKFILE (Database_Log, 1)

How to add element in List while iterating in java?

To help with this I created a function to make this more easy to achieve it.

public static <T> void forEachCurrent(List<T> list, Consumer<T> action) {
    final int size = list.size();
    for (int i = 0; i < size; i++) {
        action.accept(list.get(i));
    }
}

Example

    List<String> l = new ArrayList<>();
    l.add("1");
    l.add("2");
    l.add("3");
    forEachCurrent(l, e -> {
        l.add(e + "A");
        l.add(e + "B");
        l.add(e + "C");
    });
    l.forEach(System.out::println);

jquery-ui-dialog - How to hook into dialog close event

If I'm understanding the type of window you're talking about, wouldn't $(window).unload() (for the dialog window) give you the hook you need?

(And if I misunderstood, and you're talking about a dialog box made via CSS rather than a pop-up browser window, then all the ways of closing that window are elements you could register click handers for.)

Edit: Ah, I see now you're talking about jquery-ui dialogs, which are made via CSS. You can hook the X which closes the window by registering a click handler for the element with the class ui-dialog-titlebar-close.

More useful, perhaps, is you tell you how to figure that out quickly. While displaying the dialog, just pop open FireBug and Inspect the elements that can close the window. You'll instantly see how they are defined and that gives you what you need to register the click handlers.

So to directly answer your question, I believe the answer is really "no" -- there's isn't a close event you can hook, but "yes" -- you can hook all the ways to close the dialog box fairly easily and get what you want.

How to right align widget in horizontal linear layout Android?

Here is a sample. the key to arrange is as follows

android:layout_width="0dp"
android:layout_weight="1"

Complete code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="5dp">

    <TextView
        android:id="@+id/categoryName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="abcd" />

    <TextView
        android:id="@+id/spareName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="efgh" />

</LinearLayout>

enter image description here

Get Path from another app (WhatsApp)

you can try to this , then you get a bitmap of selected image and then you can easily find it's native path from Device Default Gallery.

Bitmap roughBitmap= null;
    try {
    // Works with content://, file://, or android.resource:// URIs
    InputStream inputStream =
    getContentResolver().openInputStream(uri);
    roughBitmap= BitmapFactory.decodeStream(inputStream);

    // calc exact destination size
    Matrix m = new Matrix();
    RectF inRect = new RectF(0, 0, roughBitmap.Width, roughBitmap.Height);
    RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
    m.SetRectToRect(inRect, outRect, Matrix.ScaleToFit.Center);
    float[] values = new float[9];
    m.GetValues(values);


    // resize bitmap if needed
    Bitmap resizedBitmap = Bitmap.CreateScaledBitmap(roughBitmap, (int) (roughBitmap.Width * values[0]), (int) (roughBitmap.Height * values[4]), true);

    string name = "IMG_" + new Java.Text.SimpleDateFormat("yyyyMMdd_HHmmss").Format(new Java.Util.Date()) + ".png";
    var sdCardPath= Environment.GetExternalStoragePublicDirectory("DCIM").AbsolutePath;
    Java.IO.File file = new Java.IO.File(sdCardPath);
    if (!file.Exists())
    {
        file.Mkdir();
    }
    var filePath = System.IO.Path.Combine(sdCardPath, name);
    } catch (FileNotFoundException e) {
    // Inform the user that things have gone horribly wrong
    }

Bootstrap carousel multiple frames at once

Updated 2019...

Bootstrap 4

The carousel has changed in 4.x, and the multi-slide animation transitions can be overridden like this...

.carousel-inner .carousel-item-right.active,
.carousel-inner .carousel-item-next {
  transform: translateX(33.33%);
}

.carousel-inner .carousel-item-left.active, 
.carousel-inner .carousel-item-prev {
  transform: translateX(-33.33%)
}

.carousel-inner .carousel-item-right,
.carousel-inner .carousel-item-left{ 
  transform: translateX(0);
}

Bootstrap 4 Alpha.6 Demo
Bootstrap 4.0.0 (show 4, advance 1 at a time)
Bootstrap 4.1.0 (show 3, advance 1 at a time)
Bootstrap 4.1.0 (advance all 4 at once)
Bootstrap 4.3.1 responsive (show multiple, advance 1)new
Bootstrap 4.3.1 carousel with cardsnew


Another option is a responsive carousel that only shows and advances 1 slide on smaller screens, but shows multiple slides are larger screens. Instead of cloning the slides like the previous example, this one adjusts the CSS and use jQuery only to move the extra slides to allow for continuous cycling (wrap around):

Please don't just copy-and-paste this code. First, understand how it works.

Bootstrap 4 Responsive (show 3, 1 slide on mobile)

@media (min-width: 768px) {

    /* show 3 items */
    .carousel-inner .active,
    .carousel-inner .active + .carousel-item,
    .carousel-inner .active + .carousel-item + .carousel-item {
        display: block;
    }

    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left),
    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item,
    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item + .carousel-item {
        transition: none;
    }

    .carousel-inner .carousel-item-next,
    .carousel-inner .carousel-item-prev {
      position: relative;
      transform: translate3d(0, 0, 0);
    }

    .carousel-inner .active.carousel-item + .carousel-item + .carousel-item + .carousel-item {
        position: absolute;
        top: 0;
        right: -33.3333%;
        z-index: -1;
        display: block;
        visibility: visible;
    }

    /* left or forward direction */
    .active.carousel-item-left + .carousel-item-next.carousel-item-left,
    .carousel-item-next.carousel-item-left + .carousel-item,
    .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item,
    .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item + .carousel-item {
        position: relative;
        transform: translate3d(-100%, 0, 0);
        visibility: visible;
    }

    /* farthest right hidden item must be abso position for animations */
    .carousel-inner .carousel-item-prev.carousel-item-right {
        position: absolute;
        top: 0;
        left: 0;
        z-index: -1;
        display: block;
        visibility: visible;
    }

    /* right or prev direction */
    .active.carousel-item-right + .carousel-item-prev.carousel-item-right,
    .carousel-item-prev.carousel-item-right + .carousel-item,
    .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item,
    .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item + .carousel-item {
        position: relative;
        transform: translate3d(100%, 0, 0);
        visibility: visible;
        display: block;
        visibility: visible;
    }

}

<div class="container-fluid">
    <div id="carouselExample" class="carousel slide" data-ride="carousel" data-interval="9000">
        <div class="carousel-inner row w-100 mx-auto" role="listbox">
            <div class="carousel-item col-md-4 active">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400/000/fff?text=1" alt="slide 1">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=2" alt="slide 2">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=3" alt="slide 3">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=4" alt="slide 4">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=5" alt="slide 5">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=6" alt="slide 6">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=7" alt="slide 7">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=8" alt="slide 7">
            </div>
        </div>
        <a class="carousel-control-prev" href="#carouselExample" role="button" data-slide="prev">
            <i class="fa fa-chevron-left fa-lg text-muted"></i>
            <span class="sr-only">Previous</span>
        </a>
        <a class="carousel-control-next text-faded" href="#carouselExample" role="button" data-slide="next">
            <i class="fa fa-chevron-right fa-lg text-muted"></i>
            <span class="sr-only">Next</span>
        </a>
    </div>
</div>

Example - Bootstrap 4 Responsive (show 4, 1 slide on mobile)
Example - Bootstrap 4 Responsive (show 5, 1 slide on mobile)


Bootstrap 3

Here is a 3.x example on Bootply: http://bootply.com/89193

You need to put an entire row of images in the item active. Here is another version that doesn't stack the images at smaller screen widths: http://bootply.com/92514

EDIT Alternative approach to advance one slide at a time:

Use jQuery to clone the next items..

$('.carousel .item').each(function(){
  var next = $(this).next();
  if (!next.length) {
    next = $(this).siblings(':first');
  }
  next.children(':first-child').clone().appendTo($(this));

  if (next.next().length>0) {
    next.next().children(':first-child').clone().appendTo($(this));
  }
  else {
    $(this).siblings(':first').children(':first-child').clone().appendTo($(this));
  }
});

And then CSS to position accordingly...

Before 3.3.1

.carousel-inner .active.left { left: -33%; }
.carousel-inner .next        { left:  33%; }

After 3.3.1

.carousel-inner .item.left.active {
  transform: translateX(-33%);
}
.carousel-inner .item.right.active {
  transform: translateX(33%);
}

.carousel-inner .item.next {
  transform: translateX(33%)
}
.carousel-inner .item.prev {
  transform: translateX(-33%)
}

.carousel-inner .item.right,
.carousel-inner .item.left { 
  transform: translateX(0);
}

This will show 3 at time, but only slide one at a time:

Bootstrap 3.x Demo


Please don't copy-and-paste this code. First, understand how it works. This answer is here to help you learn.

Doubling up this modified bootstrap 4 carousel only functions half correctly (scroll loop stops working)
how to make 2 bootstrap sliders in single page without mixing their css and jquery?
Bootstrap 4 Multi Carousel show 4 images instead of 3

Regex for string not ending with given suffix

Try this

/.*[^a]$/

The [] denotes a character class, and the ^ inverts the character class to match everything but an a.

vuejs update parent data from child component

The correct way is to $emit() an event in the child component that the main Vue instance listens for.

// Child.js
Vue.component('child', {
  methods: {
    notifyParent: function() {
      this.$emit('my-event', 42);
    }
  }
});

// Parent.js
Vue.component('parent', {
  template: '<child v-on:my-event="onEvent($event)"></child>',
  methods: {
    onEvent: function(ev) {
      v; // 42
    }
  }
});

Java Array Sort descending?

It's good sometimes we practice over an example, here is a full one:

sortdesc.java

import java.util.Arrays;
import java.util.Collections;
class sortdesc{
public static void main(String[] args){
       // int Array
       Integer[] intArray=new Integer[]{
                 new Integer(15),
                 new Integer(9),
                 new Integer(16),
                 new Integer(2),
                 new Integer(30)};

       // Sorting int Array in descending order
       Arrays.sort(intArray,Collections.reverseOrder());

       // Displaying elements of int Array
       System.out.println("Int Array Elements in reverse order:");
       for(int i=0;i<intArray.length;i++)
          System.out.println(intArray[i]);

       // String Array
       String[] stringArray=new String[]{"FF","PP","AA","OO","DD"};

       // Sorting String Array in descending order
       Arrays.sort(stringArray,Collections.reverseOrder());

       // Displaying elements of String Array
       System.out.println("String Array Elements in reverse order:");
       for(int i=0;i<stringArray.length;i++)
          System.out.println(stringArray[i]);}}

compiling it...

javac sortdec.java

calling it...

java sortdesc

OUTPUT

Int Array Elements in reverse order:
30
16
15
9
2
String Array Elements in reverse order:
PP
OO
FF
DD
AA

If you want to try an alphanumeric array...

//replace this line:
String[] stringArray=new String[]{"FF","PP","AA","OO","DD"};

//with this:
String[] stringArray=new String[]{"10FF","20AA","50AA"};

you gonna get the OUTPUT as follow:

50AA
20AA
10FF

source

How to remove "disabled" attribute using jQuery?

2018, without JQuery

I know the question is about JQuery: this answer is just FYI.

document.getElementById('edit').addEventListener(event => {
    event.preventDefault();
    [...document.querySelectorAll('.inputDisabled')].map(e => e.disabled = false);
}); 

What is the `data-target` attribute in Bootstrap 3?

data-target is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.

The data-target attribute should contain a CSS selector that points to the HTML Element that will be changed.

Modal Example Code from BS3:

<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  [...]
</div>

In this example, the button has data-target="#myModal", if you click on it, <div id="myModal">...</div> will be modified (in this case faded in). This happens because #myModal in CSS selectors points to elements that have an id attribute with the myModal value.

Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

How to integrate sourcetree for gitlab

It worked for me, but only with https link in repository setting (Repository => Repository Settings). You need to change setting to:

URL / path: https://**********.com/username/project.git
Host Type - Stash
Host Root URL - your root URL to GitLab (example:https://**********.com/) 
Username - leave blank

or in some cases if you have ssh url like:

[email protected]:USER/REPOSITORY.git

and your email like:

[email protected]

then this settings should be work:

URL / path: https://test%[email protected]:USER/REPOSITORY.git

How to break line in JavaScript?

alert("I will get back to you soon\nThanks and Regards\nSaurav Kumar");

or %0D%0A in a url

Renaming a branch in GitHub

As mentioned, delete the old one on GitHub and re-push, though the commands used are a bit more verbose than necessary:

git push origin :name_of_the_old_branch_on_github
git push origin new_name_of_the_branch_that_is_local

Dissecting the commands a bit, the git push command is essentially:

git push <remote> <local_branch>:<remote_branch>

So doing a push with no local_branch specified essentially means "take nothing from my local repository, and make it the remote branch". I've always thought this to be completely kludgy, but it's the way it's done.

As of Git 1.7 there is an alternate syntax for deleting a remote branch:

git push origin --delete name_of_the_remote_branch

As mentioned by @void.pointer in the comments

Note that you can combine the 2 push operations:

git push origin :old_branch new_branch

This will both delete the old branch and push the new one.

This can be turned into a simple alias that takes the remote, original branch and new branch name as arguments, in ~/.gitconfig:

[alias]
    branchm = "!git branch -m $2 $3 && git push $1 :$2 $3 -u #"

Usage:

git branchm origin old_branch new_branch

Note that positional arguments in shell commands were problematic in older (pre 2.8?) versions of Git, so the alias might vary according to the Git version. See this discussion for details.

Installing NumPy via Anaconda in Windows

I had the same problem, getting the message "ImportError: No module named numpy".

I'm also using anaconda and found out that I needed to add numpy to the ENV I was using. You can check the packages you have in your environment with the command:

conda list

So, when I used that command, numpy was not displayed. If that is your case, you just have to add it, with the command:

conda install numpy

After I did that, the error with the import numpy was gone

Array of arrays (Python/NumPy)

It seems strange that you would write arrays without commas (is that a MATLAB syntax?)

Have you tried going through NumPy's documentation on multi-dimensional arrays?

It seems NumPy has a "Python-like" append method to add items to a NumPy n-dimensional array:

>>> p = np.array([[1,2],[3,4]])

>>> p = np.append(p, [[5,6]], 0)

>>> p = np.append(p, [[7],[8],[9]],1)

>>> p
array([[1, 2, 7], [3, 4, 8], [5, 6, 9]])

It has also been answered already...

From the documentation for MATLAB users:

You could use a matrix constructor which takes a string in the form of a matrix MATLAB literal:

mat("1 2 3; 4 5 6")

or

matrix("[1 2 3; 4 5 6]")

Please give it a try and tell me how it goes.

How get all values in a column using PHP?

Since mysql_* are deprecated, so here is the solution using mysqli.

$mysqli = new mysqli('host', 'username', 'password', 'database');
if($mysqli->connect_errno>0)
{
  die("Connection to MySQL-server failed!"); 
}
$resultArr = array();//to store results
//to execute query
$executingFetchQuery = $mysqli->query("SELECT `name` FROM customers WHERE 1");
if($executingFetchQuery)
{
   while($arr = $executingFetchQuery->fetch_assoc())
   {
        $resultArr[] = $arr['name'];//storing values into an array
   }
}
print_r($resultArr);//print the rows returned by query, containing specified columns

There is another way to do this using PDO

  $db = new PDO('mysql:host=host_name;dbname=db_name', 'username', 'password'); //to establish a connection
  //to fetch records
  $fetchD = $db->prepare("SELECT `name` FROM customers WHERE 1");
  $fetchD->execute();//executing the query
  $resultArr = array();//to store results
  while($row = $fetchD->fetch())
  {
     $resultArr[] = $row['name'];
  }
  print_r($resultArr);

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

The problem is that dataTable is not defined at the point you are calling this method.

Ensure that you are loading the .js files in the correct order:

<script src="/Scripts/jquery.dataTables.js"></script>
<script src="/Scripts/dataTables.bootstrap.js"></script>

Change the mouse pointer using JavaScript

document.body.style.cursor = 'cursorurl';

Python: avoid new line with print command

In Python 2.x just put a , at the end of your print statement. If you want to avoid the blank space that print puts between items, use sys.stdout.write.

import sys

sys.stdout.write('hi there')
sys.stdout.write('Bob here.')

yields:

hi thereBob here.

Note that there is no newline or blank space between the two strings.

In Python 3.x, with its print() function, you can just say

print('this is a string', end="")
print(' and this is on the same line')

and get:

this is a string and this is on the same line

There is also a parameter called sep that you can set in print with Python 3.x to control how adjoining strings will be separated (or not depending on the value assigned to sep)

E.g.,

Python 2.x

print 'hi', 'there'

gives

hi there

Python 3.x

print('hi', 'there', sep='')

gives

hithere

OpenCV & Python - Image too big to display

Looks like opencv lib is pretty sensitive to parameters passed to the methods. The following code worked for me using opencv 4.3.0:

win_name = "visualization"  #  1. use var to specify window name everywhere
cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)  #  2. use 'normal' flag
img = cv2.imread(filename)
h,w = img.shape[:2]  #  suits for image containing any amount of channels
h = int(h / resize_factor)  #  one must compute beforehand
w = int(w / resize_factor)  #  and convert to INT
cv2.resizeWindow(win_name, w, h)  #  use variables defined/computed BEFOREHAND
cv2.imshow(win_name, img)

How can I conditionally require form inputs with AngularJS?

For Angular2

<input type='email' 
    [(ngModel)]='contact.email'
    [required]='!contact.phone' >

How do you strip a character out of a column in SQL Server?

Take a look at the following function - REPLACE():

select replace(DataColumn, StringToReplace, NewStringValue)

//example to replace the s in test with the number 1
select replace('test', 's', '1')
//yields te1t

http://msdn.microsoft.com/en-us/library/ms186862.aspx

EDIT
If you want to remove a string, simple use the replace function with an empty string as the third parameter like:

select replace(DataColumn, 'StringToRemove', '')

Can multiple different HTML elements have the same ID if they're different elements?

We can use class name instead of using id. html id are should be unique but classes are not. when retrieving data using class name can reduce number of code lines in your js files.

_x000D_
_x000D_
$(document).ready(function ()_x000D_
{_x000D_
    $(".class_name").click(function ()_x000D_
    {_x000D_
        //code_x000D_
    });_x000D_
});
_x000D_
_x000D_
_x000D_

How to capture a backspace on the onkeydown event

Nowadays, code to do this should look something like:

document.getElementById('foo').addEventListener('keydown', function (event) {
    if (event.keyCode == 8) {
        console.log('BACKSPACE was pressed');

        // Call event.preventDefault() to stop the character before the cursor
        // from being deleted. Remove this line if you don't want to do that.
        event.preventDefault();
    }
    if (event.keyCode == 46) {
        console.log('DELETE was pressed');

        // Call event.preventDefault() to stop the character after the cursor
        // from being deleted. Remove this line if you don't want to do that.
        event.preventDefault();
    }
});

although in the future, once they are broadly supported in browsers, you may want to use the .key or .code attributes of the KeyboardEvent instead of the deprecated .keyCode.

Details worth knowing:

  • Calling event.preventDefault() in the handler of a keydown event will prevent the default effects of the keypress. When pressing a character, this stops it from being typed into the active text field. When pressing backspace or delete in a text field, it prevents a character from being deleted. When pressing backspace without an active text field, in a browser like Chrome where backspace takes you back to the previous page, it prevents that behaviour (as long as you catch the event by adding your event listener to document instead of a text field).

  • Documentation on how the value of the keyCode attribute is determined can be found in section B.2.1 How to determine keyCode for keydown and keyup events in the W3's UI Events Specification. In particular, the codes for Backspace and Delete are listed in B.2.3 Fixed virtual key codes.

  • There is an effort underway to deprecate the .keyCode attribute in favour of .key and .code. The W3 describe the .keyCode property as "legacy", and MDN as "deprecated".

    One benefit of the change to .key and .code is having more powerful and programmer-friendly handling of non-ASCII keys - see the specification that lists all the possible key values, which are human-readable strings like "Backspace" and "Delete" and include values for everything from modifier keys specific to Japanese keyboards to obscure media keys. Another, which is highly relevant to this question, is distinguishing between the meaning of a modified keypress and the physical key that was pressed.

    On small Mac keyboards, there is no Delete key, only a Backspace key. However, pressing Fn+Backspace is equivalent to pressing Delete on a normal keyboard - that is, it deletes the character after the text cursor instead of the one before it. Depending upon your use case, in code you might want to handle a press of Backspace with Fn held down as either Backspace or Delete. That's why the new key model lets you choose.

    The .key attribute gives you the meaning of the keypress, so Fn+Backspace will yield the string "Delete". The .code attribute gives you the physical key, so Fn+Backspace will still yield the string "Backspace".

    Unfortunately, as of writing this answer, they're only supported in 18% of browsers, so if you need broad compatibility you're stuck with the "legacy" .keyCode attribute for the time being. But if you're a reader from the future, or if you're targeting a specific platform and know it supports the new interface, then you could write code that looked something like this:

    document.getElementById('foo').addEventListener('keydown', function (event) {
        if (event.code == 'Delete') {
            console.log('The physical key pressed was the DELETE key');
        }
        if (event.code == 'Backspace') {
            console.log('The physical key pressed was the BACKSPACE key');
        } 
        if (event.key == 'Delete') {
            console.log('The keypress meant the same as pressing DELETE');
            // This can happen for one of two reasons:
            // 1. The user pressed the DELETE key
            // 2. The user pressed FN+BACKSPACE on a small Mac keyboard where
            //    FN+BACKSPACE deletes the character in front of the text cursor,
            //    instead of the one behind it.
        }
        if (event.key == 'Backspace') {
            console.log('The keypress meant the same as pressing BACKSPACE');
        }
    });
    

Request string without GET arguments

I had the same problem when I wanted a link back to homepage. I tried this and it worked:

<a href="<?php echo $_SESSION['PHP_SELF']; ?>?">

Note the question mark at the end. I believe that tells the machine stop thinking on behalf of the coder :)

How to force a line break on a Javascript concatenated string?

Using Backtick

Backticks are commonly used for multi-line strings or when you want to interpolate an expression within your string

_x000D_
_x000D_
let title = 'John';_x000D_
let address = 'address';_x000D_
let address2 = 'address2222';_x000D_
let address3 = 'address33333';_x000D_
let address4 = 'address44444';_x000D_
document.getElementById("address_box").innerText = `${title} _x000D_
${address}_x000D_
${address2}_x000D_
${address3} _x000D_
${address4}`;
_x000D_
<div id="address_box">_x000D_
</div>
_x000D_
_x000D_
_x000D_

json: cannot unmarshal object into Go value of type

You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.

Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.

Microsoft Azure: How to create sub directory in a blob container

You do not need to create sub directory. Just create blob container and use file name like the variable filename as below code:

string filename = "document/tech/user-guide.pdf";
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(ConnectionString);
CloudBlockBlob blob = cloudBlobContainer.GetBlockBlobReference(filename);
blob.StreamWriteSizeInBytes = 20 * 1024;
blob.UploadFromStream(fileStream); // fileStream is System.IO.Stream

How to use GROUP BY to concatenate strings in MySQL?

The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024 characters, so we first do:

SET group_concat_max_len=100000000;

and then, for example:

SELECT pub_id,GROUP_CONCAT(cate_id SEPARATOR ' ') FROM book_mast GROUP BY pub_id

Enter key in textarea

Simply add this tad to your textarea.

onkeydown="if(event.keyCode == 13) return false;"

Get the contents of a table row with a button click

Here is the complete code for simple example of delegate

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>
<body>

<div class="container">
  <h2>Striped Rows</h2>
  <p>The .table-striped class adds zebra-stripes to a table:</p>            
  <table class="table table-striped">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>

      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td>Doe</td>
        <td>[email protected]</td>
        <td>click</td>
      </tr>
      <tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>[email protected]</td>
        <td>click</td>
      </tr>
      <tr>
        <td>July</td>
        <td>Dooley</td>
        <td>[email protected]</td>
        <td>click</td>
      </tr>

    </tbody>
  </table>
  <script>
  $(document).ready(function(){
  $("div").delegate("table tbody tr td:nth-child(4)", "click", function(){
  var $row = $(this).closest("tr"),        // Finds the closest row <tr> 
    $tds = $row.find("td:nth-child(2)");
     $.each($tds, function() {
        console.log($(this).text());
        var x = $(this).text();
        alert(x);
    });
    });
});
  </script>
</div>

</body>
</html>

Summarizing multiple columns with dplyr?

The dplyr package contains summarise_all for this aim:

library(dplyr)
# summarise_all was replaced with the summarise(acrosss(..)) syntax dplyr >=1.00
df %>% group_by(grp) %>% summarise(across(everything(), list(mean)))
#> # A tibble: 3 x 5
#>     grp     a     b     c     d
#>   <int> <dbl> <dbl> <dbl> <dbl>
#> 1     1  3.08  2.98  2.98  2.91
#> 2     2  3.03  3.04  2.97  2.87
#> 3     3  2.85  2.95  2.95  3.06

Alternatively, the purrrlyr package provides the same functionality:

library(purrrlyr)
df %>% slice_rows("grp") %>% dmap(mean)
#> # A tibble: 3 x 5
#>     grp     a     b     c     d
#>   <int> <dbl> <dbl> <dbl> <dbl>
#> 1     1  3.08  2.98  2.98  2.91
#> 2     2  3.03  3.04  2.97  2.87
#> 3     3  2.85  2.95  2.95  3.06

Also don't forget about data.table (use keyby to sort sort groups):

library(data.table)
setDT(df)[, lapply(.SD, mean), keyby = grp]
#>    grp        a        b        c        d
#> 1:   1 3.079412 2.979412 2.979412 2.914706
#> 2:   2 3.029126 3.038835 2.967638 2.873786
#> 3:   3 2.854701 2.948718 2.951567 3.062678

Let's try to compare performance.

library(dplyr)
library(purrrlyr)
library(data.table)
library(bench)
set.seed(123)
n <- 10000
df <- data.frame(
  a = sample(1:5, n, replace = TRUE), 
  b = sample(1:5, n, replace = TRUE), 
  c = sample(1:5, n, replace = TRUE), 
  d = sample(1:5, n, replace = TRUE), 
  grp = sample(1:3, n, replace = TRUE)
)
dt <- setDT(df)
mark(
  dplyr = df %>% group_by(grp) %>% summarise(across(everything(), list(mean))),
  purrrlyr = df %>% slice_rows("grp") %>% dmap(mean),
  data.table = dt[, lapply(.SD, mean), keyby = grp],
  check = FALSE
)
#> # A tibble: 3 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 dplyr        2.81ms   2.85ms      328.        NA     17.3
#> 2 purrrlyr     7.96ms   8.04ms      123.        NA     24.5
#> 3 data.table 596.33µs 707.91µs     1409.        NA     10.3

What is *.o file?

It is important to note that object files are assembled to binary code in a format that is relocatable. This is a form which allows the assembled code to be loaded anywhere into memory for use with other programs by a linker.

Instructions that refer to labels will not yet have an address assigned for these labels in the .o file.

These labels will be written as '0' and the assembler creates a relocation record for these unknown addresses. When the file is linked and output to an executable the unknown addresses are resolved and the program can be executed.

You can use the nm tool on an object file to list the symbols defined in a .o file.

What parameters should I use in a Google Maps URL to go to a lat-lon?

http://maps.google.com/maps?q=58%2041.881N%20152%2031.324W

Just use the coordinates as q-parameter. Strip the z and t prameters. While z should actually just be the zoom level, it seems that it won't work if you set any.

t is the map type. Having that said, it's not obvious how those parameters would affect the result in the shown way. But they do.

Maybe you should try the ll-parameter, but only decimal format will be accepted.

You can find a quick overview of all the parameters here.

How to get the fields in an Object via reflection?

I've an object (basically a VO) in Java and I don't know its type. I need to get values which are not null in that object.

Maybe you don't necessary need reflection for that -- here is a plain OO design that might solve your problem:

  1. Add an interface Validation which expose a method validate which checks the fields and return whatever is appropriate.
  2. Implement the interface and the method for all VO.
  3. When you get a VO, even if it's concrete type is unknown, you can typecast it to Validation and check that easily.

I guess that you need the field that are null to display an error message in a generic way, so that should be enough. Let me know if this doesn't work for you for some reason.

Modifying Objects within stream in Java8 while iterating

Yes, you can modify state of objects inside your stream, but most often you should avoid modifying state of source of stream. From non-interference section of stream package documentation we can read that:

For most data sources, preventing interference means ensuring that the data source is not modified at all during the execution of the stream pipeline. The notable exception to this are streams whose sources are concurrent collections, which are specifically designed to handle concurrent modification. Concurrent stream sources are those whose Spliterator reports the CONCURRENT characteristic.

So this is OK

  List<User> users = getUsers();
  users.stream().forEach(u -> u.setProperty(value));
//                       ^    ^^^^^^^^^^^^^

but this in most cases is not

  users.stream().forEach(u -> users.remove(u));
//^^^^^                       ^^^^^^^^^^^^

and may throw ConcurrentModificationException or even other unexpected exceptions like NPE:

List<Integer> list = IntStream.range(0, 10).boxed().collect(Collectors.toList());

list.stream()
    .filter(i -> i > 5)
    .forEach(i -> list.remove(i));  //throws NullPointerException

Changing SQL Server collation to case insensitive from case sensitive?

You can do that but the changes will affect for new data that is inserted on the database. On the long run follow as suggested above.

Also there are certain tricks you can override the collation, such as parameters for stored procedures or functions, alias data types, and variables are assigned the default collation of the database. To change the collation of an alias type, you must drop the alias and re-create it.

You can override the default collation of a literal string by using the COLLATE clause. If you do not specify a collation, the literal is assigned the database default collation. You can use DATABASEPROPERTYEX to find the current collation of the database.

You can override the server, database, or column collation by specifying a collation in the ORDER BY clause of a SELECT statement.

How do I convert a number to a numeric, comma-separated formatted string?

Not sure it works in tsql, but some platforms have to_char():

test=#select to_char(131213211653.78, '9,999,999,999,999.99');
        to_char        
-----------------------
    131,213,211,653.78
test=# select to_char(131213211653.78, '9G999G999G999G999D99');
        to_char        
-----------------------
    131,213,211,653.78
test=# select to_char(485, 'RN');
     to_char     
-----------------
         CDLXXXV

As the example suggests, the format's length needs to match that of the number for best results, so you might want to wrap it in a function (e.g. number_format()) if needed.


Converting to money works too, as point out by the other repliers.

test=# select substring(cast(cast(131213211653.78 as money) as varchar) from 2);
     substring      
--------------------
 131,213,211,653.78

Multiple conditions in a C 'for' loop

The comma operator evaluates all its operands and yields the value of the last one. So basically whichever condition you write first, it will be disregarded, and the second one will be significant only.

for (i = 0; j >= 0, i <= 5; i++)

is thus equivalent with

for (i = 0; i <= 5; i++)

which may or may not be what the author of the code intended, depending on his intents - I hope this is not production code, because if the programmer having written this wanted to express an AND relation between the conditions, then this is incorrect and the && operator should have been used instead.

SQL Server 2012 Install or add Full-text search

You can add full text to an existing instance by changing the SQL Server program in Programs and Features. Follow the steps below. You might need the original disk or ISO for the installation to complete. (Per HotN's comment: If you have SQL Server Express, make sure it is SQL Server Express With Advanced Services.)

Directions:

  1. Open the Programs and Features control panel.
  2. Select Microsoft SQL Server 2012 and click Change.
  3. When prompted to Add/Repair/Remove, select Add.
  4. Advance through the wizard until the Feature Selection screen. Then select Full-Text Search.

Step 1 Step 2

enter image description here

  1. On the Installation Type screen, select the appropriate SQL Server instance.

  2. Advance through the rest of the wizard.

Source (with screenshots): http://www.techrepublic.com/blog/networking/adding-sql-full-text-search-to-an-existing-sql-server/5546

How to return string value from the stored procedure

change your

return @str1+'present in the string' ;

to

set @r = @str1+'present in the string' 

Reading and writing binary file

You should pass length into fwrite instead of sizeof(buffer).

Python: How to get values of an array at certain index positions?

You can use index arrays, simply pass your ind_pos as an index argument as below:

a = np.array([0,88,26,3,48,85,65,16,97,83,91])
ind_pos = np.array([1,5,7])

print(a[ind_pos])
# [88,85,16]

Index arrays do not necessarily have to be numpy arrays, they can be also be lists or any sequence-like object (though not tuples).

Is there a sleep function in JavaScript?

You can use the setTimeout or setInterval functions.

Java - checking if parseInt throws exception

instead of trying & catching expressions.. its better to run regex on the string to ensure that it is a valid number..

How can a windows service programmatically restart itself?

const string strCmdText = "/C net stop \"SERVICENAME\"&net start \"SERVICENAME\"";
Process.Start("CMD.exe", strCmdText);

where SERVICENAME is the name of your service (double quotes included to account for spaces in the service name, can be omitted otherwise).

Clean, no auto-restart configuration necessary.

How to pass values arguments to modal.show() function in Bootstrap

Here's how i am calling my modal

<a data-toggle="modal" data-id="190" data-target="#modal-popup">Open</a>

Here's how i am obtaining value in the modal

$('#modal-popup').on('show.bs.modal', function(e) {
    console.log($(e.relatedTarget).data('id')); // 190 will be printed
});

iPhone: Setting Navigation Bar Title

There's one issue with using self.title = @"title";

If you're using Navigation Bar along with Tab bar, the above line also changes the label for the Tab Bar Item. To avoid this, use what @testing suggested

self.navigationItem.title = @"MyTitle";

Concept behind putting wait(),notify() methods in Object class

wait and notify operations work on implicit lock, and implicit lock is something that make inter thread communication possible. And all objects have got their own copy of implicit object. so keeping wait and notify where implicit lock lives is a good decision.

Alternatively wait and notify could have lived in Thread class as well. than instead of wait() we may have to call Thread.getCurrentThread().wait(), same with notify. For wait and notify operations there are two required parameters, one is thread who will be waiting or notifying other is implicit lock of the object . both are these could be available in Object as well as thread class as well. wait() method in Thread class would have done the same as it is doing in Object class, transition current thread to waiting state wait on the lock it had last acquired.

So yes i think wait and notify could have been there in Thread class as well but its more like a design decision to keep it in object class.

Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate

I know the answers were correct at the time of asking the question - but since people (like me this minute) still happen to find them wondering why their WildFly 10 was behaving differently, I'd like to give an update for the current Hibernate 5.x version:

In the Hibernate 5.2 User Guide it is stated in chapter 11.2. Applying fetch strategies:

The Hibernate recommendation is to statically mark all associations lazy and to use dynamic fetching strategies for eagerness. This is unfortunately at odds with the JPA specification which defines that all one-to-one and many-to-one associations should be eagerly fetched by default. Hibernate, as a JPA provider, honors that default.

So Hibernate as well behaves like Ashish Agarwal stated above for JPA:

OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER

(see JPA 2.1 Spec)

Change the size of a JTextField inside a JBorderLayout

From the api on GridLayout:

The container is divided into equal-sized rectangles, and one component is placed in each rectangle.

Try using FlowLayout or GridBagLayout for your set size to be meaningful. Also, @Serplat is correct. You need to use setPreferredSize( Dimension ) instead of setSize( int, int ).

    JPanel displayPanel = new JPanel();
    // JPanel displayPanel = new JPanel( new GridLayout( 4, 2 ) );
    // JPanel displayPanel = new JPanel( new BorderLayout() );
    // JPanel displayPanel = new JPanel( new GridBagLayout() );

    JTextField titleText = new JTextField( "title" );

    titleText.setPreferredSize( new Dimension( 200, 24 ) );

    // For FlowLayout and GridLayout, uncomment:
    displayPanel.add( titleText );

    // For BorderLayout, uncomment:
    // displayPanel.add( titleText, BorderLayout.NORTH );

    // For GridBagLayout, uncomment:
    // displayPanel.add( titleText, new GridBagConstraints( 0, 0, 1, 1, 1.0,
    // 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
    // new Insets( 0, 0, 0, 0 ), 0, 0 ) );

Protect image download

If it is only image then JavaScript is not really necessary. Try using this in your html file :

<img src="sample-img-15.jpg" alt="#" height="24" width="100" onContextMenu="return false;" />

How to upgrade Python version to 3.7?

On ubuntu you can add this PPA Repository and use it to install python 3.7: https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.7

Or a different PPA that provides several Python versions is Deadsnakes: https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa

See also here: https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get (I know it says 3.6 in the url, but the deadsnakes ppa also contains 3.7 so you can use it for 3.7 just the same)

If you want "official" you'd have to install it from the sources from the site, get the code (which you already downloaded) and do this:

tar -xf Python-3.7.0.tar.xz
cd Python-3.7.0
./configure
make
sudo make install        <-- sudo is required.

This might take a while

React-Router External link

With Link component of react-router you can do that. In the "to" prop you can specify 3 types of data:

  • a string: A string representation of the Link location, created by concatenating the location’s pathname, search, and hash properties.
  • an object: An object that can have any of the following properties:
    • pathname: A string representing the path to link to.
    • search: A string representation of query parameters.
    • hash: A hash to put in the URL, e.g. #a-hash.
    • state: State to persist to the location.
  • a function: A function to which current location is passed as an argument and which should return location representation as a string or as an object

For your example (external link):

https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies

You can do the following:

<Link to={{ pathname: "https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies" }} target="_blank" />

You can also pass props you’d like to be on the such as a title, id, className, etc.

Remove gutter space for a specific div only

Simplest way to remove padding and margin is with simple css.

<div class="header" style="margin:0px;padding:0px;">
.....
.....
.....
</div>

Is mathematics necessary for programming?

Well you generated a number of responses, and no I did not read them all. I am in the middle on this, no you certainly do not need math in order to be a programmer. Assembler vs device drivers in linux are no more or less complicated than the other and neither require math.

In no way shape or form do you need to take or pass a math class for any of this.

I will agree that the problem solving mindset for programming is quite similar to that of math solutions, and as a result math probably comes easily. or the contrary if math is hard then programming may be hard. A class or a degree or any pieces of paper or trophies are not required, going off and learning stuff, sure.

Now if you cannot convert from hex to binary to decimal quickly either in your head, on paper, or using a calculator you are going to struggle. If you want to get into networking and other things that involve timing, which kernel drivers often do but dont have to. You are going to struggle. I know of a very long list of people with math degrees and/or computer science, and/or engineering degrees that struggle with the rate calculations, bits per second, bytes per second, how much memory you need to do something, etc. To some extent it may be considered some sort of knack that some have and others have to work toward.

My bottom line is I believe in will power, if you want to learn this stuff you can and will, it is as simple as that. You dont need to take a class or spend a lot of money, linux and qemu for example can keep you busy for quite some time, different asm langauges, etc. crashable environments for kernel development, embedded, etc. You are not limited to that, but I dont believe that you have to run off and take any classes if you dont want to. If you want to then sure take some ee classes, some cs classes and some math classes..

C++ Calling a function from another class

Here's my solution to the issue. Tried to keep it straight and simple.

#include <iostream>
using namespace std;

class Game{
public:
  void init(){
    cout << "Hi" << endl;
  }
}g;

class b : Game{  //class b uses/imports class Game
public:
  void h(){
    init(); //Use function from class Game
  }
}A;

int main()
{
  A.h();
  return 0;
}

List Git aliases

Search or show all aliases

Add to your .gitconfig under [alias]:

aliases = !git config --list | grep ^alias\\. | cut -c 7- | grep -Ei --color \"$1\" "#"

Then you can do

  • git aliases - show ALL aliases
  • git aliases commit - only aliases containing "commit"

Unique on a dataframe with only selected columns

Minor update in @Joran's code.
Using the code below, you can avoid the ambiguity and only get the unique of two columns:

dat <- data.frame(id=c(1,1,3), id2=c(1,1,4) ,somevalue=c("x","y","z"))    
dat[row.names(unique(dat[,c("id", "id2")])), c("id", "id2")]

Converting Symbols, Accent Letters to English Alphabet

If the need is to convert "òéisöç->oeisoc", you can use this a starting point :

public class AsciiUtils {
    private static final String PLAIN_ASCII =
      "AaEeIiOoUu"    // grave
    + "AaEeIiOoUuYy"  // acute
    + "AaEeIiOoUuYy"  // circumflex
    + "AaOoNn"        // tilde
    + "AaEeIiOoUuYy"  // umlaut
    + "Aa"            // ring
    + "Cc"            // cedilla
    + "OoUu"          // double acute
    ;

    private static final String UNICODE =
     "\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"             
    + "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD" 
    + "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177" 
    + "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
    + "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF" 
    + "\u00C5\u00E5"                                                             
    + "\u00C7\u00E7" 
    + "\u0150\u0151\u0170\u0171" 
    ;

    // private constructor, can't be instanciated!
    private AsciiUtils() { }

    // remove accentued from a string and replace with ascii equivalent
    public static String convertNonAscii(String s) {
       if (s == null) return null;
       StringBuilder sb = new StringBuilder();
       int n = s.length();
       for (int i = 0; i < n; i++) {
          char c = s.charAt(i);
          int pos = UNICODE.indexOf(c);
          if (pos > -1){
              sb.append(PLAIN_ASCII.charAt(pos));
          }
          else {
              sb.append(c);
          }
       }
       return sb.toString();
    }

    public static void main(String args[]) {
       String s = 
         "The result : È,É,Ê,Ë,Û,Ù,Ï,Î,À,Â,Ô,è,é,ê,ë,û,ù,ï,î,à,â,ô,ç";
       System.out.println(AsciiUtils.convertNonAscii(s));
       // output : 
       // The result : E,E,E,E,U,U,I,I,A,A,O,e,e,e,e,u,u,i,i,a,a,o,c
    }
}

The JDK 1.6 provides the java.text.Normalizer class that can be used for this task.

See an example here

How to exit when back button is pressed?

The app will only exit if there are no activities in the back stack. SO add this line in your manifest android:noHistory="true" to all the activities that you dont want to be back stacked.And then to close the app call the finish() in the OnBackPressed

<activity android:name=".activities.DemoActivity"
            android:screenOrientation="portrait"
            **android:noHistory="true"**
            />

How to remove underline from a link in HTML?

I suggest to use :hover to avoid underline if mouse pointer is over an anchor

a:hover {
   text-decoration:none;
}

Encode URL in JavaScript?

Encode URL String

    var url = $(location).attr('href'); //get current url
    //OR
    var url = 'folder/index.html?param=#23dd&noob=yes'; //or specify one

var encodedUrl = encodeURIComponent(url); console.log(encodedUrl); //outputs folder%2Findex.html%3Fparam%3D%2323dd%26noob%3Dyes for more info go http://www.sitepoint.com/jquery-decode-url-string

How do you check for permissions to write to a directory or file?

You can try following code block to check if the directory is having Write Access.

It checks the FileSystemAccessRule.

           string directoryPath = "C:\\XYZ"; //folderBrowserDialog.SelectedPath;
           bool isWriteAccess = false;
           try
           {
              AuthorizationRuleCollection collection = Directory.GetAccessControl(directoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
              foreach (FileSystemAccessRule rule in collection)
              {
                 if (rule.AccessControlType == AccessControlType.Allow)
                 {
                    isWriteAccess = true;
                    break;
                 }
              }
           }
           catch (UnauthorizedAccessException ex)
           {
              isWriteAccess = false;
           }
           catch (Exception ex)
           {
              isWriteAccess = false;
           }
           if (!isWriteAccess)
           {
             //handle notifications                 
           }

Session 'app': Error Launching activity

I did all suggestions above, but they didn't work! I rebuilt the project, uninstalled the app from my real device, unplugged USB, then I run Android Studio and run the app on my real device and the issue was gone.

Hope this helps!

Unable to resolve host "<URL here>" No address associated with host name

Sometimes, although you add <uses-permission android:name="android.permission.INTERNET" /> in the AndroidManifest and you have a WiFi connection, this exception can be thrown. In my case, I have turned off WiFi and then turned it on again. This resolved the error. Weird solution, but sometimes it works.

Pipe to/from the clipboard in Bash script

This function will test what clipboard exists and use it.

To verify copy past into your shell then call the function clippaste.

clippaste () {
    if [[ $OSTYPE == darwin* ]]
    then
            pbpaste
    elif [[ $OSTYPE == cygwin* ]]
    then
            cat /dev/clipboard
    else
            if command -v xclip &> /dev/null
            then
                    xclip -out -selection clipboard
            elif command -v xsel
            then
                    xsel --clipboard --output
            else
                    print "clipcopy: Platform $OSTYPE not supported or xclip/xsel not installed" >&2
                    return 1
            fi
    fi
}

What does "xmlns" in XML mean?

You have name spaces so you can have globally unique elements. However, 99% of the time this doesn't really matter, but when you put it in the perspective of The Semantic Web, it starts to become important.

For example, you could make an XML mash-up of different schemes just by using the appropriate xmlns. For example, mash up friend of a friend with vCard, etc.

How to get all the AD groups for a particular user?

You should use System.DirectoryServices.AccountManagement. It's much easier. Here is a nice code project article giving you an overview on all the classes in this DLL.

As you pointed out, your current approach doesn't find out the primary group. Actually, it's much worse than you thought. There are some more cases that it doesn't work, like the domain local group from another domain. You can check here for details. Here is how the code looks like if you switch to use System.DirectoryServices.AccountManagement. The following code can find the immediate groups this user assigned to, which includes the primary group.

UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext (ContextType.Domain, "mydomain.com"), IdentityType.SamAccountName, "username");
foreach (GroupPrincipal group in user.GetGroups())
{
    Console.Out.WriteLine(group);
}

Node JS Error: ENOENT

use "temp" in lieu of "tmp"

"/temp/test.png"

it worked for me after i realized the tmp is a temporary folder that didn't exist on my computer, but my temp was my temporary folder

///

EDIT:

I also created a new folder "tmp" in my C: drive and everything worked perfectly. The book may have missed mentioning that small step

check out http://webchat.freenode.net/?channels=node.js to chat with some of the node.js community

How do I make an Event in the Usercontrol and have it handled in the Main Form?

For those looking to do this in VB, here's how I got mine to work with a checkbox.

Background: I was trying to make my own checkbox that is a slider/switch control. I've only included the relevant code for this question.

In User control MyCheckbox.ascx

<asp:CheckBox ID="checkbox" runat="server" AutoPostBack="true" />

In User control MyCheckbox.ascx.vb

Create an EventHandler (OnCheckChanged). When an event fires on the control (ID="checkbox") inside your usercontrol (MyCheckBox.ascx), then fire your EventHandler (OnCheckChanged).

Public Event OnCheckChanged As EventHandler

Private Sub checkbox_CheckedChanged(sender As Object, e As EventArgs) Handles checkbox.CheckedChanged
    RaiseEvent OnCheckChanged(Me, e)
End Sub

In Page MyPage.aspx

<uc:MyCheckbox runat="server" ID="myCheck" OnCheckChanged="myCheck_CheckChanged" />

Note: myCheck_CheckChanged didn't fire until I added the Handles clause below

In Page MyPage.aspx.vb

Protected Sub myCheck_CheckChanged (sender As Object, e As EventArgs) Handles scTransparentVoting.OnCheckChanged
    'Do some page logic here
End Sub

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

Android EditText view Floating Hint in Material Design

The Android support library can be imported within gradle in the dependencies :

    compile 'com.android.support:design:22.2.0'

It should be included within GradlePlease! And as an example to use it:

 <android.support.design.widget.TextInputLayout
    android:id="@+id/to_text_input_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <AutoCompleteTextView
        android:id="@+id/autoCompleteTextViewTo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="To"
        android:layout_marginTop="45dp"
        />
</android.support.design.widget.TextInputLayout>

Btw, the editor may not understand that AutoCompleteTextView is allowed within TextInputLayout.

How to get the user input in Java?

class ex1 {    
    public static void main(String args[]){
        int a, b, c;
        a = Integer.parseInt(args[0]);
        b = Integer.parseInt(args[1]);
        c = a + b;
        System.out.println("c = " + c);
    }
}
// Output  
javac ex1.java
java ex1 10 20 
c = 30

C/C++ check if one bit is set in, i.e. int variable

Yeah, I know I don't "have" to do it this way. But I usually write:

    /* Return type (8/16/32/64 int size) is specified by argument size. */
template<class TYPE> inline TYPE BIT(const TYPE & x)
{ return TYPE(1) << x; }

template<class TYPE> inline bool IsBitSet(const TYPE & x, const TYPE & y)
{ return 0 != (x & y); }

E.g.:

IsBitSet( foo, BIT(3) | BIT(6) );  // Checks if Bit 3 OR 6 is set.

Amongst other things, this approach:

  • Accommodates 8/16/32/64 bit integers.
  • Detects IsBitSet(int32,int64) calls without my knowledge & consent.
  • Inlined Template, so no function calling overhead.
  • const& references, so nothing needs to be duplicated/copied. And we are guaranteed that the compiler will pick up any typo's that attempt to change the arguments.
  • 0!= makes the code more clear & obvious. The primary point to writing code is always to communicate clearly and efficiently with other programmers, including those of lesser skill.
  • While not applicable to this particular case... In general, templated functions avoid the issue of evaluating arguments multiple times. A known problem with some #define macros.
    E.g.: #define ABS(X) (((X)<0) ? - (X) : (X))
          ABS(i++);

How to stop a JavaScript for loop?

To stop a for loop early in JavaScript, you use break:

var remSize = [], 
    szString,
    remData,
    remIndex,
    i;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // Set a default if we don't find it
for (i = 0; i < remSize.length; i++) {      
     // I'm looking for the index i, when the condition is true
     if (remSize[i].size === remData.size) {
          remIndex = i;
          break;       // <=== breaks out of the loop early
     }
}

If you're in an ES2015 (aka ES6) environment, for this specific use case, you can use Array#findIndex (to find the entry's index) or Array#find (to find the entry itself), both of which can be shimmed/polyfilled:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = remSize.findIndex(function(entry) {
     return entry.size === remData.size;
});

Array#find:

var remSize = [], 
    szString,
    remData,
    remEntry;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remEntry = remSize.find(function(entry) {
     return entry.size === remData.size;
});

Array#findIndex stops the first time the callback returns a truthy value, returning the index for that call to the callback; it returns -1 if the callback never returns a truthy value. Array#find also stops when it finds what you're looking for, but it returns the entry, not its index (or undefined if the callback never returns a truthy value).

If you're using an ES5-compatible environment (or an ES5 shim), you can use the new some function on arrays, which calls a callback until the callback returns a truthy value:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
remSize.some(function(entry, index) {
    if (entry.size === remData.size) {
        remIndex = index;
        return true; // <== Equivalent of break for `Array#some`
    }
});

If you're using jQuery, you can use jQuery.each to loop through an array; that would look like this:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
jQuery.each(remSize, function(index, entry) {
    if (entry.size === remData.size) {
        remIndex = index;
        return false; // <== Equivalent of break for jQuery.each
    }
});

C compile error: "Variable-sized object may not be initialized"

After declaring the array

int boardAux[length][length];

the simplest way to assign the initial values as zero is using for loop, even if it may be a bit lengthy

int i, j;
for (i = 0; i<length; i++)
{
    for (j = 0; j<length; j++)
        boardAux[i][j] = 0;
}

How to unzip a file in Powershell?

Hey Its working for me..

$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace("put ur zip file path here")
foreach ($item in $zip.items()) {
  $shell.Namespace("destination where files need to unzip").CopyHere($item)
}

TypeError: 'list' object cannot be interpreted as an integer

range is expecting an integer argument, from which it will build a range of integers:

>>> range(10)
range(0, 10)
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

Moreover, giving it a list will raise a TypeError because range will not know how to handle it:

>>> range([1, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object cannot be interpreted as an integer
>>>

If you want to access the items in myList, loop over the list directly:

for i in myList:
    ...

Demo:

>>> myList = [1, 2, 3]
>>> for i in myList:
...     print(i)
...
1
2
3
>>>

Email Address Validation for ASP.NET

Any script tags posted on an ASP.NET web form will cause your site to throw and unhandled exception.

You can use a asp regex validator to confirm input, just ensure you wrap your code behind method with a if(IsValid) clause in case your javascript is bypassed. If your client javascript is bypassed and script tags are posted to your asp.net form, asp.net will throw a unhandled exception.

You can use something like:

<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>

Add more than one parameter in Twig path

Consider making your route:

_files_manage:
    pattern: /files/management/{project}/{user}
    defaults: { _controller: AcmeTestBundle:File:manage }

since they are required fields. It will make your url's prettier, and be a bit easier to manage.

Your Controller would then look like

 public function projectAction($project, $user)

Code not running in IE 11, works fine in Chrome

As others have said startsWith and endsWith are part of ES6 and not available in IE11. Our company always uses lodash library as a polyfill solution for IE11. https://lodash.com/docs/4.17.4

_.startsWith([string=''], [target], [position=0])

Gets last digit of a number

No need to use any strings.Its over burden.

int i = 124;
int last= i%10;
System.out.println(last);   //prints 4

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

The server directive has to be in the http directive. It should not be outside of it.

Incase if you need detailed information, refer this.

Better way to Format Currency Input editText?

Here is how I was able to display a currency in an EditText that was easy to implement and works well for the user without the potential for crazy symbols all over the place. This will not try to do any formatting until the EditText no longer has focus. The user can still go back and make any edits without jeopardizing the formatting. I use the 'formattedPrice' variable for display only, and the 'itemPrice' variable as the value that I store/use for calculations.

It seems to be working really well, but I've only been at this for a few weeks, so any constructive criticism is absolutely welcome!

The EditText view in the xml has the following attribute:

android:inputType="numberDecimal"

Global variables:

private String formattedPrice;
private int itemPrice = 0;

In the onCreate method:

EditText itemPriceInput = findViewById(R.id.item_field_price);

itemPriceInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        String priceString = itemPriceInput.getText().toString();

        if (! priceString.equals("")) {
            itemPrice = Double.parseDouble(priceString.replaceAll("[$,]", ""));
            formattedPrice = NumberFormat.getCurrencyInstance().format(itemPrice);
            itemPriceInput.setText(formattedPrice);
        }
    }
});

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

I use it for two reasons:

  1. I can force a refresh of the icon by adding a query parameter for example ?v=2. like this: <link rel="icon" href="/favicon.ico?v=2" type="image/x-icon" />

  2. In case I need to specify the path.

How to do a SOAP wsdl web services call from the command line

For Windows I found this working:

Set http = CreateObject("Microsoft.XmlHttp")
http.open "GET", "http://www.mywebservice.com/webmethod.asmx?WSDL", FALSE
http.send ""
WScript.Echo http.responseText

Reference: CodeProject

How to catch segmentation fault in Linux?

Sometimes we want to catch a SIGSEGV to find out if a pointer is valid, that is, if it references a valid memory address. (Or even check if some arbitrary value may be a pointer.)

One option is to check it with isValidPtr() (worked on Android):

int isValidPtr(const void*p, int len) {
    if (!p) {
    return 0;
    }
    int ret = 1;
    int nullfd = open("/dev/random", O_WRONLY);
    if (write(nullfd, p, len) < 0) {
    ret = 0;
    /* Not OK */
    }
    close(nullfd);
    return ret;
}
int isValidOrNullPtr(const void*p, int len) {
    return !p||isValidPtr(p, len);
}

Another option is to read the memory protection attributes, which is a bit more tricky (worked on Android):

re_mprot.c:

#include <errno.h>
#include <malloc.h>
//#define PAGE_SIZE 4096
#include "dlog.h"
#include "stdlib.h"
#include "re_mprot.h"

struct buffer {
    int pos;
    int size;
    char* mem;
};

char* _buf_reset(struct buffer*b) {
    b->mem[b->pos] = 0;
    b->pos = 0;
    return b->mem;
}

struct buffer* _new_buffer(int length) {
    struct buffer* res = malloc(sizeof(struct buffer)+length+4);
    res->pos = 0;
    res->size = length;
    res->mem = (void*)(res+1);
    return res;
}

int _buf_putchar(struct buffer*b, int c) {
    b->mem[b->pos++] = c;
    return b->pos >= b->size;
}

void show_mappings(void)
{
    DLOG("-----------------------------------------------\n");
    int a;
    FILE *f = fopen("/proc/self/maps", "r");
    struct buffer* b = _new_buffer(1024);
    while ((a = fgetc(f)) >= 0) {
    if (_buf_putchar(b,a) || a == '\n') {
        DLOG("/proc/self/maps: %s",_buf_reset(b));
    }
    }
    if (b->pos) {
    DLOG("/proc/self/maps: %s",_buf_reset(b));
    }
    free(b);
    fclose(f);
    DLOG("-----------------------------------------------\n");
}

unsigned int read_mprotection(void* addr) {
    int a;
    unsigned int res = MPROT_0;
    FILE *f = fopen("/proc/self/maps", "r");
    struct buffer* b = _new_buffer(1024);
    while ((a = fgetc(f)) >= 0) {
    if (_buf_putchar(b,a) || a == '\n') {
        char*end0 = (void*)0;
        unsigned long addr0 = strtoul(b->mem, &end0, 0x10);
        char*end1 = (void*)0;
        unsigned long addr1 = strtoul(end0+1, &end1, 0x10);
        if ((void*)addr0 < addr && addr < (void*)addr1) {
            res |= (end1+1)[0] == 'r' ? MPROT_R : 0;
            res |= (end1+1)[1] == 'w' ? MPROT_W : 0;
            res |= (end1+1)[2] == 'x' ? MPROT_X : 0;
            res |= (end1+1)[3] == 'p' ? MPROT_P
                 : (end1+1)[3] == 's' ? MPROT_S : 0;
            break;
        }
        _buf_reset(b);
    }
    }
    free(b);
    fclose(f);
    return res;
}

int has_mprotection(void* addr, unsigned int prot, unsigned int prot_mask) {
    unsigned prot1 = read_mprotection(addr);
    return (prot1 & prot_mask) == prot;
}

char* _mprot_tostring_(char*buf, unsigned int prot) {
    buf[0] = prot & MPROT_R ? 'r' : '-';
    buf[1] = prot & MPROT_W ? 'w' : '-';
    buf[2] = prot & MPROT_X ? 'x' : '-';
    buf[3] = prot & MPROT_S ? 's' : prot & MPROT_P ? 'p' :  '-';
    buf[4] = 0;
    return buf;
}

re_mprot.h:

#include <alloca.h>
#include "re_bits.h"
#include <sys/mman.h>

void show_mappings(void);

enum {
    MPROT_0 = 0, // not found at all
    MPROT_R = PROT_READ,                                 // readable
    MPROT_W = PROT_WRITE,                                // writable
    MPROT_X = PROT_EXEC,                                 // executable
    MPROT_S = FIRST_UNUSED_BIT(MPROT_R|MPROT_W|MPROT_X), // shared
    MPROT_P = MPROT_S<<1,                                // private
};

// returns a non-zero value if the address is mapped (because either MPROT_P or MPROT_S will be set for valid addresses)
unsigned int read_mprotection(void* addr);

// check memory protection against the mask
// returns true if all bits corresponding to non-zero bits in the mask
// are the same in prot and read_mprotection(addr)
int has_mprotection(void* addr, unsigned int prot, unsigned int prot_mask);

// convert the protection mask into a string. Uses alloca(), no need to free() the memory!
#define mprot_tostring(x) ( _mprot_tostring_( (char*)alloca(8) , (x) ) )
char* _mprot_tostring_(char*buf, unsigned int prot);

PS DLOG() is printf() to the Android log. FIRST_UNUSED_BIT() is defined here.

PPS It may not be a good idea to call alloca() in a loop -- the memory may be not freed until the function returns.

Getting Access Denied when calling the PutObject operation with bucket-level permission

Error : An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

I solved the issue by passing Extra Args parameter as PutObjectAcl is disabled by company policy.

s3_client.upload_file('./local_file.csv', 'bucket-name', 'path', ExtraArgs={'ServerSideEncryption': 'AES256'})

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Just used the Nathan's solution and it works fine. I needed to convert ISO-8859-1 to Unicode:

string isocontent = Encoding.GetEncoding("ISO-8859-1").GetString(fileContent, 0, fileContent.Length);
byte[] isobytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(isocontent);
byte[] ubytes = Encoding.Convert(Encoding.GetEncoding("ISO-8859-1"), Encoding.Unicode, isobytes);
return Encoding.Unicode.GetString(ubytes, 0, ubytes.Length);

How to ignore parent css style

This got bumped to the top because of an edit ... The answers have gotten a bit stale, and not as useful today as another solution has been added to the standard.

There is now an "all" shorthand property.

#elementId select.funTimes {
   all: initial;
}

This sets all css properties to their initial value ... note some of the initial values are inherit; Resulting in some formatting still taking place on the element.

Because of that pause required when reading the code or reviewing it in the future, don't use it unless you most as the review process is a point where errors/bugs can be made! when editing the page. But clearly if there are a large number of properties that need to be reset, then "all" is the way to go.

Standard is online here: https://drafts.csswg.org/css-cascade/#all-shorthand

How to reverse MD5 to get the original string?

No, that's not really possible, as

  • there can be more than one string giving the same MD5
  • it was designed to be hard to "reverse"

The goal of the MD5 and its family of hashing functions is

  • to get short "extracts" from long string
  • to make it hard to guess where they come from
  • to make it hard to find collisions, that is other words having the same hash (which is a very similar exigence as the second one)

Think that you can get the MD5 of any string, even very long. And the MD5 is only 16 bytes long (32 if you write it in hexa to store or distribute it more easily). If you could reverse them, you'd have a magical compacting scheme.

This being said, as there aren't so many short strings (passwords...) used in the world, you can test them from a dictionary (that's called "brute force attack") or even google for your MD5. If the word is common and wasn't salted, you have a reasonable chance to succeed...

How to decode encrypted wordpress admin password?

just edit wp_user table with your phpmyadmin, and choose MD5 on Function field then input your new password, save it (go button). enter image description here

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

Example 1:

This is how the and operator works.

x and y => if x is false, then x, else y

So in other words, since mylist1 is not False, the result of the expression is mylist2. (Only empty lists evaluate to False.)

Example 2:

The & operator is for a bitwise and, as you mention. Bitwise operations only work on numbers. The result of a & b is a number composed of 1s in bits that are 1 in both a and b. For example:

>>> 3 & 1
1

It's easier to see what's happening using a binary literal (same numbers as above):

>>> 0b0011 & 0b0001
0b0001

Bitwise operations are similar in concept to boolean (truth) operations, but they work only on bits.

So, given a couple statements about my car

  1. My car is red
  2. My car has wheels

The logical "and" of these two statements is:

(is my car red?) and (does car have wheels?) => logical true of false value

Both of which are true, for my car at least. So the value of the statement as a whole is logically true.

The bitwise "and" of these two statements is a little more nebulous:

(the numeric value of the statement 'my car is red') & (the numeric value of the statement 'my car has wheels') => number

If python knows how to convert the statements to numeric values, then it will do so and compute the bitwise-and of the two values. This may lead you to believe that & is interchangeable with and, but as with the above example they are different things. Also, for the objects that can't be converted, you'll just get a TypeError.

Example 3 and 4:

Numpy implements arithmetic operations for arrays:

Arithmetic and comparison operations on ndarrays are defined as element-wise operations, and generally yield ndarray objects as results.

But does not implement logical operations for arrays, because you can't overload logical operators in python. That's why example three doesn't work, but example four does.

So to answer your and vs & question: Use and.

The bitwise operations are used for examining the structure of a number (which bits are set, which bits aren't set). This kind of information is mostly used in low-level operating system interfaces (unix permission bits, for example). Most python programs won't need to know that.

The logical operations (and, or, not), however, are used all the time.

Upload files from Java client to a HTTP server

click link get example file upload clint java with apache HttpComponents

http://hc.apache.org/httpcomponents-client-ga/httpmime/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java

and library downalod link

https://hc.apache.org/downloads.cgi

use 4.5.3.zip it's working fine in my code

and my working code..

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class ClientMultipartFormPost {

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

          CloseableHttpClient httpclient = HttpClients.createDefault();
          try {
             HttpPost httppost = new HttpPost("http://localhost:8080/MyWebSite1/UploadDownloadFileServlet");

             FileBody bin = new FileBody(new File("E:\\meter.jpg"));
             StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

             HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("bin", bin)
                .addPart("comment", comment)
                .build();


             httppost.setEntity(reqEntity);

             System.out.println("executing request " + httppost.getRequestLine());
             CloseableHttpResponse response = httpclient.execute(httppost);
           try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                     System.out.println("Response content length: " +    resEntity.getContentLength());
                }
              EntityUtils.consume(resEntity);
             } finally {
                 response.close();
            }
       } finally {
          httpclient.close();
      }
   }

}

How to check if an user is logged in Symfony2 inside a controller?

If you are using security annotation from the SensioFrameworkExtraBundle, you can use a few expressions (that are defined in \Symfony\Component\Security\Core\Authorization\ExpressionLanguageProvider):

  • @Security("is_authenticated()"): to check that the user is authed and not anonymous
  • @Security("is_anonymous()"): to check if the current user is the anonymous user
  • @Security("is_fully_authenticated()"): equivalent to is_granted('IS_AUTHENTICATED_FULLY')
  • @Security("is_remember_me()"): equivalent to is_granted('IS_AUTHENTICATED_REMEMBERED')

Convert a positive number to negative in C#

How about

myInt = myInt * -1

Hiding elements in responsive layout?

I have a couple of clarifications to add here:

1) The list shown (visible-phone, visible-tablet, etc.) is deprecated in Bootstrap 3. The new values are:

  • visible-xs-*
  • visible-sm-*
  • visible-md-*
  • visible-lg-*
  • hidden-xs-*
  • hidden-sm-*
  • hidden-md-*
  • hidden-lg-*

The asterisk translates to the following for each (I show only visible-xs-* below):

  • visible-xs-block
  • visible-xs-inline
  • visible-xs-inline-block

2) When you use these classes, you don't add a period in front (as confusingly shown in part of the answer above).

For example:

<div class="visible-md-block col-md-6 text-right text-muted">
   <h5>Copyright &copy; 2014 Jazimov</h5>
</div>

3) You can use visible-* and hidden-* (for example, visible-xs and hidden-xs) but these have been deprecated in Bootstrap 3.2.0.

For more details and the latest specs, go here and search for "visible": http://getbootstrap.com/css/

pandas: find percentile stats of a given column

You can even give multiple columns with null values and get multiple quantile values (I use 95 percentile for outlier treatment)

my_df[['field_A','field_B']].dropna().quantile([0.0, .5, .90, .95])

Get The Current Domain Name With Javascript (Not the path, etc.)

If you are only interested in the domain name and want to ignore the subdomain then you need to parse it out of host and hostname.

The following code does this:

var firstDot = window.location.hostname.indexOf('.');
var tld = ".net";
var isSubdomain = firstDot < window.location.hostname.indexOf(tld);
var domain;

if (isSubdomain) {
    domain = window.location.hostname.substring(firstDot == -1 ? 0 : firstDot + 1);
}
else {
  domain = window.location.hostname;
}

http://jsfiddle.net/5U366/4/

What is the equivalent of the C# 'var' keyword in Java?

I know this is older but why not create a var class and create constructors with different types and depending on what constructors gets invoked you get var with different type. You could even build in methods to convert one type to another.

Turn off display errors using file "php.ini"

I usually use PHP's built in error handlers that can handle every possible error outside of syntax and still render a nice 'Down for maintenance' page otherwise:

Format PHP error on production server

Grant execute permission for a user on all stored procedures in database?

This is a solution that means that as you add new stored procedures to the schema, users can execute them without having to call grant execute on the new stored procedure:

IF  EXISTS (SELECT * FROM sys.database_principals WHERE name = N'asp_net')
DROP USER asp_net
GO

IF  EXISTS (SELECT * FROM sys.database_principals 
WHERE name = N'db_execproc' AND type = 'R')
DROP ROLE [db_execproc]
GO

--Create a database role....
CREATE ROLE [db_execproc] AUTHORIZATION [dbo]
GO

--...with EXECUTE permission at the schema level...
GRANT EXECUTE ON SCHEMA::dbo TO db_execproc;
GO

--http://www.patrickkeisler.com/2012/10/grant-execute-permission-on-all-stored.html
--Any stored procedures that are created in the dbo schema can be 
--executed by users who are members of the db_execproc database role

--...add a user e.g. for the NETWORK SERVICE login that asp.net uses
CREATE USER asp_net 
FOR LOGIN [NT AUTHORITY\NETWORK SERVICE] 
WITH DEFAULT_SCHEMA=[dbo]
GO

--...and add them to the roles you need
EXEC sp_addrolemember N'db_execproc', 'asp_net';
EXEC sp_addrolemember N'db_datareader', 'asp_net';
EXEC sp_addrolemember N'db_datawriter', 'asp_net';
GO

Reference: Grant Execute Permission on All Stored Procedures

HashMap and int as key

For somebody who is interested in a such map because you want to reduce footprint of autoboxing in Java of wrappers over primitives types, I would recommend to use Eclipse collections. Trove isn't supported any more, and I believe it is quite unreliable library in this sense (though it is quite popular anyway) and couldn't be compared with Eclipse collections.

import org.eclipse.collections.impl.map.mutable.primitive.IntObjectHashMap;

public class Check {
    public static void main(String[] args) {
        IntObjectHashMap map = new IntObjectHashMap();

        map.put(5,"It works");
        map.put(6,"without");
        map.put(7,"boxing!");

        System.out.println(map.get(5));
        System.out.println(map.get(6));
        System.out.println(map.get(7));
    }
}

In this example above IntObjectHashMap.

As you need int->object mapping, also consider usage of YourObjectType[] array or List<YourObjectType> and access values by index, as map is, by nature, an associative array with int type as index.

Path.Combine for URLs?

Path.Combine("Http://MyUrl.com/", "/Images/Image.jpg").Replace("\\", "/")

replacing NA's with 0's in R dataframe

Here are two quickie approaches I know of:

In base

AQ1 <- airquality
AQ1[is.na(AQ1 <- airquality)] <- 0
AQ1

Not in base

library(qdap)
NAer(airquality)

PS P.S. Does my command above create a new dataframe called AQ1?

Look at AQ1 and see

Change Select List Option background colour on hover in html

No, it's not possible.

It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".

What techniques can be used to speed up C++ compilation times?

Where are you spending your time? Are you CPU bound? Memory bound? Disk bound? Can you use more cores? More RAM? Do you need RAID? Do you simply want to improve the efficiency of your current system?

Under gcc/g++, have you looked at ccache? It can be helpful if you are doing make clean; make a lot.

Trying to start a service on boot on Android

This is what I did

1. I made the Receiver class

public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //whatever you want to do on boot
       Intent serviceIntent = new Intent(context, YourService.class);
       context.startService(serviceIntent);
    }
}

2.in the manifest

<manifest...>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <application...>
        <receiver android:name=".BootReceiver" android:enabled="true" android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    ...

3.and after ALL you NEED to "set" the receiver in your MainActivity, it may be inside the onCreate

...
 final ComponentName onBootReceiver = new ComponentName(getApplication().getPackageName(), BootReceiver.class.getName());
        if(getPackageManager().getComponentEnabledSetting(onBootReceiver) != PackageManager.COMPONENT_ENABLED_STATE_ENABLED)
        getPackageManager().setComponentEnabledSetting(onBootReceiver,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);
...

the final steap I have learned from ApiDemos

How to close an iframe within iframe itself

None of this solution worked for me since I'm in a cross-domain scenario creating a bookmarklet like Pinterest's Pin It.

I've found a bookmarklet template on GitHub https://gist.github.com/kn0ll/1020251 that solved the problem of closing the Iframe sending the command from within it.

Since I can't access any element from parent window within the IFrame, this communication can only be made posting events between the two windows using window.postMessage

All these steps are on the GitHub link:

1- You have to inject a JS file on the parent page.

2- In this file injected on the parent, add a window event listner

    window.addEventListener('message', function(e) {
       var someIframe = window.parent.document.getElementById('iframeid');
       someIframe.parentNode.removeChild(window.parent.document.getElementById('iframeid'));
    });

This listener will handle the close and any other event you wish

3- Inside the Iframe page you send the close command via postMessage:

   $(this).trigger('post-message', [{
                    event: 'unload-bookmarklet'
                }]);

Follow the template on https://gist.github.com/kn0ll/1020251 and you'll be fine!

Hope it helps,

Laravel Eloquent "WHERE NOT IN"

Its simply means that you have an array of values and you want record except that values/records.

you can simply pass a array into whereNotIn() laravel function.

With query builder

$users = DB::table('applications')
                    ->whereNotIn('id', [1,3,5]) 
                    ->get(); //will return without applications which contain this id's

With eloquent.

$result = ModelClassName::select('your_column_name')->whereNotIn('your_column_name', ['satatus1', 'satatus2']); //return without application which contain this status.

Determine distance from the top of a div to top of window with javascript

I used this:

                              myElement = document.getElemenById("xyz");
Get_Offset_From_Start       ( myElement );  // returns positions from website's start position
Get_Offset_From_CurrentView ( myElement );  // returns positions from current scrolled view's TOP and LEFT

code:

function Get_Offset_From_Start (object, offset) { 
    offset = offset || {x : 0, y : 0};
    offset.x += object.offsetLeft;       offset.y += object.offsetTop;
    if(object.offsetParent) {
        offset = Get_Offset_From_Start (object.offsetParent, offset);
    }
    return offset;
}

function Get_Offset_From_CurrentView (myElement) {
    if (!myElement) return;
    var offset = Get_Offset_From_Start (myElement);
    var scrolled = GetScrolled (myElement.parentNode);
    var posX = offset.x - scrolled.x;   var posY = offset.y - scrolled.y;
    return {lefttt: posX , toppp: posY };
}
//helper
function GetScrolled (object, scrolled) {
    scrolled = scrolled || {x : 0, y : 0};
    scrolled.x += object.scrollLeft;    scrolled.y += object.scrollTop;
    if (object.tagName.toLowerCase () != "html" && object.parentNode) { scrolled=GetScrolled (object.parentNode, scrolled); }
    return scrolled;
}

    /*
    // live monitoring
    window.addEventListener('scroll', function (evt) {
        var Positionsss =  Get_Offset_From_CurrentView(myElement);  
        console.log(Positionsss);
    });
    */

How to break out from a ruby block?

To break out from a ruby block simply use return keyword return if value.nil?

Xcode 10, Command CodeSign failed with a nonzero exit code

This happened to me just today, only after I added a .png image with 'hide extension' ticked in the get info. (Right click image) Ths image was added to the file directory of my Xcode project.

When unticked box and re-adding the the .png image to directory of Xcode, I then Cleaned and Built and worked fine after that, a very strange bug if you ask me.

How to declare array of zeros in python (or an array of a certain size)

Use this:

bucket = [None] * 100
for i in range(100):
    bucket[i] = [None] * 100

OR

w, h = 100, 100
bucket = [[None] * w for i in range(h)]

Both of them will output proper empty multidimensional bucket list 100x100

Get a resource using getResource()

if you are calling from static method, use :

TestGameTable.class.getClassLoader().getResource("dice.jpg");

AttributeError: 'str' object has no attribute 'append'

If you want to append a value to myList, use myList.append(s).

Strings are immutable -- you can't append to them.

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

Use below code to provide different color to actionbar text and actionbar background just use below theme in manifest against the activity in which you want output :)

<style name="MyTheme" parent="@android:style/Theme.Holo.Light">
    <item name="android:actionBarStyle">@style/MyActionBar</item>
</style>

<style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:titleTextStyle">@style/TitleBarTextColor</item>
    <item name="android:background">YOUR_COLOR_CODE</item>
</style>

<style name="TitleBarTextColor" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:textColor">YOUR_COLOR_CODE</item>
</style>

Error - replacement has [x] rows, data has [y]

TL;DR ...and late to the party, but that short explanation might help future googlers..

In general that error message means that the replacement doesn't fit into the corresponding column of the dataframe.

A minimal example:

df <- data.frame(a = 1:2); df$a <- 1:3

throws the error

Error in $<-.data.frame(*tmp*, a, value = 1:3) : replacement has 3 rows, data has 2

which is clear, because the vector a of df has 2 entries (rows) whilst the vector we try to replace it has 3 entries (rows).

Multiple try codes in one block

Lets say each code is a function and its already written then the following can be used to iter through your coding list and exit the for-loop when a function is executed without error using the "break".

def a(): code a
def b(): code b
def c(): code c
def d(): code d

for func in [a, b, c, d]:  # change list order to change execution order.
   try:
       func()
       break
   except Exception as err:
       print (err)
       continue

I used "Exception " here so you can see any error printed. Turn-off the print if you know what to expect and you're not caring (e.g. in case the code returns two or three list items (i,j = msg.split('.')).

SQL Insert Multiple Rows

Wrap each row of values to be inserted in brackets/parenthesis (value1, value2, value3) and separate the brackets/parenthesis by comma for as many as you wish to insert into the table.

INSERT INTO example
VALUES
  (100, 'Name 1', 'Value 1', 'Other 1'),
  (101, 'Name 2', 'Value 2', 'Other 2'),
  (102, 'Name 3', 'Value 3', 'Other 3'),
  (103, 'Name 4', 'Value 4', 'Other 4');