Programs & Examples On #Prefixes

CSS Grid Layout not working in IE11 even with prefixes

Michael has given a very comprehensive answer, but I'd like to point out a few things which you can still do to be able to use grids in IE in a nearly painless way.

The repeat functionality is supported

You can still use the repeat functionality, it's just hiding behind a different syntax. Instead of writing repeat(4, 1fr), you have to write (1fr)[4]. That's it. See this series of articles for the current state of affairs: https://css-tricks.com/css-grid-in-ie-debunking-common-ie-grid-misconceptions/

Supporting grid-gap

Grid gaps are supported in all browsers except IE. So you can use the @supports at-rule to set the grid-gaps conditionally for all new browsers:

Example:

.grid {
  display: grid;
}
.item {
  margin-right: 1rem;
  margin-bottom: 1rem;
}
@supports (grid-gap: 1rem) {
  .grid {
    grid-gap: 1rem;
  }
  .item {
    margin-right: 0;
    margin-bottom: 0;
  }
}

It's a little verbose, but on the plus side, you don't have to give up grids altogether just to support IE.

Use Autoprefixer

I can't stress this enough - half the pain of grids is solved just be using autoprefixer in your build step. Write your CSS in a standards-complaint way, and just let autoprefixer do it's job transforming all older spec properties automatically. When you decide you don't want to support IE, just change one line in the browserlist config and you'll have removed all IE-specific code from your built files.

What does /p mean in set /p?

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

Two ways I've used it... first:

SET /P variable=

When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.

And second:

SET /P variable=<%temp%\filename.txt

Will set variable to contents (the first line) of the txt file. This method won't work unless the /P is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.

How to execute XPath one-liners from shell?

One package that is very likely to be installed on a system already is python-lxml. If so, this is possible without installing any extra package:

python -c "from lxml.etree import parse; from sys import stdin; print('\n'.join(parse(stdin).xpath('//element/@attribute')))"

jQuery click events not working in iOS

There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.

While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html

I've found this the easy fix, simply add this to the css:

cursor: pointer;

Launch Minecraft from command line - username and password as prefix

Those are all ways to start the standard minecraft launcher with those credentials in the text boxes.

There used to be a way to login to minecraft without the launcher using the command line, but it has since been patched.

If you want to make a custom launcher using the command line then good luck, the only way to login to the minecraft jar(IE: the way the launcher does it) is to send a post request to https://login.minecraft.net/ with the username,password,launcher version, and a RSA key. It then parses the pseudo Json, and uses the session token from that to authenticate the jar from the command line with a load of arguments.

If you are trying to make a minecraft launcher and you have no knowledge of java,http requests or json then you have no chance.

Swift

Python: importing a sub-package or sub-module

If all you're trying to do is to get attribute1 in your global namespace, version 3 seems just fine. Why is it overkill prefix ?

In version 2, instead of

from module import attribute1

you can do

attribute1 = module.attribute1

Export table data from one SQL Server to another

If you don't have permission to link servers, here are the steps to import a table from one server to another using Sql Server Import/Export Wizard:

  • Right click on the source database you want to copy from.
  • Select Tasks - Export Data.
  • Select Sql Server Native Client in the data source.
  • Select your authentication type (Sql Server or Windows authentication).
  • Select the source database.
  • Next, choose the Destination: Sql Server Native Client
  • Type in your Server Name (the server you want to copy the table to).
  • Select your authentication type (Sql Server or Windows authentication).
  • Select the destination database.
  • Select Copy data.
  • Select your table from the list.
  • Hit Next, Select Run immediately, or optionally, you can also save the package to a file or Sql Server if you want to run it later.
  • Finish

How to check if a string starts with one of several prefixes?

A simple solution is:

if (newStr4.startsWith("Mon") || newStr4.startsWith("Tue") || newStr4.startsWith("Wed"))
// ... you get the idea ...

A fancier solution would be:

List<String> days = Arrays.asList("SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT");
String day = newStr4.substring(0, 3).toUpperCase();
if (days.contains(day)) {
    // ...
}

CSS transition shorthand with multiple properties?

Syntax:

transition: <property> || <duration> || <timing-function> || <delay> [, ...];

Note that the duration must come before the delay, if the latter is specified.

Individual transitions combined in shorthand declarations:

-webkit-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-moz-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-o-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;

Or just transition them all:

-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;

Here is a straightforward example. Here is another one with the delay property.


Edit: previously listed here were the compatibilities and known issues regarding transition. Removed for readability.

Bottom-line: just use it. The nature of this property is non-breaking for all applications and compatibility is now well above 94% globally.

If you still want to be sure, refer to http://caniuse.com/css-transitions

Origin null is not allowed by Access-Control-Allow-Origin

I would like to humbly add that according to this SO source: https://stackoverflow.com/a/14671362/1743693, this kind of trouble is now partially solved simply by using the following jQuery instruction:

<script> 
    $.support.cors = true;
</script>

I tried it on IE10.0.9200, and it worked immediately (using jquery-1.9.0.js).

On chrome 28.0.1500.95 - this instruction doesn't work (this happens all over as david complains in the comments at the link above)

Running chrome with --allow-file-access-from-files did not work for me (as Maistora's claims above)

Generate an integer that is not among four billion given ones

You can use bit flags to mark whether an integer is present or not.

After traversing the entire file, scan each bit to determine if the number exists or not.

Assuming each integer is 32 bit, they will conveniently fit in 1 GB of RAM if bit flagging is done.

HttpListener Access Denied

As an alternative that doesn't require elevation or netsh you could also use TcpListener for instance.

The following is a modified excerpt of this sample: https://github.com/googlesamples/oauth-apps-for-windows/tree/master/OAuthDesktopApp

// Generates state and PKCE values.
string state = randomDataBase64url(32);
string code_verifier = randomDataBase64url(32);
string code_challenge = base64urlencodeNoPadding(sha256(code_verifier));
const string code_challenge_method = "S256";

// Creates a redirect URI using an available port on the loopback address.
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
string redirectURI = string.Format("http://{0}:{1}/", IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);
output("redirect URI: " + redirectURI);

// Creates the OAuth 2.0 authorization request.
string authorizationRequest = string.Format("{0}?response_type=code&scope=openid%20profile&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}",
    authorizationEndpoint,
    System.Uri.EscapeDataString(redirectURI),
    clientID,
    state,
    code_challenge,
    code_challenge_method);

// Opens request in the browser.
System.Diagnostics.Process.Start(authorizationRequest);

// Waits for the OAuth authorization response.
var client = await listener.AcceptTcpClientAsync();

// Read response.
var response = ReadString(client);

// Brings this app back to the foreground.
this.Activate();

// Sends an HTTP response to the browser.
WriteStringAsync(client, "<html><head><meta http-equiv='refresh' content='10;url=https://google.com'></head><body>Please close this window and return to the app.</body></html>").ContinueWith(t =>
{
    client.Dispose();
    listener.Stop();

    Console.WriteLine("HTTP server stopped.");
});

// TODO: Check the response here to get the authorization code and verify the code challenge

The read and write methods being:

private string ReadString(TcpClient client)
{
    var readBuffer = new byte[client.ReceiveBufferSize];
    string fullServerReply = null;

    using (var inStream = new MemoryStream())
    {
        var stream = client.GetStream();

        while (stream.DataAvailable)
        {
            var numberOfBytesRead = stream.Read(readBuffer, 0, readBuffer.Length);
            if (numberOfBytesRead <= 0)
                break;

            inStream.Write(readBuffer, 0, numberOfBytesRead);
        }

        fullServerReply = Encoding.UTF8.GetString(inStream.ToArray());
    }

    return fullServerReply;
}

private Task WriteStringAsync(TcpClient client, string str)
{
    return Task.Run(() =>
    {
        using (var writer = new StreamWriter(client.GetStream(), new UTF8Encoding(false)))
        {
            writer.Write("HTTP/1.0 200 OK");
            writer.Write(Environment.NewLine);
            writer.Write("Content-Type: text/html; charset=UTF-8");
            writer.Write(Environment.NewLine);
            writer.Write("Content-Length: " + str.Length);
            writer.Write(Environment.NewLine);
            writer.Write(Environment.NewLine);
            writer.Write(str);
        }
    });
}

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

First, this is not an error. The 3xx denotes a redirection. The real errors are 4xx (client error) and 5xx (server error).

If a client gets a 304 Not Modified, then it's the client's responsibility to display the resouce in question from its own cache. In general, the proxy shouldn't worry about this. It's just the messenger.

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

We could do without any xxxFactory, xxxManager or xxxRepository classes if we modeled the real world correctly:

Universe.Instance.Galaxies["Milky Way"].SolarSystems["Sol"]
        .Planets["Earth"].Inhabitants.OfType<Human>().WorkingFor["Initech, USA"]
        .OfType<User>().CreateNew("John Doe");

;-)

Why use prefixes on member variables in C++ classes

I like variable names to give only a meaning to the values they contain, and leave how they are declared/implemented out of the name. I want to know what the value means, period. Maybe I've done more than an average amount of refactoring, but I find that embedding how something is implemented in the name makes refactoring more tedious than it needs to be. Prefixes indicating where or how object members are declared are implementation specific.

color = Red;

Most of the time, I don't care if Red is an enum, a struct, or whatever, and if the function is so large that I can't remember if color was declared locally or is a member, it's probably time to break the function into smaller logical units.

If your cyclomatic complexity is so great that you can't keep track of what is going on in the code without implementation-specific clues embedded in the names of things, most likely you need to reduce the complexity of your function/method.

Mostly, I only use 'this' in constructors and initializers.

SQL: parse the first, middle and last name from a fullname field

I would do this as an iterative process.

1) Dump the table to a flat file to work with.

2) Write a simple program to break up your Names using a space as separator where firsts token is the first name, if there are 3 token then token 2 is middle name and token 3 is last name. If there are 2 tokens then the second token is the last name. (Perl, Java, or C/C++, language doesn't matter)

3) Eyeball the results. Look for names that don't fit this rule.

4) Using that example, create a new rule to handle that exception...

5) Rinse and Repeat

Eventually you will get a program that fixes all your data.

How do you add an image?

In order to add attributes, XSL wants

<xsl:element name="img">
     (attributes)
</xsl:element>

instead of just

<img>
     (attributes)
</img>

Although, yes, if you're just copying the element as-is, you don't need any of that.

How can I initialize C++ object member variables in the constructor?

Regarding the first (and great) answer from chris who proposed a solution to the situation where the class members are held as a "true composite" members (i.e.- not as pointers nor references):

The note is a bit large, so I will demonstrate it here with some sample code.

When you chose to hold the members as I mentioned, you have to keep in mind also these two things:

  1. For every "composed object" that does not have a default constructor - you must initialize it in the initialization list of all the constructor's of the "father" class (i.e.- BigMommaClass or MyClass in the original examples and MyClass in the code below), in case there are several (see InnerClass1 in the example below). Meaning, you can "comment out" the m_innerClass1(a) and m_innerClass1(15) only if you enable the InnerClass1 default constructor.

  2. For every "composed object" that does have a default constructor - you may initialize it within the initialization list, but it will work also if you chose not to (see InnerClass2 in the example below).

See sample code (compiled under Ubuntu 18.04 (Bionic Beaver) with g++ version 7.3.0):

#include <iostream>

using namespace std;

class InnerClass1
{
    public:
        InnerClass1(int a) : m_a(a)
        {
            cout << "InnerClass1::InnerClass1 - set m_a:" << m_a << endl;
        }

        /* No default constructor
        InnerClass1() : m_a(15)
        {
            cout << "InnerClass1::InnerClass1() - set m_a:" << m_a << endl;
        }
        */

        ~InnerClass1()
        {
            cout << "InnerClass1::~InnerClass1" << endl;
        }

    private:
        int m_a;
};

class InnerClass2
{
    public:
        InnerClass2(int a) : m_a(a)
        {
            cout << "InnerClass2::InnerClass2 - set m_a:" << m_a << endl;
        }

        InnerClass2() : m_a(15)
        {
            cout << "InnerClass2::InnerClass2() - set m_a:" << m_a << endl;
        }

        ~InnerClass2()
        {
            cout << "InnerClass2::~InnerClass2" << endl;
        }

    private:
        int m_a;
};

class MyClass
{
    public:
        MyClass(int a, int b) : m_innerClass1(a), /* m_innerClass2(a),*/ m_b(b)
        {
            cout << "MyClass::MyClass(int b) - set m_b to:" << m_b << endl;
        }

         MyClass() : m_innerClass1(15), /*m_innerClass2(15),*/ m_b(17)
        {
            cout << "MyClass::MyClass() - m_b:" << m_b << endl;
        }

        ~MyClass()
        {
            cout << "MyClass::~MyClass" << endl;
        }

    private:
        InnerClass1 m_innerClass1;
        InnerClass2 m_innerClass2;
        int m_b;
};

int main(int argc, char** argv)
{
    cout << "main - start" << endl;

    MyClass obj;

    cout << "main - end" << endl;
    return 0;
}

Int or Number DataType for DataAnnotation validation attribute

Try this attribute :

public class NumericAttribute : ValidationAttribute, IClientValidatable {

    public override bool IsValid(object value) {
        return value.ToString().All(c => (c >= '0' && c <= '9') || c == '-' || c == ' ');
    }


    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.DisplayName),
            ValidationType = "numeric"
        };
        yield return rule;
    }
}

And also you must register the attribute in the validator plugin:

if($.validator){
     $.validator.unobtrusive.adapters.add(
        'numeric', [], function (options) {
            options.rules['numeric'] = options.params;
            options.messages['numeric'] = options.message;
        }
    );
}

Eclipse change project files location

I moved my default git repository folder and therefore had the same problem. I wrote my own Class to manage eclipse location and used it to change the location file.

        File locationfile 
            = new File("<workspace>"
                    +"/.metadata/.plugins/org.eclipse.core.resources/.projects/"
                    +"<project>/"
                    +".location");

        byte data[] = Files.readAllBytes(locationfile.toPath());

        EclipseLocation eclipseLocation = new EclipseLocation(data);

        eclipseLocation.changeUri("<new path to project>");

        byte newData[] = eclipseLocation.getData();

        Files.write(locationfile.toPath(),newData);

Here my EclipseLocation Class:

public class EclipseLocation {

    private byte[] data;
    private int length;
    private String uri;


    public EclipseLocation(byte[] data) {
        init(data);
    }

    public String getUri() {
        return uri;
    }

    public byte[] getData() {
        return data;
    }


    private void init(byte[] data) {

        this.data = data;   
        this.length = (data[16] * 256) + data[17];
        this.uri = new String(data,18,length);  
    }


    public void changeUri(String newUri) {

        int newLength = newUri.length();
        byte[] newdata = new byte[data.length + newLength - length];        


        int y = 0;
        int x = 0;

        //header
        while(y < 16) newdata[y++] = data[x++];

        //length
        newdata[16] = (byte) (newLength / 256);
        newdata[17] = (byte) (newLength % 256);

        y += 2;
        x += 2;

        //Uri
        for(int i = 0;i < newLength;i++)
        {
            newdata[y++] = (byte) newUri.charAt(i);
        }
        x += length;

        //footer
        while(y < newdata.length) newdata[y++] = data[x++];

        if(y != newdata.length)
            throw new IndexOutOfBoundsException();

        if(x != data.length)
            throw new IndexOutOfBoundsException();

        init(newdata);
    }


}

Make div stay at bottom of page's content all the time even when there are scrollbars

if you have a fixed height footer (for example 712px) you can do this with js like so:

var bgTop = 0;
window.addEventListener("resize",theResize);
function theResize(){
    bgTop = winHeight - 712;
    document.getElementById("bg").style.marginTop = bgTop+"px";
}

Errors: Data path ".builders['app-shell']" should have required property 'class'

I was also coming across this issue and for me when doing more updates more issues occurred.

What worked for me in the end was more or less to remove angular cli and re install it with these steps:

npm uninstall -g @angular/cli
npm cache clean --force
npm install -g @angular/cli

this helped me out source: how to uninstall angular/cli

span with onclick event inside a tag

<a href="http://the.url.com/page.html">
    <span onclick="hide(); return false">Hide me</span>
</a>

This is the easiest solution.

How do I UPDATE from a SELECT in SQL Server?

For the record (and others searching like I was), you can do it in MySQL like this:

UPDATE first_table, second_table
SET first_table.color = second_table.color
WHERE first_table.id = second_table.foreign_id

Spring Data JPA Update @Query not updating?

I finally understood what was going on.

When creating an integration test on a statement saving an object, it is recommended to flush the entity manager so as to avoid any false negative, that is, to avoid a test running fine but whose operation would fail when run in production. Indeed, the test may run fine simply because the first level cache is not flushed and no writing hits the database. To avoid this false negative integration test use an explicit flush in the test body. Note that the production code should never need to use any explicit flush as it is the role of the ORM to decide when to flush.

When creating an integration test on an update statement, it may be necessary to clear the entity manager so as to reload the first level cache. Indeed, an update statement completely bypasses the first level cache and writes directly to the database. The first level cache is then out of sync and reflects the old value of the updated object. To avoid this stale state of the object, use an explicit clear in the test body. Note that the production code should never need to use any explicit clear as it is the role of the ORM to decide when to clear.

My test now works just fine.

Creating and Naming Worksheet in Excel VBA

Are you committing the cell before pressing the button (pressing Enter)? The contents of the cell must be stored before it can be used to name a sheet.

A better way to do this is to pop up a dialog box and get the name you wish to use.

How to check if a table exists in a given schema

Perhaps use information_schema:

SELECT EXISTS(
    SELECT * 
    FROM information_schema.tables 
    WHERE 
      table_schema = 'company3' AND 
      table_name = 'tableincompany3schema'
);

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

Add ... if string is too long PHP

This will return a given string with ellipsis based on WORD count instead of characters:

<?php
/**
*    Return an elipsis given a string and a number of words
*/
function elipsis ($text, $words = 30) {
    // Check if string has more than X words
    if (str_word_count($text) > $words) {

        // Extract first X words from string
        preg_match("/(?:[^\s,\.;\?\!]+(?:[\s,\.;\?\!]+|$)){0,$words}/", $text, $matches);
        $text = trim($matches[0]);

        // Let's check if it ends in a comma or a dot.
        if (substr($text, -1) == ',') {
            // If it's a comma, let's remove it and add a ellipsis
            $text = rtrim($text, ',');
            $text .= '...';
        } else if (substr($text, -1) == '.') {
            // If it's a dot, let's remove it and add a ellipsis (optional)
            $text = rtrim($text, '.');
            $text .= '...';
        } else {
            // Doesn't end in dot or comma, just adding ellipsis here
            $text .= '...';
        }
    }
    // Returns "ellipsed" text, or just the string, if it's less than X words wide.
    return $text;
}

$description = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quibusdam ut placeat consequuntur pariatur iure eum ducimus quasi perferendis, laborum obcaecati iusto ullam expedita excepturi debitis nisi deserunt fugiat velit assumenda. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, blanditiis nostrum. Nostrum cumque non rerum ducimus voluptas officia tempore modi, nulla nisi illum, voluptates dolor sapiente ut iusto earum. Esse? Lorem ipsum dolor sit amet, consectetur adipisicing elit. A eligendi perspiciatis natus autem. Necessitatibus eligendi doloribus corporis quia, quas laboriosam. Beatae repellat dolor alias. Perferendis, distinctio, laudantium? Dolorum, veniam, amet!';

echo elipsis($description, 30);
?>

HTML: Image won't display?

Just to expand niko's answer:

You can reference any image via its URL. No matter where it is, as long as it's accesible you can use it as the src. Example:

Relative location:

<img src="images/image.png">

The image is sought relative to the document's location. If your document is at http://example.com/site/document.html, then your images folder should be on the same directory where your document.html file is.

Absolute location:

<img src="/site/images/image.png">
<img src="http://example.com/site/images/image.png">

or

<img src="http://another-example.com/images/image.png">

In this case, your image will be sought from the document site's root, so, if your document.html is at http://example.com/site/document.html, the root would be at http://example.com/ (or it's respective directory on the server's filesystem, commonly www/). The first two examples are the same, since both point to the same host, Think of the first / as an alias for your server's root. In the second case, the image is located in another host, so you'd have to specify the complete URL of the image.

Regarding /, . and ..:

The / symbol will always return the root of a filesystem or site.

The single point ./ points to the same directory where you are.

And the double point ../ will point to the upper directory, or the one that contains the actual working directory.

So you can build relative routes using them.

Examples given the route http://example.com/dir/one/two/three/ and your calling document being inside three/:

"./pictures/image.png"

or just

"pictures/image.png"

Will try to find a directory named pictures inside http://example.com/dir/one/two/three/.

"../pictures/image.png"

Will try to find a directory named pictures inside http://example.com/dir/one/two/.

"/pictures/image.png"

Will try to find a directory named pictures directly at / or example.com (which are the same), on the same level as directory.

Date difference in minutes in Python

from datetime import datetime

fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 17:31:22', fmt)

print (d2-d1).days * 24 * 60

MySQL error - #1062 - Duplicate entry ' ' for key 2

Error 'Duplicate entry '338620-7' for key 2' on query. Default database

For this error :

set global sql_slave_skip_counter=1; 
start slave; 
show slave status\G

This worked for me

Get RETURN value from stored procedure in SQL

This should work for you. Infact the one which you are thinking will also work:-

 .......
 DECLARE @returnvalue INT

 EXEC @returnvalue = SP_One
 .....

Preventing form resubmission

Directly, you can't, and that's a good thing. The browser's alert is there for a reason. This thread should answer your question:

Prevent Back button from showing POST confirmation alert

Two key workarounds suggested were the PRG pattern, and an AJAX submit followed by a scripting relocation.

Note that if your method allows for a GET and not a POST submission method, then that would both solve the problem and better fit with convention. Those solutions are provided on the assumption you want/need to POST data.

Rebase feature branch onto another feature branch

I know you asked to Rebase, but I'd Cherry-Pick the commits I wanted to move from Branch2 to Branch1 instead. That way, I wouldn't need to care about when which branch was created from master, and I'd have more control over the merging.

a -- b -- c                  <-- Master
     \     \
      \     d -- e -- f -- g <-- Branch1 (Cherry-Pick f & g)
       \
        f -- g               <-- Branch2

Best cross-browser method to capture CTRL+S with JQuery?

This was my solution, which is much easier to read than other suggestions here, can easily include other key combinations, and has been tested on IE, Chrome, and Firefox:

$(window).keydown(function(evt) {
    var key = String.fromCharCode(evt.keyCode);
    //ctrl+s
    if (key.toLowerCase() === "s" && evt.ctrlKey) {
        fnToRun();
        evt.preventDefault(true);
        return false;
    }
    return true;
});

error: the details of the application error from being viewed remotely

This can be the message you receive even when custom errors is turned off in web.config file. It can mean you have run out of free space on the drive that hosts the application. Clean your log files if you have no other space to gain on the drive.

is there a post render callback for Angular JS directive?

I had the same problem and I believe the answer really is no. See Miško's comment and some discussion in the group.

Angular can track that all of the function calls it makes to manipulate the DOM are complete, but since those functions could trigger async logic that's still updating the DOM after they return, Angular couldn't be expected to know about it. Any callback Angular gives might work sometimes, but wouldn't be safe to rely on.

We solved this heuristically with a setTimeout, as you did.

(Please keep in mind that not everyone agrees with me - you should read the comments on the links above and see what you think.)

Given final block not properly padded

If you try to decrypt PKCS5-padded data with the wrong key, and then unpad it (which is done by the Cipher class automatically), you most likely will get the BadPaddingException (with probably of slightly less than 255/256, around 99.61%), because the padding has a special structure which is validated during unpad and very few keys would produce a valid padding.

So, if you get this exception, catch it and treat it as "wrong key".

This also can happen when you provide a wrong password, which then is used to get the key from a keystore, or which is converted into a key using a key generation function.

Of course, bad padding can also happen if your data is corrupted in transport.

That said, there are some security remarks about your scheme:

  • For password-based encryption, you should use a SecretKeyFactory and PBEKeySpec instead of using a SecureRandom with KeyGenerator. The reason is that the SecureRandom could be a different algorithm on each Java implementation, giving you a different key. The SecretKeyFactory does the key derivation in a defined manner (and a manner which is deemed secure, if you select the right algorithm).

  • Don't use ECB-mode. It encrypts each block independently, which means that identical plain text blocks also give always identical ciphertext blocks.

    Preferably use a secure mode of operation, like CBC (Cipher block chaining) or CTR (Counter). Alternatively, use a mode which also includes authentication, like GCM (Galois-Counter mode) or CCM (Counter with CBC-MAC), see next point.

  • You normally don't want only confidentiality, but also authentication, which makes sure the message is not tampered with. (This also prevents chosen-ciphertext attacks on your cipher, i.e. helps for confidentiality.) So, add a MAC (message authentication code) to your message, or use a cipher mode which includes authentication (see previous point).

  • DES has an effective key size of only 56 bits. This key space is quite small, it can be brute-forced in some hours by a dedicated attacker. If you generate your key by a password, this will get even faster. Also, DES has a block size of only 64 bits, which adds some more weaknesses in chaining modes. Use a modern algorithm like AES instead, which has a block size of 128 bits, and a key size of 128 bits (for the standard variant).

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

My sphinx.conf

source post_source 
{
    type = mysql

    sql_host = localhost
    sql_user = ***
    sql_pass = ***
    sql_db =   ***
    sql_port = 3306

    sql_query_pre = SET NAMES utf8
    # query before fetching rows to index

    sql_query = SELECT *, id AS pid, CRC32(safetag) as safetag_crc32 FROM hb_posts


    sql_attr_uint = pid  
    # pid (as 'sql_attr_uint') is necessary for sphinx
    # this field must be unique

    # that is why I like sphinx
    # you can store custom string fields into indexes (memory) as well
    sql_field_string = title
    sql_field_string = slug
    sql_field_string = content
    sql_field_string = tags

    sql_attr_uint = category
    # integer fields must be defined as sql_attr_uint

    sql_attr_timestamp = date
    # timestamp fields must be defined as sql_attr_timestamp

    sql_query_info_pre = SET NAMES utf8
    # if you need unicode support for sql_field_string, you need to patch the source
    # this param. is not supported natively

    sql_query_info = SELECT * FROM my_posts WHERE id = $id
}

index posts 
{
    source = post_source
    # source above

    path = /var/data/posts
    # index location

    charset_type = utf-8
}

Test script:

<?php

    require "sphinxapi.php";

    $safetag = $_GET["my_post_slug"];
//  $safetag = preg_replace("/[^a-z0-9\-_]/i", "", $safetag);

    $conf = getMyConf();

    $cl = New SphinxClient();

    $cl->SetServer($conf["server"], $conf["port"]);
    $cl->SetConnectTimeout($conf["timeout"]);
    $cl->setMaxQueryTime($conf["max"]);

    # set search params
    $cl->SetMatchMode(SPH_MATCH_FULLSCAN);
    $cl->SetArrayResult(TRUE);

    $cl->setLimits(0, 1, 1); 
    # looking for the post (not searching a keyword)

    $cl->SetFilter("safetag_crc32", array(crc32($safetag)));

    # fetch results
    $post = $cl->Query(null, "post_1");

    echo "<pre>";
    var_dump($post);
    echo "</pre>";
    exit("done");
?>

Sample result:

[array] => 
  "id" => 123,
  "title" => "My post title.",
  "content" => "My <p>post</p> content.",
   ...
   [ and other fields ]

Sphinx query time:

0.001 sec.

Sphinx query time (1k concurrent):

=> 0.346 sec. (average)
=> 0.340 sec. (average of last 10 query)

MySQL query time:

"SELECT * FROM hb_posts WHERE id = 123;"
=> 0.001 sec.

MySQL query time (1k concurrent):

"SELECT * FROM my_posts WHERE id = 123;" 
=> 1.612 sec. (average)
=> 1.920 sec. (average of last 10 query)

Reading settings from app.config or web.config in .NET

Just for completeness, there's another option available for web projects only: System.Web.Configuration.WebConfigurationManager.AppSettings["MySetting"]

The benefit of this is that it doesn't require an extra reference to be added, so it may be preferable for some people.

How to delete rows in tables that contain foreign keys to other tables

From your question, I think it is safe to assume you have CASCADING DELETES turned on.
All that is needed in that case is

DELETE FROM MainTable
WHERE PrimaryKey = ???

You database engine will take care of deleting the corresponding referencing records.

LINQ to SQL - How to select specific columns and return strongly typed list

Basically you are doing it the right way. However, you should use an instance of the DataContext for querying (it's not obvious that DataContext is an instance or the type name from your query):

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new Person { Name = a.Name, Age = a.Age }).ToList();

Apparently, the Person class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:

class PersonInformation {
   public string Name {get;set;}
   public int Age {get;set;}
}

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new PersonInformation { Name = a.Name, Age = a.Age }).ToList();

You can freely swap var with List<PersonInformation> here without affecting anything (as this is what the compiler does).

Otherwise, if you are working locally with the query, I suggest considering an anonymous type:

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new { a.Name, a.Age }).ToList();

Note that in all of these cases, the result is statically typed (it's type is known at compile time). The latter type is a List of a compiler generated anonymous class similar to the PersonInformation class I wrote above. As of C# 3.0, there's no dynamic typing in the language.

UPDATE:

If you really want to return a List<Person> (which might or might not be the best thing to do), you can do this:

var result = from a in new DataContext().Persons
             where a.Age > 18
             select new { a.Name, a.Age };

List<Person> list = result.AsEnumerable()
                          .Select(o => new Person {
                                           Name = o.Name, 
                                           Age = o.Age
                          }).ToList();

You can merge the above statements too, but I separated them for clarity.

How to make a simple rounded button in Storyboard?

The extension is the best option for this problem. Create an extension of View or Button

public extension UIView {
  //Round the corners
  func roundCorners(){
    let radius = bounds.maxX / 16
    layer.cornerRadius = radius
  }
}

Call it from the code

button.roundCorners()

Filter dict to contain only certain keys?

Here's an example in python 2.6:

>>> a = {1:1, 2:2, 3:3}
>>> dict((key,value) for key, value in a.iteritems() if key == 1)
{1: 1}

The filtering part is the if statement.

This method is slower than delnan's answer if you only want to select a few of very many keys.

Abort a git cherry-pick?

Try also with '--quit' option, which allows you to abort the current operation and further clear the sequencer state.

--quit Forget about the current operation in progress. Can be used to clear the sequencer state after a failed cherry-pick or revert.

--abort Cancel the operation and return to the pre-sequence state.

use help to see the original doc with more details, $ git help cherry-pick

I would avoid 'git reset --hard HEAD' that is too harsh and you might ended up doing some manual work.

Java - Best way to print 2D array?

I would prefer generally foreach when I don't need making arithmetic operations with their indices.

for (int[] x : array)
{
   for (int y : x)
   {
        System.out.print(y + " ");
   }
   System.out.println();
}

git diff between two different files

I believe using --no-index is what you're looking for:

git diff [<options>] --no-index [--] <path> <path>

as mentioned in the git manual:

This form is to compare the given two paths on the filesystem. You can omit the --no-index option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree, or when running the command outside a working tree controlled by Git.

Create a simple Login page using eclipse and mysql

use this code it is working

// index.jsp or login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>

</body>
</html>

// authentication servlet class

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class auth extends HttpServlet {
        private static final long serialVersionUID = 1L;

        public auth() {
            super();
        }
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

        }

        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            String username = request.getParameter("username");
            String pass = request.getParameter("pass");

            String sql = "select * from reg where username='" + username + "'";
            Connection conn = null;

            try {
                conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
                        "root", "");
                Statement s = conn.createStatement();

                java.sql.ResultSet rs = s.executeQuery(sql);
                String un = null;
                String pw = null;
                String name = null;

            /* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */   

            PrintWriter prwr1 = response.getWriter();               
            if(!rs.isBeforeFirst()){
                prwr1.write("<h1> No Such User in Database<h1>");
            } else {

/* Conditions to be executed after at least one row is returned by query execution */ 
                while (rs.next()) {
                    un = rs.getString("username");
                    pw = rs.getString("password");
                    name = rs.getString("name");
                }

                PrintWriter pww = response.getWriter();

                if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
                                // use this or create request dispatcher 
                    response.setContentType("text/html");
                    pww.write("<h1>Welcome, " + name + "</h1>");
                } else {
                    pww.write("wrong username or password\n");
                }
              }

            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }

How do I use the Tensorboard callback of Keras?

Change

keras.callbacks.TensorBoard(log_dir='/Graph', histogram_freq=0,  
          write_graph=True, write_images=True)

to

tbCallBack = keras.callbacks.TensorBoard(log_dir='Graph', histogram_freq=0,  
          write_graph=True, write_images=True)

and set your model

tbCallback.set_model(model)

Run in your terminal

tensorboard  --logdir Graph/

jQuery: more than one handler for same event

Both handlers will run, the jQuery event model allows multiple handlers on one element, therefore a later handler does not override an older handler.

The handlers will execute in the order in which they were bound.

How can I check if a program exists from a Bash script?

I second the use of "command -v". E.g. like this:

md=$(command -v mkdirhier) ; alias md=${md:=mkdir}  # bash

emacs="$(command -v emacs) -nw" || emacs=nano
alias e=$emacs
[[ -z $(command -v jed) ]] && alias jed=$emacs

resize2fs: Bad magic number in super-block while trying to open

On centos and fedora work with fsadm

fsadm resize /dev/vg_name/root

How to update ruby on linux (ubuntu)?

Ruby is v2.0 now. Programs like Jekyll (and I am sure many others) require it. I just ran:

sudo apt-get install ruby2.0

check version

ruby --version

Hope that helps

Location of ini/config files in linux/unix?

(1) No (unfortunately). Edit: The other answers are right, per-user configuration is usually stored in dot-files or dot-directories in the users home directory. Anything above user level often is a lot of guesswork.

(2) System-wide ini file -> user ini file -> environment -> command line options (going from lowest to highest precedence)

How to calculate moving average without keeping the count and data-total?

An example using javascript, for comparison:

https://jsfiddle.net/drzaus/Lxsa4rpz/

function calcNormalAvg(list) {
    // sum(list) / len(list)
    return list.reduce(function(a, b) { return a + b; }) / list.length;
}
function calcRunningAvg(previousAverage, currentNumber, index) {
    // [ avg' * (n-1) + x ] / n
    return ( previousAverage * (index - 1) + currentNumber ) / index;
}

_x000D_
_x000D_
(function(){_x000D_
  // populate base list_x000D_
var list = [];_x000D_
function getSeedNumber() { return Math.random()*100; }_x000D_
for(var i = 0; i < 50; i++) list.push( getSeedNumber() );_x000D_
_x000D_
  // our calculation functions, for comparison_x000D_
function calcNormalAvg(list) {_x000D_
   // sum(list) / len(list)_x000D_
 return list.reduce(function(a, b) { return a + b; }) / list.length;_x000D_
}_x000D_
function calcRunningAvg(previousAverage, currentNumber, index) {_x000D_
   // [ avg' * (n-1) + x ] / n_x000D_
 return ( previousAverage * (index - 1) + currentNumber ) / index;_x000D_
}_x000D_
  function calcMovingAvg(accumulator, new_value, alpha) {_x000D_
   return (alpha * new_value) + (1.0 - alpha) * accumulator;_x000D_
}_x000D_
_x000D_
  // start our baseline_x000D_
var baseAvg = calcNormalAvg(list);_x000D_
var runningAvg = baseAvg, movingAvg = baseAvg;_x000D_
console.log('base avg: %d', baseAvg);_x000D_
  _x000D_
  var okay = true;_x000D_
  _x000D_
  // table of output, cleaner console view_x000D_
  var results = [];_x000D_
_x000D_
  // add 10 more numbers to the list and compare calculations_x000D_
for(var n = list.length, i = 0; i < 10; i++, n++) {_x000D_
 var newNumber = getSeedNumber();_x000D_
_x000D_
 runningAvg = calcRunningAvg(runningAvg, newNumber, n+1);_x000D_
 movingAvg = calcMovingAvg(movingAvg, newNumber, 1/(n+1));_x000D_
_x000D_
 list.push(newNumber);_x000D_
 baseAvg = calcNormalAvg(list);_x000D_
_x000D_
 // assert and inspect_x000D_
 console.log('added [%d] to list at pos %d, running avg = %d vs. regular avg = %d (%s), vs. moving avg = %d (%s)'_x000D_
  , newNumber, list.length, runningAvg, baseAvg, runningAvg == baseAvg, movingAvg, movingAvg == baseAvg_x000D_
 )_x000D_
results.push( {x: newNumber, n:list.length, regular: baseAvg, running: runningAvg, moving: movingAvg, eqRun: baseAvg == runningAvg, eqMov: baseAvg == movingAvg } );_x000D_
_x000D_
if(runningAvg != baseAvg) console.warn('Fail!');_x000D_
okay = okay && (runningAvg == baseAvg);    _x000D_
}_x000D_
  _x000D_
  console.log('Everything matched for running avg? %s', okay);_x000D_
  if(console.table) console.table(results);_x000D_
})();
_x000D_
_x000D_
_x000D_

Getting 400 bad request error in Jquery Ajax POST

In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.

It turned out to be the anti forgery token.

$.ajax({
        url: "/Cart/AddProduct/",
        data: {
            __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            productId: $(this).data("productcode")
        },

The problem was that the .Net controller wasn't set up correctly.

I needed to add the attributes to the controller:

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    [DisableCors]
    [HttpPost]
    public async Task<JsonResult> AddProduct(int productId)
    {

The code needs review but for now at least I know what was causing it. 400 error not helpful at all.

How to install pip with Python 3?

For Ubuntu 12.04 or older,

sudo apt-get install python3-pip

won't work. Instead, use:

sudo apt-get install python3-setuptools ca-certificates
sudo easy_install3 pip

how to change onclick event with jquery?

(2019) I used $('#'+id).removeAttr().off('click').on('click', function(){...});

I tried $('#'+id).off().on(...), but it wouldn't work to reset the onClick attribute every time it was called to be reset.

I use .on('click',function(){...}); to stay away from having to quote block all my javascript functions.

The O.P. could now use:

$(this).removeAttr('onclick').off('click').on('click', function(){ displayCalendar(document.prjectFrm[ia + 'dtSubDate'],'yyyy-mm-dd', this); });

Where this came through for me is when my div was set with the onClick attribute set statically:

<div onclick = '...'>

Otherwise, if I only had a dynamically attached a listener to it, I would have used the $('#'+id).off().on('click', function(){...});.

Without the off('click') my onClick listeners were being appended not replaced.

Javascript regular expression password validation having special characters

Regex for password:

/^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[a-zA-Z!#$%&? "])[a-zA-Z0-9!#$%&?]{8,20}$/

Took me a while to figure out the restrictions, but I did it!

Restrictions: (Note: I have used >> and << to show the important characters)

  1. Minimum 8 characters {>>8,20}
  2. Maximum 20 characters {8,>>20}
  3. At least one uppercase character (?=.*[A-Z])
  4. At least one lowercase character (?=.*[a-z])
  5. At least one digit (?=.*\d)
  6. At least one special character (?=.*[a-zA-Z >>!#$%&? "<<])[a-zA-Z0-9 >>!#$%&?<< ]

Invalid column count in CSV input on line 1 Error

If your DB table already exists and you do NOT want to include all the table's columns in your CSV file, then when you run PHP Admin Import, you'll need fill in the Column Names field in the Format-Specific Options for CSV - Shown here at the bottom of the following screenshot.

In summary:

  • Choose a CSV file
  • Set the Format to CSV
  • Fill in the Column Names field with the names of the columns in your CSV
  • If your CSV file has the column names listed in row 1, set "Skip this number of queries (for SQL) or lines (for other formats), starting from the first one" to 1

enter image description here

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.

from pandas import DataFrame, concat

a = DataFrame([{'a':1,      'c':2,'d':3      }])
b = DataFrame([{'a':4,'b':5,      'd':6,'e':7}])

>>> concat([a,b],sort=False)
   a    c  d    b    e
0  1  2.0  3  NaN  NaN
0  4  NaN  6  5.0  7.0

>>> concat([a,b],sort=True)
   a    b    c  d    e
0  1  NaN  2.0  3  NaN
0  4  5.0  NaN  6  7.0

jQuery get mouse position within an element

To get the position of click relative to current clicked element
Use this code

$("#specialElement").click(function(e){
    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
}); 

Symbol for any number of any characters in regex?

.*

. is any char, * means repeated zero or more times.

How to get first and last day of previous month (with timestamp) in SQL Server

First Day Of Current Week.

select CONVERT(varchar,dateadd(week,datediff(week,0,getdate()),0),106)

Last Day Of Current Week.

select CONVERT(varchar,dateadd(week,datediff(week,0,getdate()),6),106)

First Day Of Last week.

select CONVERT(varchar,DATEADD(week,datediff(week,7,getdate()),0),106)

Last Day Of Last Week.

select CONVERT(varchar,dateadd(week,datediff(week,7,getdate()),6),106)

First Day Of Next Week.

select CONVERT(varchar,dateadd(week,datediff(week,0,getdate()),7),106)

Last Day Of Next Week.

select CONVERT(varchar,dateadd(week,datediff(week,0,getdate()),13),106)

First Day Of Current Month.

select CONVERT(varchar,dateadd(d,-(day(getdate()-1)),getdate()),106)

Last Day Of Current Month.

select CONVERT(varchar,dateadd(d,-(day(dateadd(m,1,getdate()))),dateadd(m,1,getdate())),106)

In this Example Works on Only date is 31. and remaining days are not.

First Day Of Last Month.

select CONVERT(varchar,dateadd(d,-(day(dateadd(m,-1,getdate()-2))),dateadd(m,-1,getdate()-1)),106)

Last Day Of Last Month.

select CONVERT(varchar,dateadd(d,-(day(getdate())),getdate()),106)

First Day Of Next Month.

select CONVERT(varchar,dateadd(d,-(day(dateadd(m,1,getdate()-1))),dateadd(m,1,getdate())),106)

Last Day Of Next Month.

select CONVERT(varchar,dateadd(d,-(day(dateadd(m,2,getdate()))),DATEADD(m,2,getdate())),106)

First Day Of Current Year.

select CONVERT(varchar,dateadd(year,datediff(year,0,getdate()),0),106)

Last Day Of Current Year.

select CONVERT(varchar,dateadd(ms,-2,dateadd(year,0,dateadd(year,datediff(year,0,getdate())+1,0))),106)

First Day of Last Year.

select CONVERT(varchar,dateadd(year,datediff(year,0,getdate())-1,0),106)

Last Day Of Last Year.

select CONVERT(varchar,dateadd(ms,-2,dateadd(year,0,dateadd(year,datediff(year,0,getdate()),0))),106)

First Day Of Next Year.

select CONVERT(varchar,dateadd(YEAR,DATEDIFF(year,0,getdate())+1,0),106)

Last Day Of Next Year.

select CONVERT(varchar,dateadd(ms,-2,dateadd(year,0,dateadd(year,datediff(year,0,getdate())+2,0))),106)

Check if table exists and if it doesn't exist, create it in SQL Server 2008

Let us create a sample database with a table by the below script:

CREATE DATABASE Test
GO
USE Test
GO
CREATE TABLE dbo.tblTest (Id INT, Name NVARCHAR(50))

Approach 1: Using INFORMATION_SCHEMA.TABLES view

We can write a query like below to check if a tblTest Table exists in the current database.

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'tblTest')
BEGIN
  PRINT 'Table Exists'
END

The above query checks the existence of the tblTest table across all the schemas in the current database. Instead of this if you want to check the existence of the Table in a specified Schema and the Specified Database then we can write the above query as below:

IF EXISTS (SELECT * FROM Test.INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = N'dbo'  AND TABLE_NAME = N'tblTest')
BEGIN
  PRINT 'Table Exists'
END

Pros of this Approach: INFORMATION_SCHEMA views are portable across different RDBMS systems, so porting to different RDBMS doesn’t require any change.

Approach 2: Using OBJECT_ID() function

We can use OBJECT_ID() function like below to check if a tblTest Table exists in the current database.

IF OBJECT_ID(N'dbo.tblTest', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END

Specifying the Database Name and Schema Name parts for the Table Name is optional. But specifying Database Name and Schema Name provides an option to check the existence of the table in the specified database and within a specified schema, instead of checking in the current database across all the schemas. The below query shows that even though the current database is MASTER database, we can check the existence of the tblTest table in the dbo schema in the Test database.

USE MASTER
GO
IF OBJECT_ID(N'Test.dbo.tblTest', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END

Pros: Easy to remember. One other notable point to mention about OBJECT_ID() function is: it provides an option to check the existence of the Temporary Table which is created in the current connection context. All other Approaches checks the existence of the Temporary Table created across all the connections context instead of just the current connection context. Below query shows how to check the existence of a Temporary Table using OBJECT_ID() function:

CREATE TABLE #TempTable(ID INT)
GO
IF OBJECT_ID(N'TempDB.dbo.#TempTable', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END
GO

Approach 3: Using sys.Objects Catalog View

We can use the Sys.Objects catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Objects WHERE  Object_id = OBJECT_ID(N'dbo.tblTest') AND Type = N'U')
BEGIN
  PRINT 'Table Exists'
END

Approach 4: Using sys.Tables Catalog View

We can use the Sys.Tables catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Tables WHERE  Name = N'tblTest' AND Type = N'U')
BEGIN
  PRINT 'Table Exists'
END

Sys.Tables catalog view inherits the rows from the Sys.Objects catalog view, Sys.objects catalog view is referred to as base view where as sys.Tables is referred to as derived view. Sys.Tables will return the rows only for the Table objects whereas Sys.Object view apart from returning the rows for table objects, it returns rows for the objects like: stored procedure, views etc.

Approach 5: Avoid Using sys.sysobjects System table

We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per [Microsoft BOL][1] link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly.

IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'tblTest' AND xtype = N'U')
BEGIN
  PRINT 'Table Exists'
END

Reference: http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/

Cannot delete directory with Directory.Delete(path, true)

This error occurs if any file or directory is considered in-use. It is a misleading error. Check to see if you have any explorer windows or command-line windows open to any directory in the tree, or a program that is using a file in that tree.

How to include layout inside layout?

Note that if you include android:id... into the <include /> tag, it will override whatever id was defined inside the included layout. For example:

<include
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:id="@+id/some_id_if_needed"
   layout="@layout/yourlayout" />

yourlayout.xml:

<LinearLayout
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:id="@+id/some_other_id">
   <Button
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:id="@+id/button1" />
 </LinearLayout>

Then you would reference this included layout in code as follows:

View includedLayout = findViewById(R.id.some_id_if_needed);
Button insideTheIncludedLayout = (Button)includedLayout.findViewById(R.id.button1);

break statement in "if else" - java

Because your else isn't attached to anything. The if without braces only encompasses the single statement that immediately follows it.

if (choice==5)
{
    System.out.println("End of Game\n Thank you for playing with us!");
    break;
}
else
{
   System.out.println("Not a valid choice!\n Please try again...\n");
}

Not using braces is generally viewed as a bad practice because it can lead to the exact problems you encountered.

In addition, using a switch here would make more sense.

int choice;
boolean keepGoing = true;
while(keepGoing)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch(choice)
    {
        case 1: 
            playGame();
            break;
        case 2: 
            loadGame();
            break;
        // your other cases
        // ...
        case 5: 
            System.out.println("End of Game\n Thank you for playing with us!");
            keepGoing = false;
            break;
        default:
            System.out.println("Not a valid choice!\n Please try again...\n");
     }
 }         

Note that instead of an infinite for loop I used a while(boolean), making it easy to exit the loop. Another approach would be using break with labels.

OS X: equivalent of Linux's wget

Curl has a mode that is almost equivalent to the default wget.

curl -O <url>

This works just like

wget <url>

And, if you like, you can add this to your .bashrc:

alias wget='curl -O'

It's not 100% compatible, but it works for the most common wget usage (IMO)

Valid characters of a hostname?

A "name" (Net, Host, Gateway, or Domain name) is a text string up to 24 characters drawn from the alphabet (A-Z), digits (0-9), minus sign (-), and period (.). Note that periods are only allowed when they serve to delimit components of "domain style names". (See RFC-921, "Domain Name System Implementation Schedule", for background). No blank or space characters are permitted as part of a name. No distinction is made between upper and lower case. The first character must be an alpha character. The last character must not be a minus sign or period. A host which serves as a GATEWAY should have "-GATEWAY" or "-GW" as part of its name. Hosts which do not serve as Internet gateways should not use "-GATEWAY" and "-GW" as part of their names. A host which is a TAC should have "-TAC" as the last part of its host name, if it is a DoD host. Single character names or nicknames are not allowed.

This is provided in http://support.microsoft.com/kb/149044

CSS3 Spin Animation

To rotate, you can use key frames and a transform.

div {
    margin: 20px;
    width: 100px; 
    height: 100px;    
    background: #f00;
    -webkit-animation-name: spin;
    -webkit-animation-duration: 40000ms;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-timing-function: linear;
    -moz-animation-name: spin;
    -moz-animation-duration: 40000ms;
    -moz-animation-iteration-count: infinite;
    -moz-animation-timing-function: linear;
    -ms-animation-name: spin;
    -ms-animation-duration: 40000ms;
    -ms-animation-iteration-count: infinite;
    -ms-animation-timing-function: linear;
}

@-webkit-keyframes spin {
  from {
    -webkit-transform:rotate(0deg);
  }

  to {
    -webkit-transform:rotate(360deg);
  }
}

Example

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

Format date and Subtract days using Moment.js

I think you have got it in that last attempt, you just need to grab the string.. in Chrome's console..

startdate = moment();
startdate.subtract(1, 'd');
startdate.format('DD-MM-YYYY');
"14-04-2015"

startdate = moment();
startdate.subtract(1, 'd');
myString = startdate.format('DD-MM-YYYY');
"14-04-2015"
myString
"14-04-2015"

What is the difference between XML and XSD?


Take an example

<root>
  <parent>
     <child_one>Y</child_one>
     <child_two>12</child_two>
  </parent>
</root>

and design an xsd for that:

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" 
xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="root">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="parent">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="child_one" type="xs:string" />
              <xs:element name="child_two" type="xs:int" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>


What isn't possible with XSD: would like to write it first as the list is very small
1) You can't validate a node/attribute using the value of another node/attribute.
2) This is a restriction : An element defined in XSD file must be defined with only one datatype. [in the above example, for <child_two> appearing in another <parent> node, datatype cannot be defined other than int.
3) You can't ignore the validation of elements and attributes, ie, if an element/attribute appears in XML, it must be well-defined in the corresponding XSD. Though usage of <xsd:any> allows it, but it has got its own rules. Abiding which leads to the validation error. I had tried for a similar approach, and certainly wasn't successful, here is the Q&A


what are possible with XSD:
1) You can test the proper hierarchy of the XML nodes. [xsd defines which child should come under which parent, etc, abiding which will be counted as error, in above example, child_two cannot be the immediate child of root, but it is the child of "parent" tag which is in-turn a child of "root" node, there is a hierarchy..]
2) You can define Data type of the values of the nodes. [in above example child_two cannot have any-other data than number]
3) You can also define custom data_types, [example, for node <month>, the possible data can be one of the 12 months.. so you need to define all the 12 months in a new data type writing all the 12 month names as enumeration values .. validation shows error if the input XML contains any-other value than these 12 values .. ]
4) You can put the restriction on the occurrence of the elements, using minOccurs and maxOccurs, the default values are 1 and 1.

.. and many more ...

Viewing localhost website from mobile device

First of all open applicationhost.config file in visual studio. address>>C:\Users\Your User Name\Documents\IISExpress\config\applicationhost.config

Then find this codes:

<site name="Your Site_Name" id="24">
        <application path="/" applicationPool="Clr4IntegratedAppPool"
        <virtualDirectory path="/" physicalPath="C:\Users\Your User         Name\Documents\Visual Studio 2013\Projects\Your Site Name" />
        </application>
         <bindings>      
           <binding protocol="http" bindingInformation="*:Port_Number:*" />
         </bindings>
   </site>

*)Port_Number:While your site running in IIS express on your computer, port number will visible in address bar of your browser like this: localhost:port_number/... When edit this file save it.

In the Second step you must run cmd as administrator and type this code: netsh http add urlacl url=http://*:port_Number/ user=everyone and press enter

In Third step you must Enable port on firewall

Go to the “Control Panel\System and Security\Windows Firewall”

Click “Advanced settings”

Select “Inbound Rules”

Click on “New Rule …” button

Select “Port”, click “Next”

Fill your IIS Express listening port number, click “Next”

Select “Allow the connection”, click “Next”

Check where you would like allow connection to IIS Express (Domain,Private, Public), click “Next”

Fill rule name (e.g “IIS Express), click “Finish”

I hopeful this answer be useful for you

Update for Visual Studio 2015 in this link: https://johan.driessen.se/posts/Accessing-an-IIS-Express-site-from-a-remote-computer

Python json.loads shows ValueError: Extra data

One-liner for your problem:

data = [json.loads(line) for line in open('tweets.json', 'r')]

How to call C++ function from C?

#include <iostream>

//////////////
// C++ code //
//////////////
struct A
{
  int i;
  int j;

  A() {i=1; j=2; std::cout << "class A created\n";}
  void dump() {std::cout << "class A dumped: " << i << ":" << j << std::endl;}
  ~A() {std::cout << "class A destroyed\n";}
};

extern "C" {
  // this is the C code interface to the class A
  static void *createA (void)
  {
    // create a handle to the A class
    return (void *)(new A);
  }
  static void dumpA (void *thisPtr)
  {
    // call A->dump ()
    if (thisPtr != NULL) // I'm an anal retentive programmer
    {
      A *classPtr = static_cast<A *>(thisPtr);
      classPtr->dump ();
    }
  }
  static void *deleteA (void *thisPtr)
  {
    // destroy the A class
    if (thisPtr != NULL)
    {
      delete (static_cast<A *>(thisPtr));
    }
  }
}

////////////////////////////////////
// this can be compiled as C code //
////////////////////////////////////
int main (int argc, char **argv)
{
  void *handle = createA();

  dumpA (handle);
  deleteA (handle);

  return 0;
}

jQuery hyperlinks - href value?

Wonder why nobody said it here earlier: to prevent <a href="#"> from scrolling document position to the top, simply use <a href="#/"> instead. That's mere HTML, no JQuery needed. Using event.preventDefault(); is just too much!

"ImportError: No module named" when trying to run Python script

Remove pathlib and reinstall it. Delete the pathlib in sitepackages folder and reinstall the pathlib package by using pip command:

pip install pathlib

Eclipse - Unable to install breakpoint due to missing line number attributes

I had similar issue on Spring MVC + Maven project; and spent 2 hours trying to figure out why target folder does not get updated with classes containing information about lines.

I suggest you clean everything and make sure all classes are deleted from the folder before you proceed with any build.

  1. Make sure that in Project's Properties > Java Compiler has "Add line number attributes to generated class fiels (used by the debugger) selected.
  2. Clean all project.. (Menu > Project > Clean...) Make sure that the target folder is empty.
  3. Build project (Menu > Project > Build Project)
  4. Make sure new classes are generated in your target directory.
  5. Run Debug; if running on WebServer - make sure you run your webserver in "Debug" mode.

If in doubt - whether compiled .class files contain line numbers or not - open the .class files in Eclipse. The Eclipse will decompile the files and tell you whether Line numbers exist or not.

enter image description here

SQL Server ORDER BY date and nulls last

A bit late, but maybe someone finds it useful.

For me, ISNULL was out of question due to the table scan. UNION ALL would need me to repeat a complex query, and due to me selecting only the TOP X it would not have been very efficient.

If you are able to change the table design, you can:

  1. Add another field, just for sorting, such as Next_Contact_Date_Sort.

  2. Create a trigger that fills that field with a large (or small) value, depending on what you need:

    CREATE TRIGGER FILL_SORTABLE_DATE ON YOUR_TABLE AFTER INSERT,UPDATE AS 
    BEGIN
        SET NOCOUNT ON;
        IF (update(Next_Contact_Date)) BEGIN
        UPDATE YOUR_TABLE SET Next_Contact_Date_Sort=IIF(YOUR_TABLE.Next_Contact_Date IS NULL, 99/99/9999, YOUR_TABLE.Next_Contact_Date_Sort) FROM inserted i WHERE YOUR_TABLE.key1=i.key1 AND YOUR_TABLE.key2=i.key2
        END
    END
    

Regular expression for URL validation (in JavaScript)

This REGEX is a patch from @Aamir answer that worked for me

/((?:(?:http?|ftp)[s]*:\/\/)?[a-z0-9-%\/\&=?\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?)/gi

It matches these URL formats

  1. yourwebsite.com
  2. yourwebsite.com/4564564/546564/546564?=adsfasd
  3. www.yourwebsite.com
  4. http://yourwebsite.com
  5. https://yourwebsite.com
  6. ftp://www.yourwebsite.com
  7. ftp://yourwebsite.com
  8. http://yourwebsite.com/4564564/546564/546564?=adsfasd

Set new id with jQuery

Use .val() not attr('value').

Mac OS X and multiple Java versions

Uninstall jdk8, install jdk7, then reinstall jdk8.

My approach to switching between them (in .profile) :

export JAVA_7_HOME=$(/usr/libexec/java_home -v1.7)
export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8)
export JAVA_9_HOME=$(/usr/libexec/java_home -v9)

alias java7='export JAVA_HOME=$JAVA_7_HOME'
alias java8='export JAVA_HOME=$JAVA_8_HOME'
alias java9='export JAVA_HOME=$JAVA_9_HOME'

#default java8
export JAVA_HOME=$JAVA_8_HOME

Then you can simply type java7 or java8 in a terminal to switch versions.

(edit: updated to add Dylans improvement for Java 9)

Alter table to modify default value of column

ALTER TABLE <table_name> MODIFY <column_name> DEFAULT <defult_value>

EX: ALTER TABLE AAA MODIFY ID DEFAULT AAA_SEQUENCE.nextval

Tested on Oracle Database 12c Enterprise Edition Release 12.2.0.1.0

The entity cannot be constructed in a LINQ to Entities query

You can project into anonymous type, and then from it to model type

public IEnumerable<Product> GetProducts(int categoryID)
{
    return (from p in Context.Set<Product>()
            where p.CategoryID == categoryID
            select new { Name = p.Name }).ToList()
           .Select(x => new Product { Name = x.Name });
}

Edit: I am going to be a bit more specific since this question got a lot of attention.

You cannot project into model type directly (EF restriction), so there is no way around this. The only way is to project into anonymous type (1st iteration), and then to model type (2nd iteration).

Please also be aware that when you partially load entities in this manner, they cannot be updated, so they should remain detached, as they are.

I never did completely understand why this is not possible, and the answers on this thread do not give strong reasons against it (mostly speaking about partially loaded data). It is correct that in partially loaded state entity cannot be updated, but then, this entity would be detached, so accidental attempts to save them would not be possible.

Consider method I used above: we still have a partially loaded model entity as a result. This entity is detached.

Consider this (wish-to-exist) possible code:

return (from p in Context.Set<Product>()
        where p.CategoryID == categoryID
        select new Product { Name = p.Name }).AsNoTracking().ToList();

This could also result in a list of detached entities, so we would not need to make two iterations. A compiler would be smart to see that AsNoTracking() has been used, which will result in detached entities, so it could allow us to do this. If, however, AsNoTracking() was omitted, it could throw the same exception as it is throwing now, to warn us that we need to be specific enough about the result we want.

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

This error can occur in several places, most commonly running further LINQ queries on top of a null collection. LINQ as Query Syntax can appear more null-safe than it is. Consider the following samples:

var filteredCollection = from item in getMyCollection()
                         orderby item.ReportDate
                         select item;

This code is not NULL SAFE, meaning that if getMyCollection() returns a null, you'll get the Value cannot be null. Parameter name: source error. Very annoying! But it makes perfect sense because LINQ Query syntax is just syntactic sugar for this equivalent code:

var filteredCollection = getMyCollection().OrderBy(x => x.ReportDate);

Which obviously will blow up if the starting method returns a null.

To prevent this, you can use a null coalescing operator in your LINQ query like so:

var filteredCollection = from item in getMyCollection() ?? 
                              Enumerable.Empty<CollectionItemClass>()
                         orderby item.ReportDate
                         select item;

However, you'll have to remember to do this in any related queries. The best approach (if you control the code that generates the collection) is to make it a coding practice to NEVER RETURN A NULL COLLECTION, EVER. In some cases, returning a null object from a method like "getCustomerById(string id)" is fine, depending on your team coding style, but if you have a method that returns a collection of business objects, like "getAllcustomers()" then it should NEVER return a null array/enumerable/etc. Always always always use an if check, the null coalescing operator, or some other switch to return an empty array/list/enumerable etc, so that consumers of your method can freely LINQ over the results.

Changing the selected option of an HTML Select element

After a lot of searching I tried @kzh on select list where I only know option inner text not value attribute, this code based on select answer I used it to change select option according to current page urlon this format http://www.example.com/index.php?u=Steve

<select id="sel">
    <option>Joe</option>
    <option>Steve</option>
    <option>Jack</option>
</select>
<script>
    var val = window.location.href.split('u=')[1]; // to filter ?u= query 
    var sel = document.getElementById('sel');
    var opts = sel.options;
    for(var opt, j = 0; opt = opts[j]; j++) {
        // search are based on text inside option Attr
        if(opt.text == val) {
            sel.selectedIndex = j;
            break;
        }
    }
</script>

This will keeps url parameters shown as selected to make it more user friendly and the visitor knows what page or profile he is currently viewing .

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

One command to convert date time to Unix format and then to string

    DateTime.strptime(Time.now.utc.to_i.to_s,'%s').strftime("%d %m %y")

    Time.now.utc.to_i #Converts time from Unix format
    DateTime.strptime(Time.now.utc.to_i.to_s,'%s') #Converts date and time from unix format to DateTime

finally strftime is used to format date

Example:

    irb(main):034:0> DateTime.strptime("1410321600",'%s').strftime("%d %m %y")
    "10 09 14"

Passing parameters from jsp to Spring Controller method

Use the @RequestParam to pass a parameter to the controller handler method. In the jsp your form should have an input field with name = "id" like the following:

<input type="text" name="id" />
<input type="submit" />

Then in your controller, your handler method should be like the following:

@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
    return "note";
}

Please also refer to these answers and tutorial:

Make scrollbars only visible when a Div is hovered over?

.div::-webkit-scrollbar-thumb {
    background: transparent;
}

.div:hover::-webkit-scrollbar-thumb {
    background: red;
}

get the value of "onclick" with jQuery?

$('#google').attr('onclick') + ""

However, Firebug shows that this returns a function 'onclick'. You can call the function later on using the following approach:

(new Function ($('#google').attr('onclick') + ';onclick();'))()

... or use a RegEx to strip the function and get only the statements within it.

SimpleDateFormat parse loses timezone

All I needed was this :

SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

try {
    String d = sdf.format(new Date());
    System.out.println(d);
    System.out.println(sdfLocal.parse(d));
} catch (Exception e) {
    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
}

Output : slightly dubious, but I want only the date to be consistent

2013.08.08 11:01:08
Thu Aug 08 11:01:08 GMT+08:00 2013

Apply style to cells of first row

Below works for first tr of the table under thead

table thead tr:first-child {
   background: #f2f2f2;
}

And this works for the first tr of thead and tbody both:

table thead tbody tr:first-child {
   background: #f2f2f2;
}

How to get only the last part of a path in Python?

With python 3 you can use the pathlib module (pathlib.PurePath for example):

>>> import pathlib

>>> path = pathlib.PurePath('/folderA/folderB/folderC/folderD/')
>>> path.name
'folderD'

If you want the last folder name where a file is located:

>>> path = pathlib.PurePath('/folderA/folderB/folderC/folderD/file.py')
>>> path.parent.name
'folderD'

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

I faced the same problem with JBoss 4.2.3 GA when deploying my web application. I solved the issue by copying my commons-codec 1.6 jar into C:\jboss-4.2.3.GA\server\default\lib

EnterKey to press button in VBA Userform

You could also use the TextBox's On Key Press event handler:

'Keycode for "Enter" is 13
Private Sub TextBox1_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = 13 Then
         Logincode_Click
    End If
End Sub

Textbox1 is an example. Make sure you choose the textbox you want to refer to and also Logincode_Click is an example sub which you call (run) with this code. Make sure you refer to your preferred sub

Converting an int to std::string

#include <string>
#include <stdlib.h>

Here, is another easy way to convert int to string

int n = random(65,90);
std::string str1=(__String::createWithFormat("%c",n)->getCString());

you may visit this link for more methods https://www.geeksforgeeks.org/what-is-the-best-way-in-c-to-convert-a-number-to-a-string/

jQuery AJAX Call to PHP Script with JSON Return

Your datatype is wrong, change datatype for dataType.

Best way to remove items from a collection

For a simple List structure the most efficient way seems to be using the Predicate RemoveAll implementation.

Eg.

 workSpace.RoleAssignments.RemoveAll(x =>x.Member.Name == shortName);

The reasons are:

  1. The Predicate/Linq RemoveAll method is implemented in List and has access to the internal array storing the actual data. It will shift the data and resize the internal array.
  2. The RemoveAt method implementation is quite slow, and will copy the entire underlying array of data into a new array. This means reverse iteration is useless for List

If you are stuck implementing this in a the pre c# 3.0 era. You have 2 options.

  • The easily maintainable option. Copy all the matching items into a new list and and swap the underlying list.

Eg.

List<int> list2 = new List<int>() ; 
foreach (int i in GetList())
{
    if (!(i % 2 == 0))
    {
        list2.Add(i);
    }
}
list2 = list2;

Or

  • The tricky slightly faster option, which involves shifting all the data in the list down when it does not match and then resizing the array.

If you are removing stuff really frequently from a list, perhaps another structure like a HashTable (.net 1.1) or a Dictionary (.net 2.0) or a HashSet (.net 3.5) are better suited for this purpose.

Error when creating a new text file with python?

instead of using try-except blocks, you could use, if else

this will not execute if the file is non-existent, open(name,'r+')

if os.path.exists('location\filename.txt'):
    print "File exists"

else:
   open("location\filename.txt", 'w')

'w' creates a file if its non-exis

How to enter ssh password using bash?

Create a new keypair: (go with the defaults)

ssh-keygen

Copy the public key to the server: (password for the last time)

ssh-copy-id [email protected]

From now on the server should recognize your key and not ask you for the password anymore:

ssh [email protected]

passing several arguments to FUN of lapply (and others *apply)

If you look up the help page, one of the arguments to lapply is the mysterious .... When we look at the Arguments section of the help page, we find the following line:

...: optional arguments to ‘FUN’.

So all you have to do is include your other argument in the lapply call as an argument, like so:

lapply(input, myfun, arg1=6)

and lapply, recognizing that arg1 is not an argument it knows what to do with, will automatically pass it on to myfun. All the other apply functions can do the same thing.

An addendum: You can use ... when you're writing your own functions, too. For example, say you write a function that calls plot at some point, and you want to be able to change the plot parameters from your function call. You could include each parameter as an argument in your function, but that's annoying. Instead you can use ... (as an argument to both your function and the call to plot within it), and have any argument that your function doesn't recognize be automatically passed on to plot.

"SMTP Error: Could not authenticate" in PHPMailer

I received the same error and in mycase it was the password. My password has special characters for and if you supply the password without escaping the special characters the error will continue to show. E.g $mail->Password = " por$ch3"; is valid but will not work using the code above . The solution should be as follows: $mail->Password = "por\$ch3"; Note the Backslash I placed before the dollar character within my password. That should work if you have a password using special characters

Get domain name

I found this question by the title. If anyone else is looking for the answer on how to just get the domain name, use the following environment variable.

System.Environment.UserDomainName

I'm aware that the author to the question mentions this, but I missed it at the first glance and thought someone else might do the same.

What the description of the question then ask for is the fully qualified domain name (FQDN).

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

The problem is that you're calling List<T>.Reverse() which returns void.

You could either do:

List<string> names = "Tom,Scott,Bob".Split(',').ToList<string>();
names.Reverse();

or:

IList<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>();

The latter is more expensive, as reversing an arbitrary IEnumerable<T> involves buffering all of the data and then yielding it all - whereas List<T> can do all the reversing "in-place". (The difference here is that it's calling the Enumerable.Reverse<T>() extension method, instead of the List<T>.Reverse() instance method.)

More efficient yet, you could use:

string[] namesArray = "Tom,Scott,Bob".Split(',');
List<string> namesList = new List<string>(namesArray.Length);
namesList.AddRange(namesArray);
namesList.Reverse();

This avoids creating any buffers of an inappropriate size - at the cost of taking four statements where one will do... As ever, weigh up readability against performance in the real use case.

Return rows in random order

The usual method is to use the NEWID() function, which generates a unique GUID. So,

SELECT * FROM dbo.Foo ORDER BY NEWID();

How can I remove specific rules from iptables?

The best solution that works for me without any problems looks this way:
1. Add temporary rule with some comment:

comment=$(cat /proc/sys/kernel/random/uuid | sed 's/\-//g')
iptables -A ..... -m comment --comment "${comment}" -j REQUIRED_ACTION

2. When the rule added and you wish to remove it (or everything with this comment), do:

iptables-save | grep -v "${comment}" | iptables-restore

So, you'll 100% delete all rules that match the $comment and leave other lines untouched. This solution works for last 2 months with about 100 changes of rules per day - no issues.Hope, it helps

How to add hamburger menu in bootstrap

All you have to do is read the code on getbootstrap.com:

Codepen

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
_x000D_
<nav class="navbar navbar-inverse navbar-static-top" role="navigation">_x000D_
  <div class="container">_x000D_
    <div class="navbar-header">_x000D_
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
    </div>_x000D_
_x000D_
    <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
      <ul class="nav navbar-nav">_x000D_
        <li><a href="index.php">Home</a></li>_x000D_
        <li><a href="about.php">About</a></li>_x000D_
        <li><a href="#portfolio">Portfolio</a></li>_x000D_
        <li><a href="#">Blog</a></li>_x000D_
        <li><a href="contact.php">Contact</a></li>_x000D_
      </ul>_x000D_
    </div>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Pressing Ctrl + A in Selenium WebDriver

The simplest answer in C# (if you are C# inclined).

Actions action = new Actions(); 
action.KeyDown(OpenQA.Selenium.Keys.Control).SendKeys("a").KeyUp(OpenQA.Selenium.Keys.Control).perform();

This answer is almost given by Hari Reddy, but I have fixed the case which he'd got wrong on some keywords, added the KeyUp or you get in a mess leaving the control key down.

I've also added the clarification on OpenQA.Selenium.Keys, because you may also be using Windows.Forms on the same class as I was an require this clarity.

Lastly, I type "a" because I found that to be the simplest way and I can see no suggestion from the OP that they don't want the simplest answer.

Many thanks to Hari Reddy though as I was a novice in Actions class usage and I was writing many different commands. Chaining them together the way he showed is quicker :-)

C++ IDE for Linux?

I use Eclipse CDT and Qt Creator (for Qt applications).

That's my preferences. It's a very suggestive question and there is as many answers as there is developers. :)

Android lollipop change navigation bar color

You can change it directly in styles.xml file \app\src\main\res\values\styles.xml

This work on older versions, I was changing it in KitKat and come here.

Date in to UTC format Java

Try this... Worked for me and printed 10/22/2013 01:37:56 AM Ofcourse this is your code only with little modifications.

final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));   // This line converts the given date into UTC time zone
final java.util.Date dateObj = sdf.parse("2013-10-22T01:37:56");

aRevisedDate = new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a").format(dateObj);
System.out.println(aRevisedDate);

Can I make a function available in every controller in angular?

I'm a bit newer to Angular but what I found useful to do (and pretty simple) is I made a global script that I load onto my page before the local script with global variables that I need to access on all pages anyway. In that script, I created an object called "globalFunctions" and added the functions that I need to access globally as properties. e.g. globalFunctions.foo = myFunc();. Then, in each local script, I wrote $scope.globalFunctions = globalFunctions; and I instantly have access to any function I added to the globalFunctions object in the global script.

This is a bit of a workaround and I'm not sure it helps you but it definitely helped me as I had many functions and it was a pain adding all of them to each page.

Which characters need to be escaped in HTML?

If you're inserting text content in your document in a location where text content is expected1, you typically only need to escape the same characters as you would in XML. Inside of an element, this just includes the entity escape ampersand & and the element delimiter less-than and greater-than signs < >:

& becomes &amp;
< becomes &lt;
> becomes &gt;

Inside of attribute values you must also escape the quote character you're using:

" becomes &quot;
' becomes &#39;

In some cases it may be safe to skip escaping some of these characters, but I encourage you to escape all five in all cases to reduce the chance of making a mistake.

If your document encoding does not support all of the characters that you're using, such as if you're trying to use emoji in an ASCII-encoded document, you also need to escape those. Most documents these days are encoded using the fully Unicode-supporting UTF-8 encoding where this won't be necessary.

In general, you should not escape spaces as &nbsp;. &nbsp; is not a normal space, it's a non-breaking space. You can use these instead of normal spaces to prevent a line break from being inserted between two words, or to insert          extra        space       without it being automatically collapsed, but this is usually a rare case. Don't do this unless you have a design constraint that requires it.


1 By "a location where text content is expected", I mean inside of an element or quoted attribute value where normal parsing rules apply. For example: <p>HERE</p> or <p title="HERE">...</p>. What I wrote above does not apply to content that has special parsing rules or meaning, such as inside of a script or style tag, or as an element or attribute name. For example: <NOT-HERE>...</NOT-HERE>, <script>NOT-HERE</script>, <style>NOT-HERE</style>, or <p NOT-HERE="...">...</p>.

In these contexts, the rules are more complicated and it's much easier to introduce a security vulnerability. I strongly discourage you from ever inserting dynamic content in any of these locations. I have seen teams of competent security-aware developers introduce vulnerabilities by assuming that they had encoded these values correctly, but missing an edge case. There's usually a safer alternative, such as putting the dynamic value in an attribute and then handling it with JavaScript.

If you must, please read the Open Web Application Security Project's XSS Prevention Rules to help understand some of the concerns you will need to keep in mind.

SQL update fields of one table from fields of another one

This is a great help. The code

UPDATE tbl_b b
SET   (  column1,   column2,   column3)
    = (a.column1, a.column2, a.column3)
FROM   tbl_a a
WHERE  b.id = 1
AND    a.id = b.id;

works perfectly.

noted that you need a bracket "" in

From "tbl_a" a

to make it work.

How to find top three highest salary in emp table in oracle?

You could use DBMS_STAT_FUNCS.Summary:

SET SERVEROUTPUT ON;
DECLARE
    s DBMS_STAT_FUNCS.SummaryType;
BEGIN
    DBMS_STAT_FUNCS.SUMMARY('HR', 'EMPLOYEES', 'SALARY',3, s);
    DBMS_OUTPUT.put_line('Top 3: ' || s.top_5_values(1) || '-' 
                         || s.top_5_values(2) || '-' || s.top_5_values(3));
END;
/

Output:

Top 3: 24000-17000-17000

Creating C formatted strings (not printing them)

Don't use sprintf.
It will overflow your String-Buffer and crash your Program.
Always use snprintf

How do multiple clients connect simultaneously to one port, say 80, on a server?

First off, a "port" is just a number. All a "connection to a port" really represents is a packet which has that number specified in its "destination port" header field.

Now, there are two answers to your question, one for stateful protocols and one for stateless protocols.

For a stateless protocol (ie UDP), there is no problem because "connections" don't exist - multiple people can send packets to the same port, and their packets will arrive in whatever sequence. Nobody is ever in the "connected" state.

For a stateful protocol (like TCP), a connection is identified by a 4-tuple consisting of source and destination ports and source and destination IP addresses. So, if two different machines connect to the same port on a third machine, there are two distinct connections because the source IPs differ. If the same machine (or two behind NAT or otherwise sharing the same IP address) connects twice to a single remote end, the connections are differentiated by source port (which is generally a random high-numbered port).

Simply, if I connect to the same web server twice from my client, the two connections will have different source ports from my perspective and destination ports from the web server's. So there is no ambiguity, even though both connections have the same source and destination IP addresses.

Ports are a way to multiplex IP addresses so that different applications can listen on the same IP address/protocol pair. Unless an application defines its own higher-level protocol, there is no way to multiplex a port. If two connections using the same protocol simultaneously have identical source and destination IPs and identical source and destination ports, they must be the same connection.

Pushing value of Var into an Array

jQuery is not the same as an array. If you want to append something at the end of a jQuery object, use:

$('#fruit').append(veggies);

or to append it to the end of a form value like in your example:

 $('#fruit').val($('#fruit').val()+veggies);

In your case, fruitvegbasket is a string that contains the current value of #fruit, not an array.

jQuery (jquery.com) allows for DOM manipulation, and the specific function you called val() returns the value attribute of an input element as a string. You can't push something onto a string.

Quick way to list all files in Amazon S3 bucket?

In Java you can get the keys using ListObjects (see AWS documentation)

FileWriter fileWriter;
BufferedWriter bufferedWriter;
// [...]

AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());        

ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
.withBucketName(bucketName)
.withPrefix("myprefix");
ObjectListing objectListing;

do {
    objectListing = s3client.listObjects(listObjectsRequest);
    for (S3ObjectSummary objectSummary : 
        objectListing.getObjectSummaries()) {
        // write to file with e.g. a bufferedWriter
        bufferedWriter.write(objectSummary.getKey());
    }
    listObjectsRequest.setMarker(objectListing.getNextMarker());
} while (objectListing.isTruncated());

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

You can customize the JsonSerializerSettings by using the Formatters.JsonFormatter.SerializerSettings property in the HttpConfiguration object.

For example, you could do that in the Application_Start() method:

protected void Application_Start()
{
    HttpConfiguration config = GlobalConfiguration.Configuration;
    config.Formatters.JsonFormatter.SerializerSettings.Formatting =
        Newtonsoft.Json.Formatting.Indented;
}

How to check if a table contains an element in Lua?

I know this is an old post, but I wanted to add something for posterity. The simple way of handling the issue that you have is to make another table, of value to key.

ie. you have 2 tables that have the same value, one pointing one direction, one pointing the other.

function addValue(key, value)
    if (value == nil) then
        removeKey(key)
        return
    end
    _primaryTable[key] = value
    _secodaryTable[value] = key
end

function removeKey(key)
    local value = _primaryTable[key]
    if (value == nil) then
        return
    end
    _primaryTable[key] = nil
    _secondaryTable[value] = nil
end

function getValue(key)
    return _primaryTable[key]
end

function containsValue(value)
    return _secondaryTable[value] ~= nil
end

You can then query the new table to see if it has the key 'element'. This prevents the need to iterate through every value of the other table.

If it turns out that you can't actually use the 'element' as a key, because it's not a string for example, then add a checksum or tostring on it for example, and then use that as the key.

Why do you want to do this? If your tables are very large, the amount of time to iterate through every element will be significant, preventing you from doing it very often. The additional memory overhead will be relatively small, as it will be storing 2 pointers to the same object, rather than 2 copies of the same object. If your tables are very small, then it will matter much less, infact it may even be faster to iterate than to have another map lookup.

The wording of the question however strongly suggests that you have a large number of items to deal with.

Unix - copy contents of one directory to another

Quite simple, with a * wildcard.

cp -r Folder1/* Folder2/

But according to your example recursion is not needed so the following will suffice:

cp Folder1/* Folder2/

EDIT:

Or skip the mkdir Folder2 part and just run:

cp -r Folder1 Folder2

VarBinary vs Image SQL Server Data Type to Store Binary Data?

varbinary(max) is the way to go (introduced in SQL Server 2005)

Adding a JAR to an Eclipse Java library

As of Helios Service Release 2, there is no longer support for JAR files.You can add them, but Eclipse will not recognize them as libraries, therefore you can only "import" but can never use.

Remove a child with a specific attribute, in SimpleXML for PHP

If you extend the base SimpleXMLElement class, you can use this method:

class MyXML extends SimpleXMLElement {

    public function find($xpath) {
        $tmp = $this->xpath($xpath);
        return isset($tmp[0])? $tmp[0]: null;
    }

    public function remove() {
        $dom = dom_import_simplexml($this);
        return $dom->parentNode->removeChild($dom);
    }

}

// Example: removing the <bar> element with id = 1
$foo = new MyXML('<foo><bar id="1"/><bar id="2"/></foo>');
$foo->find('//bar[@id="1"]')->remove();
print $foo->asXML(); // <foo><bar id="2"/></foo>

Looping over elements in jQuery

I have used the following before:

var my_form = $('#form-id');
var data = {};

$('input:not([type=checkbox]), input[type=checkbox]:selected, select, textarea', my_form).each(
    function() {
        var name = $(this).attr('name');
        var val = $(this).val();

        if (!data.hasOwnProperty(name)) {
            data[name] = new Array;
        }

        data[name].push(val);
    }
);

This is just written from memory, so might contain mistakes, but this should make an object called data that contains the values for all your inputs.

Note that you have to deal with checkboxes in a special way, to avoid getting the values of unchecked checkboxes. The same is probably true of radio inputs.

Also note using arrays for storing the values, as for one input name, you might have values from several inputs (checkboxes in particular).

Python socket connection timeout

You just need to use the socket settimeout() method before attempting the connect(), please note that after connecting you must settimeout(None) to set the socket into blocking mode, such is required for the makefile . Here is the code I am using:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(address)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)

Setting the correct PATH for Eclipse

Like Abob said:

Eclipse doesn't consult the JAVA_HOME variable

You should specify where Eclipse should find your JDK in the file eclipse.ini. Specifically, the following parameter (note that it is 2 separate lines in the ini file):

-vm
C:\Java\JDK\1.8\bin\javaw.exe

or wherever your javaw.exe happens to be.

Note: The format of the ini file is very particular; make sure to consult https://wiki.eclipse.org/Eclipse.ini to ensure you get it exactly right.

Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

After 4 hours, of trying everything... Windows 2008 R2 the files were green in Window Explorer. The files were marked for encryption and arching that came from the zip file. unchecking those options in the file property fixed the issue for me.

Why does git revert complain about a missing -m option?

I had this problem, the solution was to look at the commit graph (using gitk) and see that I had the following:

*   commit I want to cherry-pick (x)
|\  
| * branch I want to cherry-pick to (y)
* | 
|/  
* common parent (x)

I understand now that I want to do

git cherry-pick -m 2 mycommitsha

This is because -m 1 would merge based on the common parent where as -m 2 merges based on branch y, that is the one I want to cherry-pick to.

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

Do you have an Interface that your "UserService" class implements.

Your endpoints should specify an interface for the contract attribute:

contract="UserService.IUserService"

Remote debugging a Java application

For JDK 1.3 or earlier :

-Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=6006

For JDK 1.4

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=6006

For newer JDK :

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=6006

Please change the port number based on your needs.

From java technotes

From 5.0 onwards the -agentlib:jdwp option is used to load and specify options to the JDWP agent. For releases prior to 5.0, the -Xdebug and -Xrunjdwp options are used (the 5.0 implementation also supports the -Xdebug and -Xrunjdwp options but the newer -agentlib:jdwp option is preferable as the JDWP agent in 5.0 uses the JVM TI interface to the VM rather than the older JVMDI interface)

One more thing to note, from JVM Tool interface documentation:

JVM TI was introduced at JDK 5.0. JVM TI replaces the Java Virtual Machine Profiler Interface (JVMPI) and the Java Virtual Machine Debug Interface (JVMDI) which, as of JDK 6, are no longer provided.

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

In May 2017 Google announced the Google Maps URLs API that allows to construct universal cross-platform links. Now you can open Google maps on web, Android or iOS using the same URL string in form:

https://www.google.com/maps/search/?api=1&parameters

There are several modes that you can use: search, directions, show map and show street view.

So you can use something like

https://www.google.com/maps/search/?api=1&query=58.698017,-152.522067

to open map and place marker on some lat and lng.

For further details please refer to:

https://developers.google.com/maps/documentation/urls/guide

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

For (2), Guava provides exactly what you want as Int.asList(). There is an equivalent for each primitive type in the associated class, e.g., Booleans for boolean, etc.

    int[] arr={1,2,3};
    for(Integer i : Ints.asList(arr)) {
      System.out.println(i);
    }

Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?

math.sqrt is the C implementation of square root and is therefore different from using the ** operator which implements Python's built-in pow function. Thus, using math.sqrt actually gives a different answer than using the ** operator and there is indeed a computational reason to prefer numpy or math module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas ** operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".

See this Stack Overflow question for more information on the difference between ** and math.sqrt.

In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like ** e.g. C++. So ** is probably more Pythonic, but whether or not it's objectively better depends on the use case.

Good PHP ORM Library?

Until PHP 5.3 release don't expect to have a good ORM. It's a OO limitation of PHP.

ToString() function in Go

When you have own struct, you could have own convert-to-string function.

package main

import (
    "fmt"
)

type Color struct {
    Red   int `json:"red"`
    Green int `json:"green"`
    Blue  int `json:"blue"`
}

func (c Color) String() string {
    return fmt.Sprintf("[%d, %d, %d]", c.Red, c.Green, c.Blue)
}

func main() {
    c := Color{Red: 123, Green: 11, Blue: 34}
    fmt.Println(c) //[123, 11, 34]
}

How to perform Unwind segue programmatically?

SWIFT 4:

1. Create an @IBAction with segue inside controller you want to unwind to:

    @IBAction func unwindToVC(segue: UIStoryboardSegue) {

    }

2. In the storyboard, from the controller you want to segue (unwind) from ctrl+drag from the controller sign to exit sign and choose method you created earlier:

enter image description here

3. Now you can notice that in document outline you have new line with title "Unwind segue....". Now you should click on this line and open attribute inspector to set identifier (in my case unwindSegueIdentifier).

enter image description here

4. You're almost done! Now you need to open view controller you wish to unwind from and create some method that will perform segue. For example you can add button, connect it with code with @IBAction, after that inside this IBAction add perfromSegue(withIdentifier:sender:) method:

     @IBAction func unwindToSomeVCWithSegue(_ sender: UIButton) {
         performSegue(withIdentifier: "unwindSegueIdentifier", sender: nil)
     }

So that is all you have to do!

Can you find all classes in a package using reflection?

plain java: FindAllClassesUsingPlainJavaReflectionTest.java

@Slf4j
class FindAllClassesUsingPlainJavaReflectionTest {

  private static final Function<Throwable, RuntimeException> asRuntimeException = throwable -> {
    log.error(throwable.getLocalizedMessage());
    return new RuntimeException(throwable);
  };

  private static final Function<String, Collection<Class<?>>> findAllPackageClasses = basePackageName -> {

    Locale locale = Locale.getDefault();
    Charset charset = StandardCharsets.UTF_8;
    val fileManager = ToolProvider.getSystemJavaCompiler()
                                  .getStandardFileManager(/* diagnosticListener */ null, locale, charset);

    StandardLocation location = StandardLocation.CLASS_PATH;
    JavaFileObject.Kind kind = JavaFileObject.Kind.CLASS;
    Set<JavaFileObject.Kind> kinds = Collections.singleton(kind);
    val javaFileObjects = Try.of(() -> fileManager.list(location, basePackageName, kinds, /* recurse */ true))
                             .getOrElseThrow(asRuntimeException);

    String pathToPackageAndClass = basePackageName.replace(".", File.separator);
    Function<String, String> mapToClassName = s -> {
      String prefix = Arrays.stream(s.split(pathToPackageAndClass))
                            .findFirst()
                            .orElse("");
      return s.replaceFirst(prefix, "")
              .replaceAll(File.separator, ".");
    };

    return StreamSupport.stream(javaFileObjects.spliterator(), /* parallel */ true)
                        .filter(javaFileObject -> javaFileObject.getKind().equals(kind))
                        .map(FileObject::getName)
                        .map(fileObjectName -> fileObjectName.replace(".class", ""))
                        .map(mapToClassName)
                        .map(className -> Try.of(() -> Class.forName(className))
                                             .getOrElseThrow(asRuntimeException))
                        .collect(Collectors.toList());
  };

  @Test
  @DisplayName("should get classes recursively in given package")
  void test() {
    Collection<Class<?>> classes = findAllPackageClasses.apply(getClass().getPackage().getName());
    assertThat(classes).hasSizeGreaterThan(4);
    classes.stream().map(String::valueOf).forEach(log::info);
  }
}

PS: to simplify boilerplates for handling errors, etc, I'm using here vavr and lombok libraries

other implementations could be found in my GitHub daggerok/java-reflection-find-annotated-classes-or-methods repo

JPA - Persisting a One to Many relationship

One way to do that is to set the cascade option on you "One" side of relationship:

class Employee {
   // 

   @OneToMany(cascade = {CascadeType.PERSIST})
   private Set<Vehicles> vehicles = new HashSet<Vehicles>();

   //
}

by this, when you call

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

it will save the vehicles too.

Why can't I make a vector of references?

The component type of containers like vectors must be assignable. References are not assignable (you can only initialize them once when they are declared, and you cannot make them reference something else later). Other non-assignable types are also not allowed as components of containers, e.g. vector<const int> is not allowed.

Why do people say that Ruby is slow?

Obviously, talking about speed Ruby loses. Even though benchmark tests suggest that Ruby is not so much slower than PHP. But in return, you are getting easy-to-maintain DRY code, the best out of all frameworks in various languages.

For a small project, you wont feel any slowness (I mean until like <50K users) given that no complex calculations are used in the code, just the mainstream stuff.

For a bigger project, paying for resources pays off and is cheaper than developer wages. In addition, writing code on RoR turns out to be much faster than any other.

In 2014 this magnitude of speed difference you're talking about is for most websites insignificant.

How to print Unicode character in Python?

This fixes UTF-8 printing in python:

UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

Go to Internet Explorer, into options -> connections -> Lan settings. There should be an automatic config script option, copy the url, paste it into a browser, this downloads the config file, opened the file up in notepad and there will be a proxy address and a port number in there like 192.234.10.23:88 paste the address into the proxy field and the port (88) into the port field in the Android SDK manager Tools -> Options dialog.

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

I also faced the same situation. By setting following annotation above the property made it solve the exception prompted.

The Exception I faced.

Exception in thread "main" java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.model.Car_OneToMany

To overcome, the annotation I used.

    @OneToMany(cascade = {CascadeType.ALL})
    @Column(name = "ListOfCarsDrivenByDriver")
    private List<Car_OneToMany> listOfCarsBeingDriven = new ArrayList<Car_OneToMany>();

What made Hibernate throw the exception:

This exception is thrown at your console because the child object I attach to the parent object is not present in the database at that moment.

By providing @OneToMany(cascade = {CascadeType.ALL}) , it tells Hibernate to save them to the database while saving the parent object.

Disable Drag and Drop on HTML elements?

try this

$('#id').on('mousedown', function(event){
    event.preventDefault();
}

How to pass a value to razor variable from javascript variable?

here is my solution that works:

in my form i use:

@using (Html.BeginForm("RegisterOrder", "Account", FormMethod.Post, new { @class = "form", role = "form" }))
  {

   @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })

   @Html.HiddenFor(m => m.quantity, new { id = "quantity", Value = 0 })

  }

in my file.js I get the quantity from a GET request and pass the variable as follows to the form:

    $http({
        method: 'Get',
        url: "https://xxxxxxx.azurewebsites.net/api/quantity/" + usr
    })
        .success(function (data){

            setQuantity(data.number);

            function setQuantity(number) {
                $('#quantity').val(number);
            }

        });

unique() for more than one variable

How about using unique() itself?

df <- data.frame(yad = c("BARBIE", "BARBIE", "BAKUGAN", "BAKUGAN"),
                 per = c("AYLIK",  "AYLIK",  "2 AYLIK", "2 AYLIK"),
                 hmm = 1:4)

df
#       yad     per hmm
# 1  BARBIE   AYLIK   1
# 2  BARBIE   AYLIK   2
# 3 BAKUGAN 2 AYLIK   3
# 4 BAKUGAN 2 AYLIK   4

unique(df[c("yad", "per")])
#       yad     per
# 1  BARBIE   AYLIK
# 3 BAKUGAN 2 AYLIK

Multiple contexts with the same path error running web service in Eclipse using Tomcat

In your eclipse IDE on project explorer acess the server.xml like in:

enter image description here

And remove context tags with duplicates references for your project:

enter image description here

Check if a string is not NULL or EMPTY

I would define $Version as a string to start with

[string]$Version

and if it's a param you can use the code posted by Samselvaprabu or if you would rather not present your users with an error you can do something like

while (-not($version)){
    $version = Read-Host "Enter the version ya fool!"
}
$request += "/" + $version

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

Hi I know this topic is old but there is a much better way to differentiate an Array in Node.js from any other Object have a look at the docs.

var util = require('util');

util.isArray([]); // true
util.isArray({}); // false

var obj = {};
typeof obj === "Object" // true

How can I show line numbers in Eclipse?

On a Mac do this:

cmd + , or ADT -> Preferences 

Expand General -> Editors ->Text Editors

Check box: Show line numbers

enter image description here

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

JavaScript get element by name

document.getElementsByName("myInput")[0].value;

Get LatLng from Zip Code - Google Maps API

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>
<script>
    var latitude = '';
    var longitude = '';

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode(
    { 
       componentRestrictions: { 
           country: 'IN', 
           postalCode: '744102'
       } 
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            latitude = results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();
            console.log(latitude + ", " + longitude);
        } else {
            alert("Request failed.")
        }
    });
</script>

https://developers.google.com/maps/documentation/javascript/geocoding#ComponentFiltering

SSRS expression to format two decimal places does not show zeros

Please try the following code snippet,

IIF(Round(Avg(Fields!Vision_Score.Value)) = Avg(Fields!Vision_Score.Value), 
Format(Avg(Fields!Vision_Score.Value)), 
FORMAT(Avg(Fields!Vision_Score.Value),"##.##"))

hope it will help, Thank-you.

AngularJS : How do I switch views from a controller function?

This little function has served me well:

    //goto view:
    //useage -  $scope.gotoView("your/path/here", boolean_open_in_new_window)
    $scope.gotoView = function (st_view, is_newWindow)
    {

        console.log('going to view: ' + '#/' + st_view, $window.location);
        if (is_newWindow)
        {
            $window.open($window.location.origin + $window.location.pathname + '' + '#/' + st_view, '_blank');
        }
        else
        {
            $window.location.hash = '#/' + st_view;
        }


    };

You dont need the full path, just the view you are switching to

PHP : send mail in localhost

You will need to install a local mailserver in order to do this. If you want to send it to external e-mail addresses, it might end up in unwanted e-mails or it may not arrive at all.

A good mailserver which I use (I use it on Linux, but it's also available for Windows) is Axigen: http://www.axigen.com/mail-server/download/

You might need some experience with mailservers to install it, but once it works, you can do anything you want with it.

Real differences between "java -server" and "java -client"?

I've not noticed any difference in startup time between the 2, but clocked a very minimal improvement in application performance with "-server" (Solaris server, everyone using SunRays to run the app). That was under 1.5.

Reference — What does this symbol mean in PHP?

An overview of operators in PHP:


Logical Operators:

  • $a && $b : TRUE if both $a and $b are TRUE.
  • $a || $b : TRUE if either $a or $b is TRUE.
  • $a xor $b : TRUE if either $a or $b is TRUE, but not both.
  • ! $a : TRUE if $a is not TRUE.
  • $a and $b : TRUE if both $a and $b are TRUE.
  • $a or $b : TRUE if either $a or $b is TRUE.

Comparison operators:

  • $a == $b : TRUE if $a is equal to $b after type juggling.
  • $a === $b : TRUE if $a is equal to $b, and they are of the same type.
  • $a != $b : TRUE if $a is not equal to $b after type juggling.
  • $a <> $b : TRUE if $a is not equal to $b after type juggling.
  • $a !== $b : TRUE if $a is not equal to $b, or they are not of the same type.
  • $a < $b : TRUE if $a is strictly less than $b.
  • $a > $b : TRUE if $a is strictly greater than $b.
  • $a <= $b : TRUE if $a is less than or equal to $b.
  • $a >= $b : TRUE if $a is greater than or equal to $b.
  • $a <=> $b : An integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b. Available as of PHP 7.
  • $a ? $b : $c : if $a return $b else return $c (ternary operator)
  • $a ?? $c : Same as $a ? $a : $c (null coalescing operator - requires PHP>=7)

Arithmetic Operators:

  • -$a : Opposite of $a.
  • $a + $b : Sum of $a and $b.
  • $a - $b : Difference of $a and $b.
  • $a * $b : Product of $a and $b.
  • $a / $b : Quotient of $a and $b.
  • $a % $b : Remainder of $a divided by $b.
  • $a ** $b : Result of raising $a to the $b'th power (introduced in PHP 5.6)

Incrementing/Decrementing Operators:

  • ++$a : Increments $a by one, then returns $a.
  • $a++ : Returns $a, then increments $a by one.
  • --$a : Decrements $a by one, then returns $a.
  • $a-- : Returns $a, then decrements $a by one.

Bitwise Operators:

  • $a & $b : Bits that are set in both $a and $b are set.
  • $a | $b : Bits that are set in either $a or $b are set.
  • $a ^ $b : Bits that are set in $a or $b but not both are set.
  • ~ $a : Bits that are set in $a are not set, and vice versa.
  • $a << $b : Shift the bits of $a $b steps to the left (each step means "multiply by two")
  • $a >> $b : Shift the bits of $a $b steps to the right (each step means "divide by two")

String Operators:

  • $a . $b : Concatenation of $a and $b.

Array Operators:

  • $a + $b : Union of $a and $b.
  • $a == $b : TRUE if $a and $b have the same key/value pairs.
  • $a === $b : TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
  • $a != $b : TRUE if $a is not equal to $b.
  • $a <> $b : TRUE if $a is not equal to $b.
  • $a !== $b : TRUE if $a is not identical to $b.

Assignment Operators:

  • $a = $b : The value of $b is assigned to $a
  • $a += $b : Same as $a = $a + $b
  • $a -= $b : Same as $a = $a - $b
  • *$a = $b : Same as $a = $a * $b
  • $a /= $b : Same as $a = $a / $b
  • $a %= $b : Same as $a = $a % $b
  • **$a = $b : Same as $a = $a ** $b
  • $a .= $b : Same as $a = $a . $b
  • $a &= $b : Same as $a = $a & $b
  • $a |= $b : Same as $a = $a | $b
  • $a ^= $b : Same as $a = $a ^ $b
  • $a <<= $b : Same as $a = $a << $b
  • $a >>= $b : Same as $a = $a >> $b
  • $a ??= $b : The value of $b is assigned to $a if $a is null or not defined (null coalescing assignment operator - requires PHP>=7.4)

Note

and operator and or operator have lower precedence than assignment operator =.

This means that $a = true and false; is equivalent to ($a = true) and false.

In most cases you will probably want to use && and ||, which behave in a way known from languages like C, Java or JavaScript.

Python : Trying to POST form using requests

Send a POST request with content type = 'form-data':

import requests
files = {
    'username': (None, 'myusername'),
    'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)

HTML button opening link in new tab

With Bootstrap you can use an anchor like a button.

<a class="btn btn-success" href="https://www.google.com" target="_blank">Google</a>

And use target="_blank" to open the link in a new tab.

Android on-screen keyboard auto popping up

InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService);
        imm.ShowSoftInput(_enterPin.FindFocus(), 0);

*This is for Android.xamarin and FindFocus()-it searches for the view in hierarchy rooted at this view that currently has focus,as i have _enterPin.RequestFocus() before the above code thus it shows keyboard for _enterPin EditText *

How to select/get drop down option in Selenium 2

This is the code to select value from the drop down

The value for selectlocator will be the xpath or name of dropdown box, and for optionLocator will have the value to be selected from the dropdown box.

public static boolean select(final String selectLocator,
        final String optionLocator) {
    try {
        element(selectLocator).clear();
        element(selectLocator).sendKeys(Keys.PAGE_UP);
        for (int k = 0; k <= new Select(element(selectLocator))
                .getOptions().size() - 1; k++) {
            combo1.add(element(selectLocator).getValue());
            element(selectLocator).sendKeys(Keys.ARROW_DOWN);
        }
        if (combo1.contains(optionLocator)) {
            element(selectLocator).clear();
            new Select(element(selectLocator)).selectByValue(optionLocator);
            combocheck = element(selectLocator).getValue();
            combo = "";

            return true;
        } else {
            element(selectLocator).clear();
            combo = "The Value " + optionLocator
                    + " Does Not Exist In The Combobox";
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        errorcontrol.add(e.getMessage());
        return false;
    }
}



private static RenderedWebElement element(final String locator) {
    try {

        return (RenderedWebElement) drivers.findElement(by(locator));
    } catch (Exception e) {
        errorcontrol.add(e.getMessage());
        return (RenderedWebElement) drivers.findElement(by(locator));
    }
}

Thanks,

Rekha.

How to embed a YouTube channel into a webpage

YouTube supports a fairly easy to use iframe and url interface to embed videos, playlists and all user uploads to your channel: https://developers.google.com/youtube/player_parameters

For example this HTML will embed a player loaded with a playlist of all the videos uploaded to your channel. Replace YOURCHANNELNAME with the actual name of your channel:

<iframe src="http://www.youtube.com/embed/?listType=user_uploads&list=YOURCHANNELNAME" width="480" height="400"></iframe>

Go doing a GET request and building the Querystring

As a commenter mentioned you can get Values from net/url which has an Encode method. You could do something like this (req.URL.Query() returns the existing url.Values)

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
)

func main() {
    req, err := http.NewRequest("GET", "http://api.themoviedb.org/3/tv/popular", nil)
    if err != nil {
        log.Print(err)
        os.Exit(1)
    }

    q := req.URL.Query()
    q.Add("api_key", "key_from_environment_or_flag")
    q.Add("another_thing", "foo & bar")
    req.URL.RawQuery = q.Encode()

    fmt.Println(req.URL.String())
    // Output:
    // http://api.themoviedb.org/3/tv/popular?another_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}

http://play.golang.org/p/L5XCrw9VIG

Hibernate Annotations - Which is better, field or property access?

That really depends on a specific case -- both options are available for a reason. IMO it boils down to three cases:

  1. setter has some logic that should not be executed at the time of loading an instance from a database; for example, some value validation happens in the setter, however the data coming from db should be valid (otherwise it would not get there (: ); in this case field access is most appropriate;
  2. setter has some logic that should always be invoked, even during loading of an instance from db; for example, the property being initialised is used in computation of some calculated field (e.g. property -- a monetary amount, calculated property -- a total of several monetary properties of the same instance); in this case property access is required.
  3. None of the above cases -- then both options are applicable, just stay consistent (e.i. if field access is the choice in this situation then use it all the time in similar situation).

How to pass parameters to maven build using pom.xml?

We can Supply parameter in different way after some search I found some useful

<plugin>
  <artifactId>${release.artifactId}</artifactId>
  <version>${release.version}-${release.svm.version}</version>...

...

Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .

While Running build we need supply value for those parameter as follows.

RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74

Here I am supplying

release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74

It worked for me. Thanks

img tag displays wrong orientation

Until CSS: image-orientation:from-image; is more universally supported we are doing a server side solution with python. Here's the gist of it. You check the exif data for orientation, then rotate the image accordingly and resave.

We prefer this solution over client side solutions as it does not require loading extra libraries client side, and this operation only has to happen one time on file upload.

if fileType == "image":
    exifToolCommand = "exiftool -j '%s'" % filePath
    exif = json.loads(subprocess.check_output(shlex.split(exifToolCommand), stderr=subprocess.PIPE))
    if 'Orientation' in exif[0]:
        findDegrees, = re.compile("([0-9]+)").search(exif[0]['Orientation']).groups()
        if findDegrees:
            rotateDegrees = int(findDegrees)
            if 'CW' in exif[0]['Orientation'] and 'CCW' not in exif[0]['Orientation']:
                rotateDegrees = rotateDegrees * -1
            # rotate image
            img = Image.open(filePath)
            img2 = img.rotate(rotateDegrees)
            img2.save(filePath)

How can I get the timezone name in JavaScript?

Most upvoted answer is probably the best way to get the timezone, however, Intl.DateTimeFormat().resolvedOptions().timeZone returns IANA timezone name by definition, which is in English.

If you want the timezone's name in current user's language, you can parse it from Date's string representation like so:

_x000D_
_x000D_
function getTimezoneName() {_x000D_
  const today = new Date();_x000D_
  const short = today.toLocaleDateString(undefined);_x000D_
  const full = today.toLocaleDateString(undefined, { timeZoneName: 'long' });_x000D_
_x000D_
  // Trying to remove date from the string in a locale-agnostic way_x000D_
  const shortIndex = full.indexOf(short);_x000D_
  if (shortIndex >= 0) {_x000D_
    const trimmed = full.substring(0, shortIndex) + full.substring(shortIndex + short.length);_x000D_
    _x000D_
    // by this time `trimmed` should be the timezone's name with some punctuation -_x000D_
    // trim it from both sides_x000D_
    return trimmed.replace(/^[\s,.\-:;]+|[\s,.\-:;]+$/g, '');_x000D_
_x000D_
  } else {_x000D_
    // in some magic case when short representation of date is not present in the long one, just return the long one as a fallback, since it should contain the timezone's name_x000D_
    return full;_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log(getTimezoneName());
_x000D_
_x000D_
_x000D_

Tested in Chrome and Firefox.

Ofcourse, this will not work as intended in some of the environments. For example, node.js returns a GMT offset (e.g. GMT+07:00) instead of a name. But I think it's still readable as a fallback.

P.S. Won't work in IE11, just as the Intl... solution.

How do I remove javascript validation from my eclipse project?

In addition, if you are using Tern eclipse IDE or IBM Node.js Tools for Eclipse, you may need to disable JSHint and other libraries that you don't want.

To disable this, Project Properties > Tern > Modules > JSHint or any other library that you don't want. enter image description here

Request UAC elevation from within a Python script?

You can make a shortcut somewhere and as the target use: python yourscript.py then under properties and advanced select run as administrator.

When the user executes the shortcut it will ask them to elevate the application.

How do I add an integer value with javascript (jquery) to a value that's returning a string?

The integer is being converted into a string rather than vice-versa. You want:

var newValue = parseInt(currentValue) + 1

how to rename an index in a cluster?

You can use REINDEX to do that.

Reindex does not attempt to set up the destination index. It does not copy the settings of the source index. You should set up the destination index prior to running a _reindex action, including setting up mappings, shard counts, replicas, etc.

  1. First copy the index to a new name
POST /_reindex
{
  "source": {
    "index": "twitter"
  },
  "dest": {
    "index": "new_twitter"
  }
}
  1. Now delete the Index
DELETE /twitter

How do I implement charts in Bootstrap?

You can use a 3rd party library like Shield UI for charting - that is tested and works well on all legacy and new web browsers and devices.

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

Distinct and Group By generally do the same kind of thing, for different purposes... They both create a 'working" table in memory based on the columns being Grouped on, (or selected in the Select Distinct clause) - and then populate that working table as the query reads data, adding a new "row" only when the values indicate the need to do so...

The only difference is that in the Group By there are additional "columns" in the working table for any calculated aggregate fields, like Sum(), Count(), Avg(), etc. that need to updated for each original row read. Distinct doesn't have to do this... In the special case where you Group By only to get distinct values, (And there are no aggregate columns in output), then it is probably exactly the same query plan.... It would be interesting to review the query execution plan for the two options and see what it did...

Certainly Distinct is the way to go for readability if that is what you are doing (When your purpose is to eliminate duplicate rows, and you are not calculating any aggregate columns)

If statement within Where clause

You can't use IF like that. You can do what you want with AND and OR:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE ((status_flag = STATUS_ACTIVE   AND t.status = 'A')
     OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
     OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
     OR (source_flag = SOURCE_USER     AND t.business_unit = 'users'))
   AND t.first_name LIKE firstname
   AND t.last_name  LIKE lastname
   AND t.employid   LIKE employeeid;

How to pull remote branch from somebody else's repo

No, you don't need to add them as a remote. That would be clumbersome and a pain to do each time.

Grabbing their commits:

git fetch [email protected]:theirusername/reponame.git theirbranch:ournameforbranch

This creates a local branch named ournameforbranch which is exactly the same as what theirbranch was for them. For the question example, the last argument would be foo:foo.

Note :ournameforbranch part can be further left off if thinking up a name that doesn't conflict with one of your own branches is bothersome. In that case, a reference called FETCH_HEAD is available. You can git log FETCH_HEAD to see their commits then do things like cherry-picked to cherry pick their commits.

Pushing it back to them:

Oftentimes, you want to fix something of theirs and push it right back. That's possible too:

git fetch [email protected]:theirusername/reponame.git theirbranch
git checkout FETCH_HEAD

# fix fix fix

git push [email protected]:theirusername/reponame.git HEAD:theirbranch

If working in detached state worries you, by all means create a branch using :ournameforbranch and replace FETCH_HEAD and HEAD above with ournameforbranch.

how to format date in Component of angular 5

Another option can be using built in angular formatDate function. I am assuming that you are using reactive forms. Here todoDate is a date input field in template.

import {formatDate} from '@angular/common';

this.todoForm.controls.todoDate.setValue(formatDate(this.todo.targetDate, 'yyyy-MM-dd', 'en-US'));

How to determine the encoding of text?

Depending on your platform, I just opt to use the linux shell file command. This works for me since I am using it in a script that exclusively runs on one of our linux machines.

Obviously this isn't an ideal solution or answer, but it could be modified to fit your needs. In my case I just need to determine whether a file is UTF-8 or not.

import subprocess
file_cmd = ['file', 'test.txt']
p = subprocess.Popen(file_cmd, stdout=subprocess.PIPE)
cmd_output = p.stdout.readlines()
# x will begin with the file type output as is observed using 'file' command
x = cmd_output[0].split(": ")[1]
return x.startswith('UTF-8')

Regex select all text between tags

Tag can be completed in another line. This is why \n needs to be added.

<PRE>(.|\n)*?<\/PRE>

Getting visitors country from their IP

You could use my service: https://SmartIP.io , which provides full country names and city names of any IP address. We also expose timezones, currency, proxy detection, TOR nodes detection and Crypto detection.

You just need to signup and get a free API key which allows for 250,000 requests per month.

Using the official PHP library, the API call becomes:

$apiKey = "your API key";
$smartIp = new SmartIP($apiKey);
$response = $smartIp->requestIPData("8.8.8.8");

echo "\nstatus code: " . $response->{"status-code"};
echo "\ncountry name: " . $response->country->{"country-name"};

Check the API documentation for more info: https://smartip.io/docs

Assigning the return value of new by reference is deprecated

In PHP5 this idiom is deprecated

$obj_md =& new MDB2();

You sure you've not missed an ampersand in your sample code? That would generate the warning you state, but it is not required and can be removed.

To see why this idiom was used in PHP4, see this manual page (note that PHP4 is long dead and this link is to an archived version of the relevant page)

Remove element from JSON Object

To iterate through the keys of an object, use a for .. in loop:

for (var key in json_obj) {
    if (json_obj.hasOwnProperty(key)) {
        // do something with `key'
    }
}

To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.

Removing a property of an object can be done by using the delete keyword:

var someObj = {
    "one": 123,
    "two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }

Documentation:

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

I had this same issue and wondered why it didn't happen with a bitbucket repo that was cloned with https. Looking into it a bit I found that the config for the BB repo had a URL that included my username. So I manually edited the config for my GH repo like so and voila, no more username prompt. I'm on Windows.

Edit your_repo_dir/.git/config (remember: .git folder is hidden)

Change:

https://github.com/WEMP/project-slideshow.git

to:

https://*username*@github.com/WEMP/project-slideshow.git

Save the file. Do a git pull to test it.

The proper way to do this is probably by using git bash commands to edit the setting, but editing the file directly didn't seem to be a problem.

Get my phone number in android

As Answered here

Use below code :

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

In AndroidManifest.xml, give the following permission:

 <uses-permission android:name="android.permission.READ_PHONE_STATE"/> 

But remember, this code does not always work, since Cell phone number is dependent on the SIM Card and the Network operator / Cell phone carrier.

Also, try checking in Phone--> Settings --> About --> Phone Identity, If you are able to view the Number there, the probability of getting the phone number from above code is higher. If you are not able to view the phone number in the settings, then you won't be able to get via this code!

Suggested Workaround:

  1. Get the user's phone number as manual input from the user.
  2. Send a code to the user's mobile number via SMS.
  3. Ask user to enter the code to confirm the phone number.
  4. Save the number in sharedpreference.

Do the above 4 steps as one time activity during the app's first launch. Later on, whenever phone number is required, use the value available in shared preference.

Font size relative to the user's screen resolution?

You can use em, %, px. But in combination with media-queries See this Link to learn about media-queries. Also, CSS3 have some new values for sizing things relative to the current viewport size: vw, vh, and vmin. See link about that.

What is the SQL command to return the field names of a table?

SQL-92 standard defines INFORMATION_SCHEMA which conforming rdbms's like MS SQL Server support. The following works for MS SQL Server 2000/2005/2008 and MySql 5 and above

select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'myTable'

MS SQl Server Specific:

exec sp_help 'myTable'

This solution returns several result sets within which is the information you desire, where as the former gives you exactly what you want.

Also just for completeness you can query the sys tables directly. This is not recommended as the schema can change between versions of SQL Server and INFORMATION_SCHEMA is a layer of abstraction above these tables. But here it is anyway for SQL Server 2000

select [name] from dbo.syscolumns where id = object_id(N'[dbo].[myTable]')

Error: unable to verify the first certificate in nodejs

Another approach to solve this is to use the following module.

node_extra_ca_certs_mozilla_bundle

This module can work without any code modification by generating a PEM file that includes all root and intermediate certificates trusted by Mozilla. You can use the following environment variable (Works with Nodejs v7.3+),

NODE_EXTRA_CA_CERTS

To generate the PEM file to use with the above environment variable. You can install the module using:

npm install --save node_extra_ca_certs_mozilla_bundle

and then launch your node script with an environment variable.

NODE_EXTRA_CA_CERTS=node_modules/node_extra_ca_certs_mozilla_bundle/ca_bundle/ca_intermediate_root_bundle.pem node your_script.js

Other ways to use the generated PEM file are available at:

https://github.com/arvind-agarwal/node_extra_ca_certs_mozilla_bundle

NOTE: I am the author of the above module.

How to change PHP version used by composer

Old question I know, but just to add some additional information:

  • WAMP is used only on Microsoft Windows Operating Systems.
  • Changing the version of PHP used through the left-click -> PHP -> Version menu changes the version used by Apache to server your site.
  • Changing the version of PHP used through the right-click -> Tools -> Change PHP CLI Version menu changes the version used by WAMP's PHP CLI.

Note: It is important to understand that the "PHP CLI Version" is used by WAMP's own internal PHP scripts. This "PHP CLI Version" has nothing to do with the version you wish to use for your scripts, Composer or anything else.

For your scripts to work with the version you require, you need to add it's path to the Users Environmental Path. You could add it to the Systems environmental Path but the Users Path is the recommended option.

From WAMP v3.1.2, it would display an error when it detect reference to a PHP path in the System or User Environmental Path. This was to stop confusion such as you were experiencing. Since v3.1.7 the display of this error can now be optionally displayed through a selection in the WampSettings menu.

As indicated in previous answers, adding an installed PHP path (such as "C:\wamp64\bin\php\php7.2.30") to the Users Environmental Path is the correct approach. PS: As the value of the Users Environmental Path is a string, all paths added must be separated with a semi-colon (;)

After experiencing the exact same problem (IE: Choosing which version of PHP I wanted Composer to use), I created a script which could easily and rapidly switch between PHP CLI Versions depending on what project I was working on.

The Windows batch script "WampServer-PHP-CLI-Version-Changer" can be found at https://github.com/custom-dev-tools/WampServer-PHP-CLI-Version-Changer

I hope this helps others.

Good luck.

One-liner if statements, how to convert this if-else-statement

return (expression) ? value1 : value2;

If value1 and value2 are actually true and false like in your example, you may as well just

return expression;

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

MultipartException: Current request is not a multipart request

in ARC (advanced rest client) - specify as below to make it work Content-Type multipart/form-data (this is header name and header value) this allows you to add form data as key and values you can specify you field name now as per your REST specification and select your file to upload from file selector.

Best practices to test protected methods with PHPUnit

I'd like to propose a slight variation to getMethod() defined in uckelman's answer.

This version changes getMethod() by removing hard-coded values and simplifying usage a little. I recommend adding it to your PHPUnitUtil class as in the example below or to your PHPUnit_Framework_TestCase-extending class (or, I suppose, globally to your PHPUnitUtil file).

Since MyClass is being instantiated anyways and ReflectionClass can take a string or an object...

class PHPUnitUtil {
    /**
     * Get a private or protected method for testing/documentation purposes.
     * How to use for MyClass->foo():
     *      $cls = new MyClass();
     *      $foo = PHPUnitUtil::getPrivateMethod($cls, 'foo');
     *      $foo->invoke($cls, $...);
     * @param object $obj The instantiated instance of your class
     * @param string $name The name of your private/protected method
     * @return ReflectionMethod The method you asked for
     */
    public static function getPrivateMethod($obj, $name) {
      $class = new ReflectionClass($obj);
      $method = $class->getMethod($name);
      $method->setAccessible(true);
      return $method;
    }
    // ... some other functions
}

I also created an alias function getProtectedMethod() to be explicit what is expected, but that one's up to you.

Vue JS mounted()

Abstract your initialization into a method, and call the method from mounted and wherever else you want.

new Vue({
  methods:{
    init(){
      //call API
      //Setup game
    }
  },
  mounted(){
    this.init()
  }
})

Then possibly have a button in your template to start over.

<button v-if="playerWon" @click="init">Play Again</button>

In this button, playerWon represents a boolean value in your data that you would set when the player wins the game so the button appears. You would set it back to false in init.

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

Extending Yoni Gibbs's answer, if you are in an android project using retrofit and configure serialization with Jackson you can do these things in order to deserialization works as expected with kotlin's data class.

In your build gradle import:

implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.11.+"

Then, your implementation of retrofit:

val serverURL = "http://localhost:8080/api/v1"

val objectMapper = ObjectMapper()
objectMapper.registerModule(KotlinModule())
//Only if you are using Java 8's Time API too, require jackson-datatype-jsr310
objectMapper.registerModule(JavaTimeModule())

Retrofit.Builder()
    .baseUrl(serverURL)
    .client(
        OkHttpClient.Builder()
           .readTimeout(1, TimeUnit.MINUTES)//No mandatory
            .connectTimeout(1, TimeUnit.MINUTES)//No mandatory
            .addInterceptor(UnauthorizedHandler())//No mandatory
            .build())
    .addConverterFactory(
                JacksonConverterFactory.create(objectMapper)
            )
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .build()

Data class:

@JsonIgnoreProperties(ignoreUnknown = true)
data class Task(val id: Int,
                val name: String,
                @JsonSerialize(using = LocalDateTimeSerializer::class)
                @JsonDeserialize(using = LocalDateTimeDeserializer::class)
                val specificDate: LocalDateTime?,
                var completed: Boolean,
                val archived: Boolean,
                val taskListId: UUID?

Converts scss to css

You can use sass /sassFile.scss /cssFile.css

Attention: Before using sass command you must install ruby and then install sass.

For installing sass, after ruby installation type gem install sass in your Terminal

Hint: sass compile SCSS files

Changing route doesn't scroll to top in the new page

This code worked great for me .. I hope it will also work great for you .. All you have to do is just inject $anchorScroll to your run block and apply listener function to the rootScope like I have done in the below example ..

 angular.module('myAngularApp')
.run(function($rootScope, Auth, $state, $anchorScroll){
    $rootScope.$on("$locationChangeSuccess", function(){
        $anchorScroll();
    });

Here's the calling order of Angularjs Module:

  1. app.config()
  2. app.run()
  3. directive's compile functions (if they are found in the dom)
  4. app.controller()
  5. directive's link functions (again, if found)

RUN BLOCK get executed after the injector is created and are used to kickstart the application.. it means when you redirected to the new route view ,the listener in the run block calls the

$anchorScroll()

and you can now see the scroll starts to the top with the new routed view :)

SQL Server default character encoding

I think this is worthy of a separate answer: although internally unicode data is stored as UTF-16 in Sql Server this is the Little Endian flavour, so if you're calling the database from an external system, you probably need to specify UTF-16LE.

How to perform a sum of an int[] array

Once is out (March 2014) you'll be able to use streams:

int sum = IntStream.of(a).sum();

or even

int sum = IntStream.of(a).parallel().sum();

Perform commands over ssh with Python

Have a look at spurplus, a wrapper we developed around spur that provides type annotations and some minor gimmicks (reconnecting SFTP, md5 etc.): https://pypi.org/project/spurplus/

How to Auto resize HTML table cell to fit the text size

You can try this:

HTML

<table>
    <tr>
        <td class="shrink">element1</td>
        <td class="shrink">data</td>
        <td class="shrink">junk here</td>
        <td class="expand">last column</td>
    </tr>
    <tr>
        <td class="shrink">elem</td>
        <td class="shrink">more data</td>
        <td class="shrink">other stuff</td>
        <td class="expand">again, last column</td>
    </tr>
    <tr>
        <td class="shrink">more</td>
        <td class="shrink">of </td>
        <td class="shrink">these</td>
        <td class="expand">rows</td>
    </tr>
</table>

CSS

table {
    border: 1px solid green;
    border-collapse: collapse;
    width:100%;
}

table td {
    border: 1px solid green;
}

table td.shrink {
    white-space:nowrap
}
table td.expand {
    width: 99%
}

How can I use goto in Javascript?

Sure, using the switch construct you can simulate goto in JavaScript. Unfortunately, the language doesn't provide goto, but this is a good enough of a replacement.

let counter = 10
function goto(newValue) {
  counter = newValue
}
while (true) {
  switch (counter) {
    case 10: alert("RINSE")
    case 20: alert("LATHER")
    case 30: goto(10); break
  }
}

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

Try without command mvn in the command line. Example:

From:

mvn clean install jetty:run

To:

clean install jetty:run

Allow multiple roles to access controller action

One possible simplification would be to subclass AuthorizeAttribute:

public class RolesAttribute : AuthorizeAttribute
{
    public RolesAttribute(params string[] roles)
    {
        Roles = String.Join(",", roles);
    }
}

Usage:

[Roles("members", "admin")]

Semantically it is the same as Jim Schmehil's answer.

Measure the time it takes to execute a t-sql query

Another way is using a SQL Server built-in feature named Client Statistics which is accessible through Menu > Query > Include Client Statistics.

You can run each query in separated query window and compare the results which is given in Client Statistics tab just beside the Messages tab.

For example in image below it shows that the average time elapsed to get the server reply for one of my queries is 39 milliseconds.

Result

You can read all 3 ways for acquiring execution time in here. You may even need to display Estimated Execution Plan ctrlL for further investigation about your query.

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

downgrade node to 0.10.36

  sudo npm cache clean -f
  sudo npm install -g n
  sudo n 0.10.36

upgrade node to stable v

  sudo npm cache clean -f
  sudo npm install -g n
  sudo n stable

How do I loop through children objects in javascript?

The backwards compatible version (IE9+) is

var parent = document.querySelector(selector);
Array.prototype.forEach.call(parent.children, function(child, index){
  // Do stuff
});

The es6 way is

const parent = document.querySelector(selector);
Array.from(parent.children).forEach((child, index) => {
  // Do stuff
});

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

Right Click on Project, Properties ---> Java Compiler ( on same page change compiler Compliance Level to 1.6 (or) 1.7 (or) 1.8 ( match with your JAVA_HOME)

Remove Object from Array using JavaScript

You can use map function also.

someArray = [{name:"Kristian", lines:"2,5,10"},{name:"John",lines:"1,19,26,96"}];
newArray=[];
someArray.map(function(obj, index){
    if(obj.name !== "Kristian"){
       newArray.push(obj);
    }
});
someArray = newArray;
console.log(someArray);